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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ExportProjectWizardPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.exportproject/src/net/heartsome/cat/ts/exportproject/wizards/ExportProjectWizardPage.java | package net.heartsome.cat.ts.exportproject.wizards;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import net.heartsome.cat.ts.exportproject.resource.Messages;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages;
import org.eclipse.ui.internal.wizards.datatransfer.IDataTransferHelpContextIds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 导出项目向导页面
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class ExportProjectWizardPage extends WizardFileSystemResourceExportPage2 {
private final static String STORE_DESTINATION_NAMES_ID = "ExportProjectWizardPage.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_CREATE_STRUCTURE_ID = "ExportProjectWizardPage.STORE_CREATE_STRUCTURE_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS_CONTENTS_ID = "ExportProjectWizardPage.STORE_COMPRESS_CONTENTS_ID"; //$NON-NLS-1$
/**
* Create an instance of this class.
* @param name
* java.lang.String
*/
protected ExportProjectWizardPage(String name, IStructuredSelection selection) {
super(name, selection);
setTitle(Messages.getString("wizard.ExportProjectWizardPage.title"));
setDescription(Messages.getString("wizard.ExportProjectWizardPage.desc"));
}
/**
* Create an instance of this class
* @param selection
* the selection
*/
public ExportProjectWizardPage(IStructuredSelection selection) {
this("exportWizardPage", selection); //$NON-NLS-1$
}
/**
* (non-Javadoc) Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem()
.setHelp(getControl(), IDataTransferHelpContextIds.ZIP_FILE_EXPORT_WIZARD_PAGE);
}
/**
* Returns a boolean indicating whether the directory portion of the passed pathname is valid and available for use.
*/
protected boolean ensureTargetDirectoryIsValid(String fullPathname) {
int separatorIndex = fullPathname.lastIndexOf(File.separator);
if (separatorIndex == -1) {
return true;
}
return ensureTargetIsValid(new File(fullPathname.substring(0, separatorIndex)));
}
/**
* Returns a boolean indicating whether the passed File handle is is valid and available for use.
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory()) {
displayErrorDialog(DataTransferMessages.ZipExport_mustBeFile);
giveFocusToDestination();
return false;
}
if (targetFile.exists()) {
if (targetFile.canWrite()) {
if (!queryYesNoQuestion(DataTransferMessages.ZipExport_alreadyExists)) {
return false;
}
} else {
displayErrorDialog(DataTransferMessages.ZipExport_alreadyExistsError);
giveFocusToDestination();
return false;
}
}
return true;
}
/**
* Ensures that the target output file and its containing directory are both valid and able to be used. Answer a
* boolean indicating validity.
*/
protected boolean ensureTargetIsValid() {
String targetPath = getDestinationValue();
if (!ensureTargetDirectoryIsValid(targetPath)) {
return false;
}
if (!ensureTargetFileIsValid(new File(targetPath))) {
return false;
}
return true;
}
/**
* Export the passed resource and recursively export all of its child resources (iff it's a container). Answer a
* boolean indicating success.
*/
protected boolean executeExportOperation(ArchiveFileExportOperation2 op) {
op.setCreateLeadupStructure(true);
op.setUseCompression(true);
op.setUseTarFormat(false);
op.setExportTb(isExportSQLiteTBs());
op.setExportTm(isExportSQLiteTMs());
try {
getContainer().run(true, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
displayErrorDialog(e.getTargetException());
return false;
}
IStatus status = op.getStatus();
if (!status.isOK()) {
ErrorDialog.openError(getContainer().getShell(), DataTransferMessages.DataTransfer_exportProblems, null, // no
// special
// message
status);
return false;
}
return true;
}
private static final Logger LOGGER = LoggerFactory.getLogger(ExportProjectWizardPage.class);
/**
* The Finish button was pressed. Try to do the required work now and answer a boolean indicating success. If false
* is returned then the wizard will not close.
* @returns boolean
*/
public boolean finish() {
List resourcesToExport = getWhiteCheckedResources();
List defaultExportItems = getDefaultExportItems();
boolean isContain = false;
boolean isBelongToSameProject = false;
for (Object defaultObj : defaultExportItems) {
if (defaultObj instanceof IResource) {
try {
((IResource) defaultObj).refreshLocal(IResource.DEPTH_ZERO, null);
} catch (CoreException e) {
e.printStackTrace();
LOGGER.error("", e);
}
String defaultPath = ((IResource) defaultObj).getFullPath().toOSString();
for (Object obj : resourcesToExport) {
if (obj instanceof IProject) {
String path = ((IProject) obj).getFullPath().toOSString();
if (defaultPath.equals(path + System.getProperty("file.separator") + ".config")
|| defaultPath.equals(path + System.getProperty("file.separator") + ".project")) {
isContain = true;
isBelongToSameProject = true;
break;
}
}
if (obj instanceof IResource) {
String path = ((IResource) obj).getFullPath().toOSString();
String projectPath = ((IResource) obj).getProject().getFullPath().toOSString();
String defaultProjectPath = ((IResource) defaultObj).getProject().getFullPath().toOSString();
if (projectPath.equals(defaultProjectPath)) {
isBelongToSameProject = true;
}
if (path.equals(defaultPath)) {
isContain = true;
break;
}
}
}
if (!isContain && isBelongToSameProject) {
resourcesToExport.add(defaultObj);
} else {
isContain = false;
}
}
isBelongToSameProject = false;
}
if (!ensureTargetIsValid()) {
return false;
}
// Save dirty editors if possible but do not stop if not all are saved
saveDirtyEditors();
// about to invoke the operation so save our state
saveWidgetValues();
return executeExportOperation(new ArchiveFileExportOperation2(null, resourcesToExport, getDestinationValue()));
}
/**
* Answer the string to display in the receiver as the destination type
*/
protected String getDestinationLabel() {
return DataTransferMessages.ArchiveExport_destinationLabel;
}
/**
* Answer the contents of self's destination specification widget. If this value does not have a suffix then add it
* first.
*/
protected String getDestinationValue() {
String idealSuffix = getOutputSuffix();
String destinationText = super.getDestinationValue();
// only append a suffix if the destination doesn't already have a . in
// its last path segment.
// Also prevent the user from selecting a directory. Allowing this will
// create a ".zip" file in the directory
if (destinationText.length() != 0 && !destinationText.endsWith(File.separator)) {
int dotIndex = destinationText.lastIndexOf('.');
if (dotIndex != -1) {
// the last path seperator index
int pathSepIndex = destinationText.lastIndexOf(File.separator);
if (pathSepIndex != -1 && dotIndex < pathSepIndex) {
destinationText += idealSuffix;
}
} else {
destinationText += idealSuffix;
}
}
return destinationText;
}
/**
* Answer the suffix that files exported from this wizard should have. If this suffix is a file extension (which is
* typically the case) then it must include the leading period character.
*/
protected String getOutputSuffix() {
// if (zipFormatButton.getSelection()) {
return ".zip"; //$NON-NLS-1$
// } else if (compressContentsCheckbox.getSelection()) {
// return ".tar.gz"; //$NON-NLS-1$
// } else {
// return ".tar"; //$NON-NLS-1$
// }
}
/**
* Open an appropriate destination browser so that the user can specify a source to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.SAVE | SWT.SHEET);
dialog.setFilterExtensions(new String[] { "*.hszip", "*" }); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setText(DataTransferMessages.ArchiveExport_selectDestinationTitle);
String currentSourceString = getDestinationValue();
int lastSeparatorIndex = currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
}
String selectedFileName = dialog.open();
if (selectedFileName != null) {
setErrorMessage(null);
setDestinationValue(selectedFileName);
if (getWhiteCheckedResources().size() > 0) {
setDescription(null);
}
}
}
/**
* Hook method for saving widget values for restoration by the next instance of this class.
*/
protected void internalSaveWidgetValues() {
super.internalSaveWidgetValues();
// update directory names history
IDialogSettings settings = getDialogSettings();
if (settings != null) {
String[] directoryNames = settings.getArray(STORE_DESTINATION_NAMES_ID);
if (directoryNames == null) {
directoryNames = new String[0];
}
directoryNames = addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES_ID, directoryNames);
settings.put(STORE_CREATE_STRUCTURE_ID, true);
settings.put(STORE_COMPRESS_CONTENTS_ID, true);
}
}
/**
* Hook method for restoring widget values to the values that they held last time this wizard was used to
* completion.
*/
protected void restoreWidgetValues() {
super.restoreWidgetValues();
IDialogSettings settings = getDialogSettings();
if (settings != null) {
String[] directoryNames = settings.getArray(STORE_DESTINATION_NAMES_ID);
if (directoryNames == null || directoryNames.length == 0) {
return; // ie.- no settings stored
}
// destination
setDestinationValue(directoryNames[0]);
// for (int i = 0; i < directoryNames.length; i++) {
// addDestinationItem(directoryNames[i]);
// }
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.wizards.datatransfer.WizardFileSystemResourceExportPage1#destinationEmptyMessage()
*/
protected String destinationEmptyMessage() {
return DataTransferMessages.ArchiveExport_destinationEmpty;
}
/**
* Answer a boolean indicating whether the receivers destination specification widgets currently all contain valid
* values.
*/
protected boolean validateDestinationGroup() {
// String destinationValue = getDestinationValue();
// if (destinationValue.endsWith(".tar")) { //$NON-NLS-1$
// compressContentsCheckbox.setSelection(false);
// targzFormatButton.setSelection(true);
// zipFormatButton.setSelection(false);
// } else if (destinationValue.endsWith(".tar.gz") //$NON-NLS-1$
// || destinationValue.endsWith(".tgz")) { //$NON-NLS-1$
// compressContentsCheckbox.setSelection(true);
// targzFormatButton.setSelection(true);
// zipFormatButton.setSelection(false);
// } else if (destinationValue.endsWith(".zip")) { //$NON-NLS-1$
// zipFormatButton.setSelection(true);
// targzFormatButton.setSelection(false);
// }
return super.validateDestinationGroup();
}
}
| 12,011 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportProjectWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.exportproject/src/net/heartsome/cat/ts/exportproject/wizards/ExportProjectWizard.java | package net.heartsome.cat.ts.exportproject.wizards;
import net.heartsome.cat.ts.exportproject.resource.Messages;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.slf4j.LoggerFactory;
/**
* 导出项目向导
* @author peason
* @version
* @since JDK1.6
*/
public class ExportProjectWizard extends Wizard implements IExportWizard {
private IStructuredSelection selection;
private ExportProjectWizardPage page;
public ExportProjectWizard() {
setWindowTitle(Messages.getString("wizard.ExportProjectWizard.title"));
setNeedsProgressMonitor(true);
IDialogSettings workbenchSettings = WorkbenchPlugin.getDefault().getDialogSettings();
IDialogSettings section = workbenchSettings
.getSection("ExportProjectWizard");//$NON-NLS-1$
if (section == null) {
section = workbenchSettings.addNewSection("ExportProjectWizard");//$NON-NLS-1$
}
setDialogSettings(section);
}
public void init(IWorkbench workbench, IStructuredSelection selection) {
}
@Override
public boolean performFinish() {
// TODO Auto-generated method stub
boolean isFinish = page.finish();
if (isFinish) {
MessageDialog.openInformation(getShell(), Messages.getString("wizard.ExportProjectWizard.msgTitle"),
Messages.getString("wizard.ExportProjectWizard.msg"));
}
return isFinish;
}
@Override
public void addPages() {
// TODO Auto-generated method stub
super.addPages();
IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IViewPart viewPart = workbenchPage.findView("net.heartsome.cat.common.ui.navigator.view");
if (viewPart != null) {
this.selection = (StructuredSelection) viewPart.getSite().getSelectionProvider().getSelection();
}
page = new ExportProjectWizardPage("", selection);
addPage(page);
}
}
| 2,266 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WizardExportResourcesPage2.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.exportproject/src/net/heartsome/cat/ts/exportproject/wizards/WizardExportResourcesPage2.java | package net.heartsome.cat.ts.exportproject.wizards;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.resources.IContainer;
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.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
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.Shell;
import org.eclipse.ui.dialogs.TypeFilteringDialog;
import org.eclipse.ui.dialogs.WizardDataTransferPage;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ide.DialogUtil;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.ide.dialogs.ResourceTreeAndListGroup;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* 此类与 org.eclipse.ui.dialogs.WizardExportResourcesPage 代码大多数是一样的,区别为在左边树中选择目录后右边过滤掉了隐藏的文件
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public abstract class WizardExportResourcesPage2 extends WizardDataTransferPage {
private IStructuredSelection initialResourceSelection;
private List selectedTypes = new ArrayList();
// widgets
private ResourceTreeAndListGroup resourceGroup;
private final static String SELECT_TYPES_TITLE = IDEWorkbenchMessages.WizardTransferPage_selectTypes;
private final static String SELECT_ALL_TITLE = IDEWorkbenchMessages.WizardTransferPage_selectAll;
private final static String DESELECT_ALL_TITLE = IDEWorkbenchMessages.WizardTransferPage_deselectAll;
private List defaultExportItems = new ArrayList();
/**
* Creates an export wizard page. If the current resource selection is not empty then it will be used as the initial
* collection of resources selected for export.
* @param pageName
* the name of the page
* @param selection
* {@link IStructuredSelection} of {@link IResource}
* @see IDE#computeSelectedResources(IStructuredSelection)
*/
protected WizardExportResourcesPage2(String pageName, IStructuredSelection selection) {
super(pageName);
this.initialResourceSelection = selection;
}
/**
* The <code>addToHierarchyToCheckedStore</code> implementation of this <code>WizardDataTransferPage</code> method
* returns <code>false</code>. Subclasses may override this method.
*/
protected boolean allowNewContainerName() {
return false;
}
/**
* Creates a new button with the given id.
* <p>
* The <code>Dialog</code> implementation of this framework method creates a standard push button, registers for
* selection events including button presses and registers default buttons with its shell. The button id is stored
* as the buttons client data. Note that the parent's layout is assumed to be a GridLayout and the number of columns
* in this layout is incremented. Subclasses may override.
* </p>
* @param parent
* the parent composite
* @param id
* the id of the button (see <code>IDialogConstants.*_ID</code> constants for standard dialog button ids)
* @param label
* the label from the button
* @param defaultButton
* <code>true</code> if the button is to be the default button, and <code>false</code> otherwise
*/
protected Button createButton(Composite parent, int id, String label, boolean defaultButton) {
// increment the number of columns in the button bar
((GridLayout) parent.getLayout()).numColumns++;
Button button = new Button(parent, SWT.PUSH);
GridData buttonData = new GridData(GridData.FILL_HORIZONTAL);
button.setLayoutData(buttonData);
button.setData(new Integer(id));
button.setText(label);
button.setFont(parent.getFont());
if (defaultButton) {
Shell shell = parent.getShell();
if (shell != null) {
shell.setDefaultButton(button);
}
button.setFocus();
}
button.setFont(parent.getFont());
setButtonLayoutData(button);
return button;
}
/**
* Creates the buttons for selecting specific types or selecting all or none of the elements.
* @param parent
* the parent control
*/
protected final void createButtonsGroup(Composite parent) {
Font font = parent.getFont();
// top level group
Composite buttonComposite = new Composite(parent, SWT.NONE);
buttonComposite.setFont(parent.getFont());
GridLayout layout = new GridLayout();
layout.numColumns = 3;
layout.makeColumnsEqualWidth = true;
buttonComposite.setLayout(layout);
buttonComposite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
// types edit button
Button selectTypesButton = createButton(buttonComposite, IDialogConstants.SELECT_TYPES_ID, SELECT_TYPES_TITLE,
false);
SelectionListener listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleTypesEditButtonPressed();
}
};
selectTypesButton.addSelectionListener(listener);
selectTypesButton.setFont(font);
setButtonLayoutData(selectTypesButton);
Button selectButton = createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, SELECT_ALL_TITLE, false);
listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resourceGroup.setAllSelections(true);
updateWidgetEnablements();
}
};
selectButton.addSelectionListener(listener);
selectButton.setFont(font);
setButtonLayoutData(selectButton);
Button deselectButton = createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, DESELECT_ALL_TITLE,
false);
listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resourceGroup.setAllSelections(false);
updateWidgetEnablements();
}
};
deselectButton.addSelectionListener(listener);
deselectButton.setFont(font);
setButtonLayoutData(deselectButton);
}
/**
* (non-Javadoc) Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
composite.setFont(parent.getFont());
createResourcesGroup(composite);
createButtonsGroup(composite);
createDBExportGroup(composite);
createDestinationGroup(composite);
restoreResourceSpecificationWidgetValues(); // ie.- local
restoreWidgetValues(); // ie.- subclass hook
if (initialResourceSelection != null) {
setupBasedOnInitialSelections();
}
updateWidgetEnablements();
setPageComplete(determinePageCompletion());
setErrorMessage(null); // should not initially have error message
setControl(composite);
}
protected abstract void createDBExportGroup(Composite parent);
/**
* Creates the export destination specification visual components.
* <p>
* Subclasses must implement this method.
* </p>
* @param parent
* the parent control
*/
protected abstract void createDestinationGroup(Composite parent);
/**
* Creates the checkbox tree and list for selecting resources.
* @param parent
* the parent control
*/
protected final void createResourcesGroup(Composite parent) {
// create the input element, which has the root resource
// as its only child
List input = new ArrayList();
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
if (projects[i].isOpen()) {
input.add(projects[i]);
}
}
this.resourceGroup = new ResourceTreeAndListGroup(parent, input, getResourceProvider(IResource.FOLDER
| IResource.PROJECT), WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(),
getResourceProvider(IResource.FILE), WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(),
SWT.NONE, DialogUtil.inRegularFontMode(parent));
ICheckStateListener listener = new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateWidgetEnablements();
}
};
this.resourceGroup.addCheckStateListener(listener);
}
/*
* @see WizardDataTransferPage.getErrorDialogTitle()
*/
protected String getErrorDialogTitle() {
return IDEWorkbenchMessages.WizardExportPage_errorDialogTitle;
}
/**
* Obsolete method. This was implemented to handle the case where ensureLocal() needed to be called but it doesn't
* use it any longer.
* @deprecated Only retained for backwards compatibility.
*/
protected boolean ensureResourcesLocal(List resources) {
return true;
}
/**
* Returns a new subcollection containing only those resources which are not local.
* @param originalList
* the original list of resources (element type: <code>IResource</code>)
* @return the new list of non-local resources (element type: <code>IResource</code>)
*/
protected List extractNonLocalResources(List originalList) {
Vector result = new Vector(originalList.size());
Iterator resourcesEnum = originalList.iterator();
while (resourcesEnum.hasNext()) {
IResource currentResource = (IResource) resourcesEnum.next();
if (!currentResource.isLocal(IResource.DEPTH_ZERO)) {
result.addElement(currentResource);
}
}
return result;
}
/**
* Returns a content provider for <code>IResource</code>s that returns only children of the given resource type.
*/
private ITreeContentProvider getResourceProvider(final int resourceType) {
return new WorkbenchContentProvider() {
public Object[] getChildren(Object o) {
if (o instanceof IContainer) {
IResource[] members = null;
try {
members = ((IContainer) o).members();
} catch (CoreException e) {
// just return an empty set of children
return new Object[0];
}
// filter out the desired resource types
ArrayList results = new ArrayList();
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(".config") || members[i].getName().equals(".project") ||members[i].getName().equalsIgnoreCase(".temp") ) {
defaultExportItems.add(members[i]);
continue;
}
// And the test bits with the resource types to see if they are what we want
if ((members[i].getType() & resourceType) > 0) {
results.add(members[i]);
}
}
return results.toArray();
}
// input element case
if (o instanceof ArrayList) {
return ((ArrayList) o).toArray();
}
return new Object[0];
}
};
}
public List getDefaultExportItems() {
return defaultExportItems;
}
/**
* Returns this page's collection of currently-specified resources to be exported. This is the primary resource
* selection facility accessor for subclasses.
* @return a collection of resources currently selected for export (element type: <code>IResource</code>)
*/
protected List getSelectedResources() {
Iterator resourcesToExportIterator = this.getSelectedResourcesIterator();
List resourcesToExport = new ArrayList();
while (resourcesToExportIterator.hasNext()) {
resourcesToExport.add(resourcesToExportIterator.next());
}
return resourcesToExport;
}
/**
* Returns this page's collection of currently-specified resources to be exported. This is the primary resource
* selection facility accessor for subclasses.
* @return an iterator over the collection of resources currently selected for export (element type:
* <code>IResource</code>). This will include white checked folders and individually checked files.
*/
protected Iterator getSelectedResourcesIterator() {
return this.resourceGroup.getAllCheckedListItems().iterator();
}
/**
* Returns the resource extensions currently specified to be exported.
* @return the resource extensions currently specified to be exported (element type: <code>String</code>)
*/
protected List getTypesToExport() {
return selectedTypes;
}
/**
* Returns this page's collection of currently-specified resources to be exported. This returns both folders and
* files - for just the files use getSelectedResources.
* @return a collection of resources currently selected for export (element type: <code>IResource</code>)
*/
protected List getWhiteCheckedResources() {
return this.resourceGroup.getAllWhiteCheckedItems();
}
/**
* Queries the user for the types of resources to be exported and selects them in the checkbox group.
*/
protected void handleTypesEditButtonPressed() {
Object[] newSelectedTypes = queryResourceTypesToExport();
if (newSelectedTypes != null) { // ie.- did not press Cancel
this.selectedTypes = new ArrayList(newSelectedTypes.length);
for (int i = 0; i < newSelectedTypes.length; i++) {
this.selectedTypes.add(newSelectedTypes[i]);
}
setupSelectionsBasedOnSelectedTypes();
}
}
/**
* Returns whether the extension of the given resource name is an extension that has been specified for export by
* the user.
* @param resourceName
* the resource name
* @return <code>true</code> if the resource name is suitable for export based upon its extension
*/
protected boolean hasExportableExtension(String resourceName) {
if (selectedTypes == null) {
return true;
}
int separatorIndex = resourceName.lastIndexOf("."); //$NON-NLS-1$
if (separatorIndex == -1) {
return false;
}
String extension = resourceName.substring(separatorIndex + 1);
Iterator it = selectedTypes.iterator();
while (it.hasNext()) {
if (extension.equalsIgnoreCase((String) it.next())) {
return true;
}
}
return false;
}
/**
* Persists additional setting that are to be restored in the next instance of this page.
* <p>
* The <code>WizardImportPage</code> implementation of this method does nothing. Subclasses may extend to persist
* additional settings.
* </p>
*/
protected void internalSaveWidgetValues() {
}
/**
* Queries the user for the resource types that are to be exported and returns these types as an array.
* @return the resource types selected for export (element type: <code>String</code>), or <code>null</code> if the
* user canceled the selection
*/
protected Object[] queryResourceTypesToExport() {
TypeFilteringDialog dialog = new TypeFilteringDialog(getContainer().getShell(), getTypesToExport());
dialog.open();
return dialog.getResult();
}
/**
* Restores resource specification control settings that were persisted in the previous instance of this page.
* Subclasses wishing to restore persisted values for their controls may extend.
*/
protected void restoreResourceSpecificationWidgetValues() {
}
/**
* Persists resource specification control setting that are to be restored in the next instance of this page.
* Subclasses wishing to persist additional setting for their controls should extend hook method
* <code>internalSaveWidgetValues</code>.
*/
protected void saveWidgetValues() {
// allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Set the initial selections in the resource group.
*/
protected void setupBasedOnInitialSelections() {
Iterator it = this.initialResourceSelection.iterator();
while (it.hasNext()) {
IResource currentResource = (IResource) it.next();
if (currentResource.getType() == IResource.FILE) {
this.resourceGroup.initialCheckListItem(currentResource);
} else {
this.resourceGroup.initialCheckTreeItem(currentResource);
}
}
}
/**
* Update the tree to only select those elements that match the selected types
*/
private void setupSelectionsBasedOnSelectedTypes() {
Runnable runnable = new Runnable() {
public void run() {
Map selectionMap = new Hashtable();
// Only get the white selected ones
Iterator resourceIterator = resourceGroup.getAllWhiteCheckedItems().iterator();
while (resourceIterator.hasNext()) {
// handle the files here - white checked containers require recursion
IResource resource = (IResource) resourceIterator.next();
if (resource.getType() == IResource.FILE) {
if (hasExportableExtension(resource.getName())) {
List resourceList = new ArrayList();
IContainer parent = resource.getParent();
if (selectionMap.containsKey(parent)) {
resourceList = (List) selectionMap.get(parent);
}
resourceList.add(resource);
selectionMap.put(parent, resourceList);
}
} else {
setupSelectionsBasedOnSelectedTypes(selectionMap, (IContainer) resource);
}
}
resourceGroup.updateSelections(selectionMap);
}
};
BusyIndicator.showWhile(getShell().getDisplay(), runnable);
}
/**
* Set up the selection values for the resources and put them in the selectionMap. If a resource is a file see if it
* matches one of the selected extensions. If not then check the children.
*/
private void setupSelectionsBasedOnSelectedTypes(Map selectionMap, IContainer parent) {
List selections = new ArrayList();
IResource[] resources;
boolean hasFiles = false;
try {
resources = parent.members();
} catch (CoreException exception) {
// Just return if we can't get any info
return;
}
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (resource.getType() == IResource.FILE) {
if (hasExportableExtension(resource.getName())) {
hasFiles = true;
selections.add(resource);
}
} else {
setupSelectionsBasedOnSelectedTypes(selectionMap, (IContainer) resource);
}
}
// Only add it to the list if there are files in this folder
if (hasFiles) {
selectionMap.put(parent, selections);
}
}
/**
* Save any editors that the user wants to save before export.
* @return boolean if the save was successful.
*/
protected boolean saveDirtyEditors() {
return IDEWorkbenchPlugin.getDefault().getWorkbench().saveAllEditors(true);
}
/**
* Check if widgets are enabled or disabled by a change in the dialog.
*/
protected void updateWidgetEnablements() {
boolean pageComplete = determinePageCompletion();
setPageComplete(pageComplete);
if (pageComplete) {
setMessage(null);
}
super.updateWidgetEnablements();
}
public boolean isExportSQLiteTMs(){
return false;
}
public boolean isExportSQLiteTBs(){
return false;
}
}
| 19,207 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ZipFileExporter2.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.exportproject/src/net/heartsome/cat/ts/exportproject/wizards/ZipFileExporter2.java | package net.heartsome.cat.ts.exportproject.wizards;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.internal.wizards.datatransfer.IFileExporter;
/**
* 此类与 org.eclipse.ui.internal.wizards.datatransfer.ZipFileExporter 代码基本是一样的,但当文件名包含中文时, ZipFileExporter
* 生成的压缩包中的文件名包含乱码,此类使用了 ant.jar 生成压缩包,不会包含乱码。
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class ZipFileExporter2 implements IFileExporter {
private ZipOutputStream outputStream;
private boolean useCompression = true;
/**
* Create an instance of this class.
* @param filename
* java.lang.String
* @param compress
* boolean
* @exception java.io.IOException
*/
public ZipFileExporter2(String filename, boolean compress) throws IOException {
outputStream = new ZipOutputStream(new FileOutputStream(filename));
useCompression = compress;
}
/**
* Do all required cleanup now that we're finished with the currently-open .zip
* @exception java.io.IOException
*/
public void finished() throws IOException {
outputStream.close();
}
/**
* Write the contents of the file to the tar archive.
* @param entry
* @param contents
* @exception java.io.IOException
* @exception org.eclipse.core.runtime.CoreException
*/
private void write(ZipEntry entry, IFile contents) throws IOException, CoreException {
byte[] readBuffer = new byte[4096];
// If the contents are being compressed then we get the below for free.
if (!useCompression) {
entry.setMethod(ZipEntry.STORED);
InputStream contentStream = contents.getContents(false);
int length = 0;
CRC32 checksumCalculator = new CRC32();
try {
int n;
while ((n = contentStream.read(readBuffer)) > 0) {
checksumCalculator.update(readBuffer, 0, n);
length += n;
}
} finally {
if (contentStream != null) {
contentStream.close();
}
}
entry.setSize(length);
entry.setCrc(checksumCalculator.getValue());
}
// set the timestamp
long localTimeStamp = contents.getLocalTimeStamp();
if (localTimeStamp != IResource.NULL_STAMP)
entry.setTime(localTimeStamp);
outputStream.putNextEntry(entry);
InputStream contentStream = contents.getContents(false);
try {
int n;
while ((n = contentStream.read(readBuffer)) > 0) {
outputStream.write(readBuffer, 0, n);
}
} finally {
if (contentStream != null) {
contentStream.close();
}
}
outputStream.closeEntry();
}
public void write(IContainer container, String destinationPath) throws IOException {
ZipEntry newEntry = new ZipEntry(destinationPath);
outputStream.putNextEntry(newEntry);
}
/**
* Write the passed resource to the current archive.
* @param resource
* org.eclipse.core.resources.IFile
* @param destinationPath
* java.lang.String
* @exception java.io.IOException
* @exception org.eclipse.core.runtime.CoreException
*/
public void write(IFile resource, String destinationPath) throws IOException, CoreException {
ZipEntry newEntry = new ZipEntry(destinationPath);
write(newEntry, resource);
}
public void addDbFolder(String destinationPath) throws IOException {
ZipEntry newEntry = new ZipEntry(destinationPath);
outputStream.putNextEntry(newEntry);
}
public void addDbFile(File file, String destinationPath) throws IOException {
ZipEntry newEntry = new ZipEntry(destinationPath);
writeFile(newEntry, file);
}
private void writeFile(ZipEntry entry, File file) throws IOException {
byte[] readBuffer = new byte[4096];
// If the contents are being compressed then we get the below for free.
if (!useCompression) {
entry.setMethod(ZipEntry.STORED);
InputStream contentStream = getFileInpuStream(file);// contents.getContents(false);
int length = 0;
CRC32 checksumCalculator = new CRC32();
try {
int n;
while ((n = contentStream.read(readBuffer)) > 0) {
checksumCalculator.update(readBuffer, 0, n);
length += n;
}
} finally {
if (contentStream != null) {
contentStream.close();
}
}
entry.setSize(length);
entry.setCrc(checksumCalculator.getValue());
}
// set the timestamp
long localTimeStamp = file.lastModified();// contents.getLocalTimeStamp();
if (localTimeStamp != IResource.NULL_STAMP)
entry.setTime(localTimeStamp);
outputStream.putNextEntry(entry);
InputStream contentStream = getFileInpuStream(file);// contents.getContents(false);
try {
int n;
while ((n = contentStream.read(readBuffer)) > 0) {
outputStream.write(readBuffer, 0, n);
}
} finally {
if (contentStream != null) {
contentStream.close();
}
}
outputStream.closeEntry();
}
private InputStream getFileInpuStream(File file) throws FileNotFoundException {
return new FileInputStream(file);
}
}
| 5,370 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ArchiveFileExportOperation2.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.exportproject/src/net/heartsome/cat/ts/exportproject/wizards/ArchiveFileExportOperation2.java | package net.heartsome.cat.ts.exportproject.wizards;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.ProjectInfoBean;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages;
import org.eclipse.ui.internal.wizards.datatransfer.IFileExporter;
import org.eclipse.ui.internal.wizards.datatransfer.TarFileExporter;
/**
* 此类与 org.eclipse.ui.internal.wizards.datatransfer 大部分代码一样,区别为调用的生成 ZIP 压缩包的类为
* net.heartsome.cat.ts.ui.wizards.ZipFileExporter2
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class ArchiveFileExportOperation2 implements IRunnableWithProgress {
private IFileExporter exporter;
private String destinationFilename;
private IProgressMonitor monitor;
private List resourcesToExport;
private IResource resource;
private List errorTable = new ArrayList(1); // IStatus
private boolean useCompression = true;
private boolean useTarFormat = false;
private boolean createLeadupStructure = true;
private boolean isExportTm = false;;
private boolean isExportTb = false;
/** @return the isExportTm */
public boolean isExportTm() {
return isExportTm;
}
/**
* @param isExportTm
* the isExportTm to set
*/
public void setExportTm(boolean isExportTm) {
this.isExportTm = isExportTm;
}
/** @return the isExportTb */
public boolean isExportTb() {
return isExportTb;
}
/**
* @param isExportTb
* the isExportTb to set
*/
public void setExportTb(boolean isExportTb) {
this.isExportTb = isExportTb;
}
/**
* Create an instance of this class. Use this constructor if you wish to export specific resources without a common
* parent resource
* @param resources
* java.util.Vector
* @param filename
* java.lang.String
*/
public ArchiveFileExportOperation2(List resources, String filename) {
super();
// Eliminate redundancies in list of resources being exported
Iterator elementsEnum = resources.iterator();
while (elementsEnum.hasNext()) {
IResource currentResource = (IResource) elementsEnum.next();
if (isDescendent(resources, currentResource)) {
elementsEnum.remove(); // Removes currentResource;
}
}
resourcesToExport = resources;
destinationFilename = filename;
}
/**
* Create an instance of this class. Use this constructor if you wish to recursively export a single resource.
* @param res
* org.eclipse.core.resources.IResource;
* @param filename
* java.lang.String
*/
public ArchiveFileExportOperation2(IResource res, String filename) {
super();
resource = res;
destinationFilename = filename;
}
/**
* Create an instance of this class. Use this constructor if you wish to export specific resources with a common
* parent resource (affects container directory creation)
* @param res
* org.eclipse.core.resources.IResource
* @param resources
* java.util.Vector
* @param filename
* java.lang.String
*/
public ArchiveFileExportOperation2(IResource res, List resources, String filename) {
this(res, filename);
resourcesToExport = resources;
}
/**
* Add a new entry to the error table with the passed information
*/
protected void addError(String message, Throwable e) {
errorTable.add(new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, 0, message, e));
}
/**
* Answer the total number of file resources that exist at or below self in the resources hierarchy.
* @return int
* @param checkResource
* org.eclipse.core.resources.IResource
*/
protected int countChildrenOf(IResource checkResource) throws CoreException {
if (checkResource.getType() == IResource.FILE) {
return 1;
}
int count = 0;
if (checkResource.isAccessible()) {
IResource[] children = ((IContainer) checkResource).members();
for (int i = 0; i < children.length; i++) {
count += countChildrenOf(children[i]);
}
}
return count;
}
/**
* Answer a boolean indicating the number of file resources that were specified for export
* @return int
*/
protected int countSelectedResources() throws CoreException {
int result = 0;
Iterator resources = resourcesToExport.iterator();
while (resources.hasNext()) {
result += countChildrenOf((IResource) resources.next());
}
return result;
}
/**
* Export the passed resource to the destination .zip. Export with no path leadup
* @param exportResource
* org.eclipse.core.resources.IResource
*/
protected void exportResource(IResource exportResource) throws InterruptedException {
exportResource(exportResource, 1);
}
/**
* Creates and returns the string that should be used as the name of the entry in the archive.
* @param exportResource
* the resource to export
* @param leadupDepth
* the number of resource levels to be included in the path including the resourse itself.
*/
private String createDestinationName(int leadupDepth, IResource exportResource) {
IPath fullPath = exportResource.getFullPath();
if (createLeadupStructure) {
return fullPath.makeRelative().toString();
}
return fullPath.removeFirstSegments(fullPath.segmentCount() - leadupDepth).toString();
}
/**
* Export the passed resource to the destination .zip
* @param exportResource
* org.eclipse.core.resources.IResourcep
* @param leadupDepth
* the number of resource levels to be included in the path including the resourse itself.
*/
protected void exportResource(IResource exportResource, int leadupDepth) throws InterruptedException {
if (!exportResource.isAccessible()) {
return;
}
exportProjectSQLiteFiles(exportResource.getProject()); // 导出文件数据库文件
if (exportResource.getType() == IResource.FILE) {
String destinationName = createDestinationName(leadupDepth, exportResource);
monitor.subTask(destinationName);
try {
exporter.write((IFile) exportResource, destinationName);
} catch (IOException e) {
addError(NLS.bind(DataTransferMessages.DataTransfer_errorExporting, exportResource.getFullPath()
.makeRelative(), e.getMessage()), e);
} catch (CoreException e) {
addError(NLS.bind(DataTransferMessages.DataTransfer_errorExporting, exportResource.getFullPath()
.makeRelative(), e.getMessage()), e);
}
monitor.worked(1);
ModalContext.checkCanceled(monitor);
} else {
IResource[] children = null;
try {
children = ((IContainer) exportResource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addError(NLS.bind(DataTransferMessages.DataTransfer_errorExporting, exportResource.getFullPath()), e);
}
if (children.length == 0) { // create an entry for empty containers, see bug 278402
String destinationName = createDestinationName(leadupDepth, exportResource);
try {
exporter.write((IContainer) exportResource, destinationName + "/");
} catch (IOException e) {
addError(NLS.bind(DataTransferMessages.DataTransfer_errorExporting, exportResource.getFullPath()
.makeRelative(), e.getMessage()), e);
}
}
for (int i = 0; i < children.length; i++) {
exportResource(children[i], leadupDepth + 1);
}
}
}
/**
* Export the resources contained in the previously-defined resourcesToExport collection
*/
protected void exportSpecifiedResources() throws InterruptedException {
Iterator resources = resourcesToExport.iterator();
while (resources.hasNext()) {
IResource currentResource = (IResource) resources.next();
exportResource(currentResource);
}
}
/**
* Returns the status of the operation. If there were any errors, the result is a status object containing
* individual status objects for each error. If there were no errors, the result is a status object with error code
* <code>OK</code>.
* @return the status
*/
public IStatus getStatus() {
IStatus[] errors = new IStatus[errorTable.size()];
errorTable.toArray(errors);
return new MultiStatus(IDEWorkbenchPlugin.IDE_WORKBENCH, IStatus.OK, errors,
DataTransferMessages.FileSystemExportOperation_problemsExporting, null);
}
/**
* Initialize this operation
* @exception java.io.IOException
*/
protected void initialize() throws IOException {
if (useTarFormat) {
exporter = new TarFileExporter(destinationFilename, useCompression);
} else {
exporter = new ZipFileExporter2(destinationFilename, useCompression);
}
}
/**
* Answer a boolean indicating whether the passed child is a descendent of one or more members of the passed
* resources collection
* @return boolean
* @param resources
* java.util.Vector
* @param child
* org.eclipse.core.resources.IResource
*/
protected boolean isDescendent(List resources, IResource child) {
if (child.getType() == IResource.PROJECT) {
return false;
}
IResource parent = child.getParent();
if (resources.contains(parent)) {
return true;
}
return isDescendent(resources, parent);
}
/**
* Export the resources that were previously specified for export (or if a single resource was specified then export
* it recursively)
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
this.monitor = progressMonitor;
try {
initialize();
} catch (IOException e) {
throw new InvocationTargetException(e, NLS.bind(DataTransferMessages.ZipExport_cannotOpen, e.getMessage()));
}
try {
// ie.- a single resource for recursive export was specified
int totalWork = IProgressMonitor.UNKNOWN;
try {
if (resourcesToExport == null) {
totalWork = countChildrenOf(resource);
} else {
totalWork = countSelectedResources();
}
} catch (CoreException e) {
// Should not happen
}
monitor.beginTask(DataTransferMessages.DataTransfer_exportingTitle, totalWork);
if (resourcesToExport == null) {
exportResource(resource);
} else {
// ie.- a list of specific resources to export was specified
exportSpecifiedResources();
}
try {
exporter.finished();
} catch (IOException e) {
throw new InvocationTargetException(e, NLS.bind(DataTransferMessages.ZipExport_cannotClose,
e.getMessage()));
}
} finally {
monitor.done();
}
}
/**
* Set this boolean indicating whether each exported resource's path should include containment hierarchies as
* dictated by its parents
* @param value
* boolean
*/
public void setCreateLeadupStructure(boolean value) {
createLeadupStructure = value;
}
/**
* Set this boolean indicating whether exported resources should be compressed (as opposed to simply being stored)
* @param value
* boolean
*/
public void setUseCompression(boolean value) {
useCompression = value;
}
/**
* Set this boolean indicating whether the file should be output in tar.gz format rather than .zip format.
* @param value
* boolean
*/
public void setUseTarFormat(boolean value) {
useTarFormat = value;
}
private final int TM = 0;
private final int TB = 1;
/**
* @param project
* @param type
* @return ;
*/
private List<File> getProjectSQLiteFiles(IProject project, int type) {
ProjectConfiger projectConfiger = ProjectConfigerFactory.getProjectConfiger(project);
ProjectInfoBean currentProjectConfig = projectConfiger.getCurrentProjectConfig();
List<DatabaseModelBean> sqlDbs = null;
if (TM == type) {
sqlDbs = currentProjectConfig.getTmDb();
} else if (TB == type) {
sqlDbs = currentProjectConfig.getTbDb();
}
List<File> files = new ArrayList<File>();
for (DatabaseModelBean bean : sqlDbs) {
if ("SQLite".equals(bean.getDbType())) {
File file = new File(getSqliteFilePath(bean));
if (file.exists() && file.isFile()) {
files.add(file);
}
}
}
return files;
}
private String getSqliteFilePath(DatabaseModelBean bean) {
return bean.getItlDBLocation() + File.separator + bean.getDbName();
}
private List<IProject> exprotedProject = new ArrayList<IProject>();
private void exportProjectSQLiteFiles(IProject project) {
if (exprotedProject.contains(project)) {
return;
} else {
exprotedProject.add(project);
}
List<File> projectSQLiteTmFiles = getProjectSQLiteFiles(project, TM);
List<File> projectSQLiteTbFiles = getProjectSQLiteFiles(project, TB);
String fileSeparator = "/";// just support char '/' , use System.getProperty("file.separator") maybe has a bug;
if (exporter instanceof ZipFileExporter2) {
ZipFileExporter2 zipFileExporter2 = (ZipFileExporter2) exporter;
String tmParent = project.getName() + fileSeparator + "TM" + fileSeparator;
String tbParent = project.getName() + fileSeparator + "TB" + fileSeparator;
try {
// 导出SQLITE TM File
if (isExportTm() && null != projectSQLiteTmFiles && !projectSQLiteTmFiles.isEmpty()) {
zipFileExporter2.addDbFolder(tmParent);
int index = 0;
for (File file : projectSQLiteTmFiles) {
String exportDBName = getExportDBName(project, file, TM, index);
if (null != exportDBName) {
zipFileExporter2.addDbFile(file, tmParent + exportDBName);
index++;
}
}
}
// 导出SQLITE TB File
int index = 0;
if (isExportTb() && null != projectSQLiteTbFiles && !projectSQLiteTbFiles.isEmpty()) {
zipFileExporter2.addDbFolder(tbParent);
for (File file : projectSQLiteTbFiles) {
String exportDBName = getExportDBName(project, file, TB, index);
if (null != exportDBName) {
zipFileExporter2.addDbFile(file, tbParent + exportDBName);
index++;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getExportDBName(IProject project, File dbfile, int type, int index) {
String fileName = dbfile.getName();
String exportName = fileName;
String filePath = dbfile.getAbsolutePath();
if (TM == type) {
IFolder folder = project.getFolder("TM");
if (folder.exists()) {
IFile file = folder.getFile(fileName);
if (file.exists() && !equalPath(filePath, file.getLocation().toOSString())) {
exportName = "Exported_" + index + "_" + fileName;
}
if (resourcesToExport.contains(project) && equalPath(filePath, file.getLocation().toOSString())) {
return null;
}
}
} else if (TB == type) {
IFolder folder = project.getFolder("TB");
if (folder.exists()) {
IFile file = folder.getFile(fileName);
if (file.exists() && !equalPath(filePath, file.getLocation().toOSString())) {
exportName = "Exported_" + index + "_" + fileName;
}
if (resourcesToExport.contains(project) && equalPath(filePath, file.getLocation().toOSString())) {
return null;
}
}
}
return exportName;
}
private boolean equalPath(String path1, String path2) {
String pathOne = path1.replaceAll("\\\\", "/");
String pathTwo = path2.replaceAll("\\\\", "/");
return pathOne.equals(pathTwo);
}
}
| 16,165 | 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.exportproject/src/net/heartsome/cat/ts/exportproject/resource/Messages.java | package net.heartsome.cat.ts.exportproject.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.exportproject.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 570 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTransUitls.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/PreMachineTransUitls.java | /**
* PreTransUitls.java
*
* Version information :
*
* Date:2012-6-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.file.XLFValidator;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.ts.core.bean.XliffBean;
import net.heartsome.cat.ts.core.file.XLFHandler;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTransParameters;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTranslationCounter;
import net.heartsome.cat.ts.machinetranslation.dialog.PreMachineTranslationDialog;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.VTDGen;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class PreMachineTransUitls {
public static final Logger logger = LoggerFactory.getLogger(PreMachineTransUitls.class);
public static void executeTranslation(List<IFile> list, final Shell shell) {
HsMultiActiveCellEditor.commit(true);
try {
if (list.size() == 0) {
MessageDialog.openInformation(shell, Messages.getString("pretranslation.PreTransUitls.msgTitle"),
Messages.getString("pretranslation.PreTransUitls.msg1"));
return;
}
List<IFile> lstFiles = new ArrayList<IFile>();
XLFValidator.resetFlag();
for (IFile iFile : list) {
if (!XLFValidator.validateXliffFile(iFile)) {
lstFiles.add(iFile);
}
}
XLFValidator.resetFlag();
list = new ArrayList<IFile>(list);
list.removeAll(lstFiles);
if (list.size() == 0) {
return;
}
final IProject project = list.get(0).getProject();
final List<String> filesWithOsPath = ResourceUtils.IFilesToOsPath(list);
final XLFHandler xlfHandler = new XLFHandler();
Map<String, Object> resultMap = xlfHandler.openFiles(filesWithOsPath);
if (resultMap == null
|| Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap.get(Constant.RETURNVALUE_RESULT)) {
// 打开文件失败。
MessageDialog.openInformation(shell, Messages.getString("pretranslation.PreTransUitls.msgTitle"),
Messages.getString("pretranslation.PreTransUitls.msg2"));
return;
}
Map<String, List<XliffBean>> map = xlfHandler.getXliffInfo();
final PreMachineTransParameters parameters =new PreMachineTransParameters();
PreMachineTranslationDialog dialog = new PreMachineTranslationDialog(shell, map, parameters);
if (dialog.open() == Window.OK) {
if (project == null) {
MessageDialog.openInformation(shell, Messages.getString("pretranslation.PreTransUitls.msgTitle"),
Messages.getString("pretranslation.PreTransUitls.msg3"));
return;
}
if (filesWithOsPath == null || filesWithOsPath.size() == 0) {
MessageDialog.openInformation(shell, Messages.getString("pretranslation.PreTransUitls.msgTitle"),
Messages.getString("pretranslation.PreTransUitls.msg4"));
return;
}
final List<IFile> lstFile = list;
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
PreMachineTranslation pt = new PreMachineTranslation(xlfHandler, filesWithOsPath, project, parameters);
try {
final List<PreMachineTranslationCounter> result = pt.executeTranslation(monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
//PreMachineTranslationResultDialog dialog = new PreMachineTranslationResultDialog(shell, result);
//dialog.open();
}
});
project.refreshLocal(IResource.DEPTH_INFINITE, null);
result.clear();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
logger.error("", e);
e.printStackTrace();
} finally {
pt.clearResources();
}
Display.getDefault().syncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage();
for (IFile file : lstFile) {
FileEditorInput editorInput = new FileEditorInput(file);
IEditorPart editorPart = page.findEditor(editorInput);
// 选择所有语言
XLFHandler handler = null;
if (editorPart != null && editorPart instanceof IXliffEditor) {
// xliff 文件已用 XLIFF 编辑器打开
IXliffEditor xliffEditor = (IXliffEditor) editorPart;
handler = xliffEditor.getXLFHandler();
handler.resetCache();
VTDGen vg = new VTDGen();
String path = ResourceUtils.iFileToOSPath(file);
if (vg.parseFile(path, true)) {
handler.getVnMap().put(path, vg.getNav());
xliffEditor.refresh();
}
}
}
}
});
}
};
try {
new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()).run(
true, true, runnable);
MessageDialog.openInformation(shell, Messages.getString("pretranslation.PreTransUitls.msgTitle"),
Messages.getString("pretranslation.PreTransUitls.result.msg"));
} catch (InvocationTargetException e) {
logger.error("", e);
} catch (InterruptedException e) {
logger.error("", e);
}
}
} finally {
HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.getCurrent());
}
}
}
| 7,159 | 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.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/Activator.java | package net.heartsome.cat.ts.machinetranslation;
import net.heartsome.cat.ts.ui.bean.TranslateParameter;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.ts.machinetranslation"; //$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;
TranslateParameter.getInstance().setMachinePs(plugin.getPreferenceStore());
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* 提供一个图片文件对插件的相对路径,返回该图片的描述信息。
* @param path
* 图片资源对插件的相对路径。
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
/**
* 提供一个图片文件对插件的相对路径,返回该图片被伸缩变换为16*16像素的描述信息。
* @param path
* the path
* @return the icon descriptor
*/
public static ImageDescriptor getIconDescriptor(String path) {
ImageDescriptor image = getImageDescriptor(path);
ImageData data = image.getImageData();
data = data.scaledTo(16, 16);
image = ImageDescriptor.createFromImageData(data);
return image;
}
}
| 2,166 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
BingTransUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/BingTransUtils.java | /**
* GoogleTransUtils.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import com.memetix.mst.language.Language;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class BingTransUtils {
/** 处理语言 */
public static Language processLanguage(String hsLanguageCode) {
// 由于中文前缀一样,需针对中文特殊处理。
if (hsLanguageCode.equalsIgnoreCase("zh-CN")) {
return Language.CHINESE_SIMPLIFIED;
}
if (hsLanguageCode.equalsIgnoreCase("zh-TW") || hsLanguageCode.equalsIgnoreCase("zh-HK")) {
return Language.CHINESE_TRADITIONAL;
}
Language[] supportedLangs = Language.values();
for (Language lang : supportedLangs) {
String code = lang.toString();
if (code.equals("")) {
continue;
}
if (hsLanguageCode.startsWith(code) || code.startsWith(hsLanguageCode)) {
return lang;
}
}
return null;
}
}
| 1,477 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GoogleTransUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/GoogleTransUtils.java | /**
* GoogleTransUtils.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import com.google.api.translate.Language;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class GoogleTransUtils {
/** 处理语言 */
public static Language processLanguage(String hsLanguageCode) {
// 由于中文前缀一样,需针对中文特殊处理。
if (hsLanguageCode.equalsIgnoreCase("zh-CN")) {
return Language.CHINESE_SIMPLIFIED;
}
if (hsLanguageCode.equalsIgnoreCase("zh-TW")) {
return Language.CHINESE_TRADITIONAL;
}
Language[] supportedLangs = Language.values();
for (Language lang : supportedLangs) {
String code = lang.toString();
if (code.equals("")) {
continue;
}
if (hsLanguageCode.startsWith(code) || code.startsWith(hsLanguageCode)) {
return lang;
}
}
return null;
}
}
| 1,433 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTranslation.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/PreMachineTranslation.java | /**
* PreTranslation.java
*
* Version information :
*
* Date:Dec 13, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.ts.core.bean.AltTransBean;
import net.heartsome.cat.ts.core.file.XLFHandler;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTransParameters;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTranslationCounter;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean;
import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher;
import net.heartsome.cat.ts.tm.simpleMatch.SimpleMatcherFactory;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
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
*/
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class PreMachineTranslation {
public static final Logger logger = LoggerFactory.getLogger(PreMachineTranslation.class);
private PreMachineTransParameters parameters;
/** 项目中的XLIFF文件解析 */
private XLFHandler xlfHandler;
/** 项目中的XLIFF文件路径,绝对路径 */
private List<String> xlfFiles;
private List<PreMachineTranslationCounter> transCounters;
private PreMachineTranslationCounter currentCounter;
/**
* 需要的机器翻译服务
*/
private List<ISimpleMatcher> simpleMatchers;
public PreMachineTranslation(XLFHandler xlfHandler, List<String> xlfFiles, IProject currIProject,
PreMachineTransParameters parameters) {
this.xlfHandler = xlfHandler;
this.xlfFiles = xlfFiles;
this.parameters = parameters;
transCounters = new ArrayList<PreMachineTranslationCounter>();
}
/**
* 根据构建参数执行预翻译 ;
* @throws InterruptedException
*/
public List<PreMachineTranslationCounter> executeTranslation(IProgressMonitor monitor) throws InterruptedException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
simpleMatchers = getMacthers();
if (null == simpleMatchers || simpleMatchers.isEmpty()) {
return this.transCounters;
}
monitor.beginTask("", this.xlfFiles.size());
monitor.setTaskName(Messages.getString("pretranslation.PreTranslation.task1"));
try {
for (String xlfPath : xlfFiles) {
if (monitor != null && monitor.isCanceled()) {
throw new InterruptedException();
}
currentCounter = new PreMachineTranslationCounter(xlfPath);
this.transCounters.add(currentCounter);
VTDNav vn = xlfHandler.getVnMap().get(xlfPath);
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vu.getVTDNav());
int tuNumber = xlfHandler.getNodeCount(xlfPath,
"/xliff/file//descendant::trans-unit[(source/text()!='' or source/*)]");
currentCounter.setTuNumber(tuNumber);
ap.selectXPath("/xliff/file");
String srcLang = "";
String tgtLang = "";
XMLModifier xm = new XMLModifier(vn);
IProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1);
monitor2.beginTask(Messages.getString("pretranslation.PreTranslation.task2"), tuNumber);
while (ap.evalXPath() != -1) { // 循环 file 节点
String _srcLang = vu.getCurrentElementAttribut("source-language", "");
String _tgtLang = vu.getCurrentElementAttribut("target-language", "");
if (!_srcLang.equals("")) {
srcLang = _srcLang;
}
if (!_tgtLang.equals("")) {
tgtLang = _tgtLang;
}
if (srcLang.equals("") || tgtLang.equals("")) {
continue;
}
keepCurrentMatchs(vu, _srcLang, _tgtLang, xm, monitor2);
}
monitor2.done();
FileOutputStream fos = new FileOutputStream(xlfPath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
}
} catch (XPathParseException e) {
logger.error("", e);
e.printStackTrace();
} catch (NavException e) {
logger.error("", e);
e.printStackTrace();
} catch (ModifyException e) {
logger.error("", e);
e.printStackTrace();
} catch (XPathEvalException e) {
logger.error("", e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
logger.error("", e);
e.printStackTrace();
} catch (FileNotFoundException e) {
logger.error("", e);
e.printStackTrace();
} catch (TranscodeException e) {
logger.error("", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("", e);
e.printStackTrace();
}
monitor.done();
return this.transCounters;
}
public void clearResources() {
// 完成翻译后清除使用的资源
this.transCounters.clear();
this.transCounters = null;
}
private void keepCurrentMatchs(VTDUtils vu, String srcLang, String tgtLang, XMLModifier xm, IProgressMonitor monitor)
throws NavException, XPathParseException, XPathEvalException, ModifyException,
UnsupportedEncodingException, InterruptedException {
AutoPilot tuAp = new AutoPilot(vu.getVTDNav());
tuAp.selectXPath("./body//trans-unit");
while (tuAp.evalXPath() != -1) { // 循环 Trans-unit
if (monitor != null && monitor.isCanceled()) {
throw new InterruptedException();
}
if (parameters.isIgnoreLock()) {// 1、如果忽略锁定文本
String locked = vu.getCurrentElementAttribut("translate", "yes");
if (locked.equals("no")) {
currentCounter.countLockedContextmatch();
continue;
}
}
if(parameters.isIgnoreExactMatch()){// 2、如果忽略匹配率
String qualityValue = vu.getElementAttribute("./target", "hs:quality");
if(null != qualityValue && !qualityValue.isEmpty()){
qualityValue = qualityValue.trim();
if (qualityValue.equals("100") || qualityValue.equals("101")) {
currentCounter.countLockedFullMatch();
continue;
}
}
}
TransUnitInfo2TranslationBean tuInfo = getTransUnitInfo(vu);
if (tuInfo == null) {
continue;
}
tuInfo.setSrcLanguage(srcLang);
tuInfo.setTgtLangugage(tgtLang);
updateXliffFile(vu, tuInfo, xm);
monitor.worked(1);
}
}
/**
* 将机器翻译结果存入XLIFF
* @param vu
* @param tuInfo
* @param xm
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
* @throws ModifyException
* @throws UnsupportedEncodingException
* ;
*/
private void updateXliffFile(VTDUtils vu, TransUnitInfo2TranslationBean tuInfo, XMLModifier xm)
throws XPathParseException, XPathEvalException, NavException, ModifyException, UnsupportedEncodingException {
String targetContent = "";
String simpleMatchContent = executeSimpleMatch(vu, tuInfo, xm);
targetContent += simpleMatchContent;
if (targetContent.length() > 0) {
currentCounter.countTransTu();
xm.insertBeforeTail(targetContent);
}
}
private List<ISimpleMatcher> getMacthers() {
List<ISimpleMatcher> spMatchers = SimpleMatcherFactory.getInstance().getCuurentMatcher();
List<ISimpleMatcher> useableSimeMathers =new ArrayList<ISimpleMatcher>();
if (parameters.isBingTranslate()) {// 1、是否勾选bing翻译
for (ISimpleMatcher matcher : spMatchers) {
if (matcher.getMathcerOrigin().equals("Bing Translation")) {
useableSimeMathers.add(matcher);
break;
}
}
}
if (parameters.isGoogleTranslate()) {// 2、是否勾选google翻译
for (ISimpleMatcher matcher : spMatchers) {
if (matcher.getMathcerOrigin().equals("Google Translation")) {
useableSimeMathers.add(matcher);
break;
}
}
}
return useableSimeMathers;
}
/**
* 访问机器翻译API
* @param vu
* @param tuInfo
* @param xm
* @return
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
* ;
*/
private String executeSimpleMatch(VTDUtils vu, TransUnitInfo2TranslationBean tuInfo, XMLModifier xm)
throws XPathParseException, XPathEvalException, NavException {
StringBuffer bf = new StringBuffer();
for (ISimpleMatcher matcher : simpleMatchers) {
// 1、是否支持预存机器翻译
if (!matcher.isSuportPreTrans()) {
continue;
}
String toolId = matcher.getMathcerToolId();
vu.getVTDNav().push();
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("./alt-trans[@tool-id='" + toolId + "']");
// 3、 是否有预存翻译,有预存的机器翻译,不进行预存
if (ap.evalXPath() != -1) {
vu.getVTDNav().pop();
continue;
}
vu.getVTDNav().pop();
String tgtText = matcher.executeMatch(tuInfo);
if (tgtText.equals("")) {
continue;
}
AltTransBean bean = new AltTransBean(tuInfo.getSrcPureText(), tgtText, tuInfo.getSrcLanguage(),
tuInfo.getTgtLangugage(), matcher.getMathcerOrigin(), matcher.getMathcerToolId());
bean.getMatchProps().put("match-quality", "100");
bean.setSrcContent(tuInfo.getSrcPureText());
bean.setTgtContent(tgtText);
bean.getMatchProps().put("hs:matchType", matcher.getMatcherType());
bf.append(bean.toXMLString());
}
return bf.toString();
}
private TransUnitInfo2TranslationBean getTransUnitInfo(VTDUtils vu) throws XPathParseException, XPathEvalException,
NavException {
TransUnitInfo2TranslationBean tuInfo = new TransUnitInfo2TranslationBean();
vu.getVTDNav().push();
AutoPilot sourceAp = new AutoPilot(vu.getVTDNav());
sourceAp.selectXPath("./source");
String fullText = "";
String pureText = "";
if (sourceAp.evalXPath() != -1) {
fullText = vu.getElementContent();
pureText = xlfHandler.getTUPureText(vu.getVTDNav());
}
vu.getVTDNav().pop();
if (fullText == null || fullText.equals("") || pureText.equals("")) {
return null;
}
tuInfo.setSrcFullText(fullText);
tuInfo.setSrcPureText(pureText);
return tuInfo;
}
}
| 11,031 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SimpleMatcherBingImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/SimpleMatcherBingImpl.java | /**
* SimpleMatcherBingImpl.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import net.heartsome.cat.common.util.InnerTagClearUtil;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.machinetranslation.bean.PrefrenceParameters;
import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean;
import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher;
import com.memetix.mst.translate.Translate;
/**
* http://code.google.com/p/microsoft-translator-java-api/
* @author jason
* @version
* @since JDK1.6
*/
public class SimpleMatcherBingImpl implements ISimpleMatcher {
private PrefrenceParameters parameters = PrefrenceParameters.getInstance();
private String type = "Bing";
private String toolId = "Bing Translation";
private String origin = "Bing Translation";
/**
*
*/
public SimpleMatcherBingImpl() {
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#getMatcherOrigin()
*/
public String getMatcherType() {
return type;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#getMathcerToolId()
*/
public String getMathcerToolId() {
return toolId;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#matchChecker()
*/
public boolean matchChecker() {
if (!parameters.isBingState()) {
return false;
}
if(!parameters.isAlwaysAccess()){
return false;
}
return true;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#executeMatch(net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean)
*/
public String executeMatch(TransUnitInfo2TranslationBean tuInfo) {
try {
String srcText = tuInfo.getSrcPureText();
String srcLang = tuInfo.getSrcLanguage();
String tgtLang = tuInfo.getTgtLangugage();
String bingId = parameters.getBingId();
String bingKey = parameters.getBingKey();
Translate.setClientId(bingId);
Translate.setClientSecret(bingKey);
String result = Translate.execute(srcText, BingTransUtils.processLanguage(srcLang),
BingTransUtils.processLanguage(tgtLang));
result=TextUtil.convertMachineTranslateResult(result);
if (result != null) {
return InnerTagClearUtil.clearTmx4Xliff(result);
}
} catch (Exception e) {
return "";
}
return "";
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#isSuportPreTrans()
*/
public boolean isSuportPreTrans() {
if(parameters != null){
return parameters.isBingState();
}
return false;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#isOverwriteMatch()
*/
public boolean isOverwriteMatch() {
/*return parameters.isAlwaysAccess();*/
return false;
}
public String getMathcerOrigin() {
return origin;
}
public static void main(String arg[]) {
Translate.setClientId("Bing_Client_ID");
Translate.setClientSecret("tEIlN/kkAFGFaNve4Q3q85sB6QARrlf2pMyBkuIgTjs=");
String result;
try {
result = Translate.execute(" < Obey all safety <>messages that follow this symbol to avoid possible injury or death.", BingTransUtils.processLanguage("en-US"), BingTransUtils.processLanguage("zh-CN"));
// 是否有已经转义的字符
System.out.println(result);
String resetSpecialString = TextUtil.resetSpecialString(result);
System.out.println(resetSpecialString);
result = TextUtil.cleanSpecialString(resetSpecialString);
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 4,193 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SimpleMatcherGoogleImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/SimpleMatcherGoogleImpl.java | /**
* SimpleMatcherGoogleImpl.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation;
import net.heartsome.cat.common.util.InnerTagClearUtil;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.machinetranslation.bean.PrefrenceParameters;
import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean;
import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher;
import com.google.api.GoogleAPI;
import com.google.api.GoogleAPIException;
import com.google.api.translate.Translate;
/**
* http://code.google.com/p/google-api-translate-java/
* @author jason
* @version
* @since JDK1.6
*/
public class SimpleMatcherGoogleImpl implements ISimpleMatcher {
private PrefrenceParameters parameters = PrefrenceParameters.getInstance();
private String type = "Google";
private String toolId = "Google Translation";
private String origin = "Google Translation";
/**
*
*/
public SimpleMatcherGoogleImpl() {
String googleKey = this.parameters.getGoolgeKey();
GoogleAPI.setHttpReferrer("http://www.heartsome.net");
GoogleAPI.setKey(googleKey);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#matchChecker()
*/
public boolean matchChecker() {
if (!parameters.isGoogleState()) {
return false;
}
if(parameters.isManualAccess()){
return false;
}
return true;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#executeMatch(net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean)
*/
public String executeMatch(TransUnitInfo2TranslationBean tuInfo) {
try {
String srcText = tuInfo.getSrcPureText();
String srcLang = tuInfo.getSrcLanguage();
String tgtLang = tuInfo.getTgtLangugage();
String result = Translate.DEFAULT.execute(srcText, GoogleTransUtils.processLanguage(srcLang),
GoogleTransUtils.processLanguage(tgtLang));
result=TextUtil.convertMachineTranslateResult(result);
if (result != null) {
return InnerTagClearUtil.clearTmx4Xliff(result);
}
} catch (GoogleAPIException e) {
return "";
}
return "";
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#isSuportPreTrans()
*/
public boolean isSuportPreTrans() {
if (parameters != null) {
return parameters.isGoogleState();
}
return false;
}
public boolean isOverwriteMatch() {
/*if (parameters != null) {
return parameters.isAlwaysAccess();
}*/
return false;
}
public String getMatcherType() {
return type;
}
public String getMathcerToolId() {
return toolId;
}
public String getMathcerOrigin() {
return origin;
}
}
| 3,215 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MachineTranslationPreferenceInitializer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/prefrence/MachineTranslationPreferenceInitializer.java | /**
* GooglTransPreferenceInitializer.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.prefrence;
import net.heartsome.cat.ts.machinetranslation.Activator;
import net.heartsome.cat.ts.machinetranslation.bean.IPreferenceConstant;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class MachineTranslationPreferenceInitializer extends AbstractPreferenceInitializer {
/** (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
IPreferenceStore ps = Activator.getDefault().getPreferenceStore();
ps.setDefault(IPreferenceConstant.GOOGLE_STATE, false);
ps.setDefault(IPreferenceConstant.GOOGLE_KEY, "");
ps.setDefault(IPreferenceConstant.BING_ID, "");
ps.setDefault(IPreferenceConstant.BING_KEY, "");
ps.setDefault(IPreferenceConstant.BING_STATE, false);
ps.setDefault(IPreferenceConstant.ALWAYS_ACCESS, false);
ps.setDefault(IPreferenceConstant.MANUAL_ACCESS, true);
ps.setDefault(IPreferenceConstant.IGNORE_EXACT_MATCH, true);
ps.setDefault(IPreferenceConstant.INGORE_LOCK, true);
}
}
| 1,900 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MachineTranslationPreferencePage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/prefrence/MachineTranslationPreferencePage.java | /**
* GooglePreferencePage.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.prefrence;
import net.heartsome.cat.common.ui.HsImageLabel;
import net.heartsome.cat.ts.machinetranslation.Activator;
import net.heartsome.cat.ts.machinetranslation.BingTransUtils;
import net.heartsome.cat.ts.machinetranslation.GoogleTransUtils;
import net.heartsome.cat.ts.machinetranslation.bean.IPreferenceConstant;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.ui.bean.TranslateParameter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import com.google.api.GoogleAPI;
import com.google.api.GoogleAPIException;
import com.google.api.translate.Translate;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class MachineTranslationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public static final String ID = "net.heartsome.cat.ts.machinetranslation.prefrence.MachineTranslationPreferencePage";
private IPreferenceStore ps;
private Label googleStateLabel;
private Label bingStateLable;
private Image rightImage;
private Image errorImage;
private Text googleKeyText;
private boolean googleState;
private boolean bingState;
private Text idText;
private Text bingKeyText;
// accessibility widget
private Button alwaysAccessBtn;
private Button manualAccessBtn;
private Button ignoreExactMatchBtn;
private Button ignoreLockBtn;
/**
* constructor
*/
public MachineTranslationPreferencePage() {
setPreferenceStore(Activator.getDefault().getPreferenceStore());
ps = getPreferenceStore();
googleState = ps.getBoolean(IPreferenceConstant.GOOGLE_STATE);
bingState = ps.getBoolean(IPreferenceConstant.BING_STATE);
rightImage = Activator.getImageDescriptor("images/right.png").createImage();
errorImage = Activator.getImageDescriptor("images/error.png").createImage();
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
// private Label label;
/**
* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Composite tparent = new Composite(parent, SWT.NONE);
tparent.setLayout(new GridLayout(1, false));
tparent.setLayoutData(new GridData(GridData.FILL_BOTH));
createGoogleTranslateArea(tparent);
createBingTranslateArea(tparent);
createIgnoreArea(tparent);
createTranslateSettingArea(tparent);
// 设置界面的值
setValues();
// 设置界面状态
setComponentsState();
return parent;
}
private Composite createGoogleTranslateArea(Composite tparent) {
Group apiKeySettingGroup = new Group(tparent, SWT.NONE);
apiKeySettingGroup.setText(Messages.getString("preference.GooglePreferencePage.apiKeySettingGroup"));
apiKeySettingGroup.setLayout(new GridLayout(1, false));
apiKeySettingGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
HsImageLabel test = new HsImageLabel(Messages.getString("preference.GooglePreferencePage.lbKeySetting"),
Activator.getImageDescriptor("images/trans_google_key_32.png"));
Composite com = test.createControl(apiKeySettingGroup);
com.setLayout(new GridLayout(3, false));
Label lblApiKey = new Label(com, SWT.NONE);
lblApiKey.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblApiKey.setText(Messages.getString("preference.GooglePreferencePage.lblApiKey"));
googleKeyText = new Text(com, SWT.BORDER);
googleKeyText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
googleStateLabel = new Label(com, SWT.NONE);
googleStateLabel.setImage(errorImage);
new Label(com, SWT.NONE);
Button validateKey = new Button(com, SWT.NONE);
validateKey.setText(Messages.getString("preference.GooglePreferencePage.validateKey"));
validateKey.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String key = googleKeyText.getText();
if (key == null || key.equals("")) {
MessageDialog.openError(getShell(), Messages.getString("preference.GooglePreferencePage.msgTitle"),
Messages.getString("preference.GooglePreferencePage.msg1"));
return;
}
googleValidator();
setComponentsState();
if (!googleState) {
MessageDialog.openError(getShell(), Messages.getString("preference.GooglePreferencePage.msgTitle"),
Messages.getString("preference.GooglePreferencePage.msg2"));
return;
}
}
});
new Label(com, SWT.NONE);
new Label(com, SWT.NONE);
Link link = new Link(com, SWT.NONE);
link.setText("<a>" + Messages.getString("preference.GooglePreferencePage.link") + "</a>");
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Program.launch("http://code.google.com/apis/language/translate/v2/getting_started.html");
}
});
link.setToolTipText("http://code.google.com/apis/language/translate/v2/getting_started.html");
new Label(com, SWT.NONE);
test.computeSize();
return tparent;
}
private Composite createBingTranslateArea(Composite tparent) {
Group apiKeySettingGroup = new Group(tparent, SWT.NONE);
apiKeySettingGroup.setText(Messages.getString("preference.BingPreferencePage.apiKeySettingGroup"));
apiKeySettingGroup.setLayout(new GridLayout(1, false));
apiKeySettingGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
HsImageLabel lbKeySetting = new HsImageLabel(Messages.getString("preference.BingPreferencePage.lbKeySetting"),
Activator.getImageDescriptor("images/trans_bing_key_32.png"));
Composite com = lbKeySetting.createControl(apiKeySettingGroup);
com.setLayout(new GridLayout(3, false));
Label lblId = new Label(com, SWT.NONE);
lblId.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblId.setText(Messages.getString("preference.BingPreferencePage.lblId"));
idText = new Text(com, SWT.BORDER);
idText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(com, SWT.NONE);
Label lblApiKey = new Label(com, SWT.NONE);
lblApiKey.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblApiKey.setText(Messages.getString("preference.BingPreferencePage.lblApiKey"));
bingKeyText = new Text(com, SWT.BORDER);
bingKeyText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
bingStateLable = new Label(com, SWT.NONE);
bingStateLable.setImage(errorImage);
new Label(com, SWT.NONE);
Button validateKey = new Button(com, SWT.NONE);
validateKey.setText(Messages.getString("preference.BingPreferencePage.validateKey"));
validateKey.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String id = idText.getText();
String bingKey = bingKeyText.getText();
if (id == null || id.equals("")) {
MessageDialog.openInformation(getShell(),
Messages.getString("preference.BingPreferencePage.msgTitle"),
Messages.getString("preference.BingPreferencePage.msg1"));
return;
}
if (bingKey == null || bingKey.equals("")) {
MessageDialog.openInformation(getShell(),
Messages.getString("preference.BingPreferencePage.msgTitle"),
Messages.getString("preference.BingPreferencePage.msg2"));
return;
}
bingValidator();
setComponentsState();
if (!bingState) {
MessageDialog.openInformation(getShell(),
Messages.getString("preference.BingPreferencePage.msgTitle"),
Messages.getString("preference.BingPreferencePage.msg3"));
return;
}
}
});
new Label(com, SWT.NONE);
new Label(com, SWT.NONE);
Link link = new Link(com, SWT.NONE);
link.setText("<a>" + Messages.getString("preference.BingPreferencePage.link") + "</a>");
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Program.launch("http://msdn.microsoft.com/en-us/library/hh454950.aspx");
}
});
link.setToolTipText("http://msdn.microsoft.com/en-us/library/hh454950.aspx");
new Label(com, SWT.NONE);
lbKeySetting.computeSize();
return tparent;
}
private Composite createIgnoreArea(Composite tparent) {
Group ignoreGroup = new Group(tparent, SWT.NONE);
GridDataFactory.createFrom(new GridData(GridData.FILL_HORIZONTAL)).applyTo(ignoreGroup);
GridLayoutFactory.swtDefaults().numColumns(1).applyTo(ignoreGroup);
ignoreGroup.setText(Messages.getString("dialog.PreMachineTranslationDialog.ignore"));
ignoreExactMatchBtn = new Button(ignoreGroup, SWT.CHECK);
ignoreExactMatchBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.exactmatch"));
ignoreLockBtn = new Button(ignoreGroup, SWT.CHECK);
ignoreLockBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.lock"));
return tparent;
}
private Composite createTranslateSettingArea(Composite tparent) {
Group apiAccessibilityGroup = new Group(tparent, SWT.NONE);
apiAccessibilityGroup.setLayout(new GridLayout(1, false));
apiAccessibilityGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
apiAccessibilityGroup.setText(Messages.getString("preference.machinetranslattionPage.accessMachineServer"));
HsImageLabel accessibility = new HsImageLabel(
Messages.getString("preference.machinetranslattionPage.accessMachineServer.msg"),
Activator.getImageDescriptor("images/trans_google_set_32.png"));
Composite accessibilityComp = accessibility.createControl(apiAccessibilityGroup);
accessibilityComp.setLayout(new GridLayout());
alwaysAccessBtn = new Button(accessibilityComp, SWT.RADIO);
alwaysAccessBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
alwaysAccessBtn.setText(Messages.getString("preference.GooglePreferencePage.alwaysAccessBtn"));
alwaysAccessBtn.setEnabled(false);
alwaysAccessBtn.setSelection(false);
manualAccessBtn = new Button(accessibilityComp, SWT.RADIO);
manualAccessBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
manualAccessBtn.setText(Messages.getString("preference.GooglePreferencePage.neverAccessBtn"));
manualAccessBtn.setEnabled(false);
manualAccessBtn.setSelection(false);
accessibility.computeSize();
return tparent;
}
@Override
protected void performDefaults() {
setDefaultValues();
}
@Override
protected void performApply() {
super.performApply();
}
@Override
public boolean performOk() {
googleValidator();
bingValidator();
// if(this.bingState){
ps.setValue(IPreferenceConstant.BING_STATE, this.bingState);
ps.setValue(IPreferenceConstant.BING_ID, idText.getText());
ps.setValue(IPreferenceConstant.BING_KEY, bingKeyText.getText());
// }
// if(this.googleState){
ps.setValue(IPreferenceConstant.GOOGLE_KEY, googleKeyText.getText());
ps.setValue(IPreferenceConstant.GOOGLE_STATE, this.googleState);
// }
ps.setValue(IPreferenceConstant.ALWAYS_ACCESS, alwaysAccessBtn.getSelection());
ps.setValue(IPreferenceConstant.MANUAL_ACCESS, manualAccessBtn.getSelection());
ps.setValue(IPreferenceConstant.IGNORE_EXACT_MATCH, ignoreExactMatchBtn.getSelection());
ps.setValue(IPreferenceConstant.INGORE_LOCK, ignoreLockBtn.getSelection());
setComponentsState();
return true;
}
/**
* 访问goolge api以验证 Key是否可用。 ;
*/
private void googleValidator() {
final String googleKey = googleKeyText.getText();
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
// TODO Auto-generated method stub
if (googleKey != null && !googleKey.trim().equals("")) {
GoogleAPI.setHttpReferrer("http://www.heartsome.net");
GoogleAPI.setKey(googleKey);
try {
String result = Translate.DEFAULT.execute("test", GoogleTransUtils.processLanguage("en-US"),
GoogleTransUtils.processLanguage("zh-CN"));
if (result.equals("测试")) {
googleState = true;
}
} catch (GoogleAPIException e) {
googleState = false;
}
} else {
googleState = false;
}
}
});
}
/**
* 访问bing api是否可用 ;
*/
private void bingValidator() {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
String id = idText.getText();
String bingKey = bingKeyText.getText();
if (bingKey != null && !bingKey.trim().equals("") && id != null && !id.equals("")) {
com.memetix.mst.translate.Translate.setClientId(id);
com.memetix.mst.translate.Translate.setClientSecret(bingKey);
try {
String result = com.memetix.mst.translate.Translate.execute("test",
BingTransUtils.processLanguage("en-US"), BingTransUtils.processLanguage("zh-CN"));
if (result.equals("测试")) {
bingState = true;
} else {
bingState = false;
}
} catch (Exception e) {
bingState = false;
}
} else {
bingState = false;
}
}
});
}
private void setDefaultValues() {
boolean goolgeDefault = ps.getDefaultBoolean(IPreferenceConstant.GOOGLE_STATE);
// ps.setValue(IPreferenceConstant.GOOGLE_STATE, goolgeDefault);
this.googleState = goolgeDefault;
String goolgeKey = ps.getDefaultString(IPreferenceConstant.GOOGLE_KEY);
// ps.setValue(IPreferenceConstant.GOOGLE_KEY, goolgeKey);
this.googleKeyText.setText(goolgeKey);
boolean bingState = ps.getDefaultBoolean(IPreferenceConstant.BING_STATE);
// ps.setValue(IPreferenceConstant.BING_STATE, bingState);
this.bingState = bingState;
String bingId = ps.getDefaultString(IPreferenceConstant.BING_ID);
// ps.setValue(IPreferenceConstant.BING_ID, bingId);
this.idText.setText(bingId);
String bingKey = ps.getDefaultString(IPreferenceConstant.BING_KEY);
// ps.setValue(IPreferenceConstant.BING_KEY, bingKey);
this.bingKeyText.setText(bingKey);
boolean awaysAccess = ps.getDefaultBoolean(IPreferenceConstant.ALWAYS_ACCESS);
this.alwaysAccessBtn.setSelection(awaysAccess);
boolean mamualAccess = ps.getDefaultBoolean(IPreferenceConstant.MANUAL_ACCESS);
this.manualAccessBtn.setSelection(mamualAccess);
this.ignoreExactMatchBtn.setSelection(ps.getDefaultBoolean(IPreferenceConstant.IGNORE_EXACT_MATCH));
this.ignoreLockBtn.setSelection(ps.getDefaultBoolean(IPreferenceConstant.INGORE_LOCK));
setComponentsState();
}
private void setValues() {
this.googleState = ps.getBoolean(IPreferenceConstant.GOOGLE_STATE);
this.googleKeyText.setText(ps.getString(IPreferenceConstant.GOOGLE_KEY));
this.bingState = ps.getBoolean(IPreferenceConstant.BING_STATE);
this.bingKeyText.setText(ps.getString(IPreferenceConstant.BING_KEY));
this.idText.setText(ps.getString(IPreferenceConstant.BING_ID));
this.ignoreExactMatchBtn.setSelection(ps.getBoolean(IPreferenceConstant.IGNORE_EXACT_MATCH));
this.ignoreLockBtn.setSelection(ps.getBoolean(IPreferenceConstant.INGORE_LOCK));
setComponentsState();
}
/**
* 设置组件的状态 ;
*/
private void setComponentsState() {
// 设置google标签的状态
if (this.googleState) {
googleStateLabel.setImage(rightImage);
} else {
googleStateLabel.setImage(errorImage);
}
if (this.bingState) {
bingStateLable.setImage(rightImage);
} else {
bingStateLable.setImage(errorImage);
}
// 设置访问策略的状态
if (this.googleState || this.bingState) {
alwaysAccessBtn.setEnabled(true);
alwaysAccessBtn.setSelection(ps.getBoolean(IPreferenceConstant.ALWAYS_ACCESS));
manualAccessBtn.setEnabled(true);
manualAccessBtn.setSelection(ps.getBoolean(IPreferenceConstant.MANUAL_ACCESS));
} else {
alwaysAccessBtn.setEnabled(false);
manualAccessBtn.setEnabled(false);
// alwaysAccessBtn.setSelection(false);
// manualAccessBtn.setSelection(false);
}
}
@Override
public void dispose() {
if (rightImage != null) {
rightImage.dispose();
}
if (errorImage != null) {
errorImage.dispose();
}
super.dispose();
}
}
| 17,489 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PrefrenceParameters.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/bean/PrefrenceParameters.java | /**
* PrefrenceParameters.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.bean;
import net.heartsome.cat.ts.machinetranslation.Activator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class PrefrenceParameters implements IPropertyChangeListener {
/**
* goolge key
*/
private String goolgeKey ;
/**
* goolge state
*/
private boolean googleState;
private boolean bingState;
private String bingId;
private String bingKey;
private boolean isAlwaysAccess;
private boolean isManualAccess;
private IPreferenceStore ps;
private static PrefrenceParameters instance;
public static PrefrenceParameters getInstance() {
if (instance == null) {
instance = new PrefrenceParameters();
}
return instance;
}
private PrefrenceParameters() {
ps = Activator.getDefault().getPreferenceStore();
ps.addPropertyChangeListener(this);
loadPrefrence();
}
private void loadPrefrence() {
if (ps != null) {
googleState = ps.getBoolean(IPreferenceConstant.GOOGLE_STATE);
goolgeKey = ps.getString(IPreferenceConstant.GOOGLE_KEY);
bingId = ps.getString(IPreferenceConstant.BING_ID);
bingKey = ps.getString(IPreferenceConstant.BING_KEY);
bingState = ps.getBoolean(IPreferenceConstant.BING_STATE);
isAlwaysAccess = ps.getBoolean(IPreferenceConstant.ALWAYS_ACCESS);
isManualAccess = ps.getBoolean(IPreferenceConstant.MANUAL_ACCESS);
}
}
public void propertyChange(PropertyChangeEvent event) {
loadPrefrence();
}
/**
* 返回访问API的策略, 没有指定访问策略则返回一个空串,如果有策略则返回对的首选项参数名称
* @return
*/
public String getAccessStrategy() {
if (isAlwaysAccess) {
return IPreferenceConstant.ALWAYS_ACCESS;
}
if (isManualAccess) {
return IPreferenceConstant.MANUAL_ACCESS;
}
return "";
}
/**
* 是否总是访问API
* @return the isAlwaysAccess
*/
public boolean isAlwaysAccess() {
return isAlwaysAccess;
}
/**
* 是否从不访问API
* @return the isNeverAccess
*/
public boolean isManualAccess() {
return isManualAccess;
}
/** @return the goolgeKey */
public String getGoolgeKey() {
return goolgeKey;
}
/** @return the googleState */
public boolean isGoogleState() {
return googleState;
}
/** @return the bingState */
public boolean isBingState() {
return bingState;
}
/** @return the bingId */
public String getBingId() {
return bingId;
}
/** @return the bingKey */
public String getBingKey() {
return bingKey;
}
}
| 3,276 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTransParameters.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/bean/PreMachineTransParameters.java | /**
* PreTransParameters.java
*
* Version information :
*
* Date:2012-5-8
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.bean;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class PreMachineTransParameters {
/**
* 是否使用goolge翻译
*/
private boolean isGoogleTranslate;
/**
* 是否使用bing翻译
*/
private boolean isBingTranslate;
/**
* 是否忽略完全匹配
*/
private boolean isIgnoreExactMatch;
/**
* 是否忽略锁定
*/
private boolean isIgnoreLock;
/**
* 机器翻译首选项值
*/
private PrefrenceParameters pefrenceParameters;
/** @return the isGoogleTranslate */
public boolean isGoogleTranslate() {
return isGoogleTranslate;
}
/** @param isGoogleTranslate the isGoogleTranslate to set */
public void setGoogleTranslate(boolean isGoogleTranslate) {
this.isGoogleTranslate = isGoogleTranslate;
}
/** @return the isBingTranslate */
public boolean isBingTranslate() {
return isBingTranslate;
}
/** @param isBingTranslate the isBingTranslate to set */
public void setBingTranslate(boolean isBingTranslate) {
this.isBingTranslate = isBingTranslate;
}
/** @return the isIgnoreExactMatch */
public boolean isIgnoreExactMatch() {
return isIgnoreExactMatch;
}
/** @param isIgnoreExactMatch the isIgnoreExactMatch to set */
public void setIgnoreExactMatch(boolean isIgnoreExactMatch) {
this.isIgnoreExactMatch = isIgnoreExactMatch;
}
/** @return the isIgnoreLock */
public boolean isIgnoreLock() {
return isIgnoreLock;
}
/** @param isIgnoreLock the isIgnoreLock to set */
public void setIgnoreLock(boolean isIgnoreLock) {
this.isIgnoreLock = isIgnoreLock;
}
/** @return the pefrenceParameters */
public PrefrenceParameters getPefrenceParameters() {
return PrefrenceParameters.getInstance();
}
/** @param pefrenceParameters the pefrenceParameters to set */
public void setPefrenceParameters(PrefrenceParameters pefrenceParameters) {
this.pefrenceParameters = pefrenceParameters;
}
}
| 2,558 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IPreferenceConstant.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/bean/IPreferenceConstant.java | /**
* IPreferenceConstant.java
*
* Version information :
*
* Date:2012-5-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.bean;
/**
* 机器翻译首选项常量
* @author jason
* @version
* @since JDK1.6
*/
public interface IPreferenceConstant {
// google
/**
* 当前google 翻译状态,用于记录当前是否通过了验证
*/
String GOOGLE_STATE = "net.heartsome.cat.ts.googletrans.state";
/** Google 翻译的Key */
String GOOGLE_KEY = "net.heartsome.cat.ts.googletrans.key";
//bing
/**
* 当前bing 翻译状态,用于记录当前是否通过了验证
*/
String BING_STATE = "net.heartsome.cat.ts.bingtrans.state";
/** bing 的id*/
String BING_ID = "net.heartsome.cat.ts.bingtrans.id";
/** bing 翻译的Key */
String BING_KEY = "net.heartsome.cat.ts.bingtrans.key";
// 访问策略
/** 总是访问 */
String ALWAYS_ACCESS = "net.heartsome.cat.ts.googletrans.always";
/*** 手动访问 */
String MANUAL_ACCESS = "net.heartsome.cat.ts.googletrans.manual";
/**
* 忽略完全匹配和上下文匹配
*/
String IGNORE_EXACT_MATCH="net.heartsome.cat.ts.machineTranslate.ignoreexactmatch";
/**
* 忽略锁定的文本段
*/
String INGORE_LOCK="net.heartsome.cat.ts.machineTranslate.ignorelock";
}
| 1,827 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTranslationCounter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/bean/PreMachineTranslationCounter.java | /**
* PreTranslationCounter.java
*
* Version information :
*
* Date:2012-5-10
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.bean;
/**
* 预翻译计数器,用于对预翻译的文件进行统计
* @author jason
* @version
* @since JDK1.6
*/
public class PreMachineTranslationCounter {
private int transTuCount = 0;
private int lockedFullCount = 0;
private int lockedContextCount = 0;
private int tuNumber = 0;
private String currentFile = "";
public PreMachineTranslationCounter(String file) {
this.currentFile = file;
}
public void countTransTu() {
this.transTuCount++;
}
public void countLockedFullMatch() {
this.lockedFullCount++;
}
public void countLockedContextmatch() {
this.lockedContextCount++;
}
/** @return the transTuCount */
public int getTransTuCount() {
return transTuCount;
}
/** @return the lockedFullCount */
public int getLockedFullCount() {
return lockedFullCount;
}
/** @return the lockedContextCount */
public int getLockedContextCount() {
return lockedContextCount;
}
/** @return the tuNumber */
public int getTuNumber() {
return tuNumber;
}
/**
* @param tuNumber
* the tuNumber to set
*/
public void setTuNumber(int tuNumber) {
this.tuNumber = tuNumber;
}
/** @return the currentFile */
public String getCurrentFile() {
return currentFile;
}
}
| 1,903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTranslationResultDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/dialog/PreMachineTranslationResultDialog.java | /**
* PreTranslationResultDialog.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.dialog;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTranslationCounter;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
/**
* 预翻译结果显示对话框
* @author Jason
* @version
* @since JDK1.6
*/
public class PreMachineTranslationResultDialog extends Dialog {
private TableViewer tableViewer;
List<PreMachineTranslationCounter> preTransResult;
/**
* Create the dialog.
* @param parentShell
*/
public PreMachineTranslationResultDialog(Shell parentShell, List<PreMachineTranslationCounter> preTransResult) {
super(parentShell);
this.preTransResult = preTransResult;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.PreTranslationResultDialog.title"));
}
/**
* Create contents of the dialog.
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new GridLayout(1, false));
Composite composite = new Composite(container, SWT.NONE);
GridLayout gl_composite = new GridLayout(1, false);
gl_composite.verticalSpacing = 0;
gl_composite.marginWidth = 0;
gl_composite.marginHeight = 0;
composite.setLayout(gl_composite);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL);
Table table = tableViewer.getTable();
GridData tableGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
tableGd.heightHint = 220;
table.setLayoutData(tableGd);
table.setLinesVisible(true);
table.setHeaderVisible(true);
String[] clmnTitles = new String[] { Messages.getString("dialog.PreTranslationResultDialog.clmnTitles1"),
Messages.getString("dialog.PreTranslationResultDialog.clmnTitles2"),
Messages.getString("dialog.PreTranslationResultDialog.clmnTitles3"),
Messages.getString("dialog.PreTranslationResultDialog.clmnTitles4"),
Messages.getString("dialog.PreTranslationResultDialog.clmnTitles5"),
Messages.getString("dialog.PreTranslationResultDialog.clmnTitles6") };
int[] clmnBounds = { 60, 200, 100, 110, 110, 110 };
for (int i = 0; i < clmnTitles.length; i++) {
createTableViewerColumn(tableViewer, clmnTitles[i], clmnBounds[i], i);
}
tableViewer.setLabelProvider(new TableViewerLabelProvider());
tableViewer.setContentProvider(new ArrayContentProvider());
tableViewer.setInput(this.getTableViewerInput());
return container;
}
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
private String[][] getTableViewerInput() {
String wPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
List<String[]> rows = new ArrayList<String[]>();
int i = 1;
for (PreMachineTranslationCounter counter : preTransResult) {
String iFilePath = counter.getCurrentFile().replace(wPath, "");
String[] row = new String[] { (i++) + "", iFilePath, counter.getTuNumber() + "",
counter.getTransTuCount() + "", counter.getLockedContextCount() + "",
counter.getLockedFullCount() + "" };
rows.add(row);
}
return rows.toArray(new String[][] {});
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* tableViewer的标签提供器
* @author Jason
*/
class TableViewerLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof String[]) {
String[] array = (String[]) element;
return array[columnIndex];
}
return null;
}
}
/**
* @param tableViewer
* the tableViewer to set
*/
public void setTableViewer(TableViewer tableViewer) {
this.tableViewer = tableViewer;
}
public boolean close() {
this.preTransResult.clear();
this.preTransResult = null;
return super.close();
}
}
| 6,454 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreMachineTranslationDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/dialog/PreMachineTranslationDialog.java | /**
* PreTranslationDialog.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.dialog;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.core.bean.XliffBean;
import net.heartsome.cat.ts.machinetranslation.Activator;
import net.heartsome.cat.ts.machinetranslation.bean.IPreferenceConstant;
import net.heartsome.cat.ts.machinetranslation.bean.PreMachineTransParameters;
import net.heartsome.cat.ts.machinetranslation.prefrence.MachineTranslationPreferencePage;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.ui.composite.DialogLogoCmp;
import net.heartsome.cat.ts.ui.util.PreferenceUtil;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.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.Group;
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.eclipse.ui.PlatformUI;
/**
* 预翻译信息显示对话框,用于展示文件列表
* @author Jason
* @version
* @since JDK1.6
*/
public class PreMachineTranslationDialog extends TrayDialog {
private TableViewer viewer;
private Map<String, List<XliffBean>> xliffInofs;
private PreMachineTransParameters paramerters;
private Button googleBtn;
private Button bingBtn;
//private Button ignoreExactMatchBtn;
// private Button ignoreLockBtn;
/**
* TODO :logo 图标
*/
private Image logoImage = Activator.getImageDescriptor("images/pre-machine-translation-logo.png").createImage();
/**
* Create the dialog.
* @param parentShell
* @param parameters
*/
public PreMachineTranslationDialog(Shell parentShell, Map<String, List<XliffBean>> xliffInofs,
PreMachineTransParameters paramerters) {
super(parentShell);
this.xliffInofs = xliffInofs;
this.paramerters = paramerters;
setHelpAvailable(true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.PreMachineTranslationDialog.title"));
}
// TODO :帮助按钮URL需要修改
/**
* 添加帮助按钮 robert 2012-09-06
*/
@Override
protected Control createHelpControl(Composite parent) {
// ROBERTHELP 预翻译
String language = CommonFunction.getSystemLanguage();
final String helpUrl = MessageFormat.format(
"/net.heartsome.cat.ts.ui.help/html/{0}/ch05s03.html?#prestore-mt", language);
Image helpImage = JFaceResources.getImage(DLG_IMG_HELP);
ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS);
((GridLayout) parent.getLayout()).numColumns++;
toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
toolBar.setCursor(cursor);
toolBar.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
cursor.dispose();
}
});
ToolItem helpItem = new ToolItem(toolBar, SWT.NONE);
helpItem.setImage(helpImage);
helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$
helpItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl);
}
});
return toolBar;
}
/**
* Create contents of the dialog.
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
GridLayoutFactory.fillDefaults().extendedMargins(-1, -1, -1, 8).numColumns(1).applyTo(container);
createLogoArea(container);
Composite parentCmp = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().extendedMargins(9, 9, 0, 0).numColumns(1).applyTo(parentCmp);
GridDataFactory.fillDefaults().grab(true, true).applyTo(parentCmp);
createInputPageContent(parentCmp);
createSelectArea(parentCmp);
viewer.getTable().setFocus();
return container;
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
/**
* 创建页面内容
* @param parent
* ;
*/
private void createInputPageContent(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout gl_composite = new GridLayout(1, false);
gl_composite.marginHeight = 0;
gl_composite.marginWidth = 0;
gl_composite.verticalSpacing = 0;
composite.setLayout(gl_composite);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
viewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
final Table table = viewer.getTable();
GridData tableGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
tableGd.heightHint = 220;
table.setLayoutData(tableGd);
table.setLinesVisible(true);
table.setHeaderVisible(true);
String[] clmnTitles = new String[] { Messages.getString("dialog.PreTranslationDialog.clmnTitles1"),
Messages.getString("dialog.PreTranslationDialog.clmnTitles2"),
Messages.getString("dialog.PreTranslationDialog.clmnTitles3"),
Messages.getString("dialog.PreTranslationDialog.clmnTitles4") };
int[] clmnBounds = { 80, 250, 100, 100 };
for (int i = 0; i < clmnTitles.length; i++) {
createTableViewerColumn(viewer, clmnTitles[i], clmnBounds[i], i);
}
viewer.setLabelProvider(new TableViewerLabelProvider());
viewer.setContentProvider(new ArrayContentProvider());
viewer.setInput(this.getTableViewerInput());
}
private void createSelectArea(Composite parent) {
Composite selectArea = new Composite(parent, SWT.NONE);
GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(selectArea);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(selectArea);
Group selectGroup = new Group(selectArea, SWT.NONE);
GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(selectGroup);
GridLayoutFactory.swtDefaults().numColumns(1).applyTo(selectGroup);
selectGroup.setText(Messages.getString("dialog.PreMachineTranslationDialog.selectTranlateType"));
googleBtn = new Button(selectGroup, SWT.CHECK);
googleBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.google"));
bingBtn = new Button(selectGroup, SWT.CHECK);
bingBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.bing"));
// Group ignoreGroup = new Group(selectArea, SWT.NONE);
// GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(ignoreGroup);
// GridLayoutFactory.swtDefaults().numColumns(1).applyTo(ignoreGroup);
// ignoreGroup.setText(Messages.getString("dialog.PreMachineTranslationDialog.ignore"));
//
// ignoreExactMatchBtn = new Button(ignoreGroup, SWT.CHECK);
// ignoreExactMatchBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.exactmatch"));
// ignoreLockBtn = new Button(ignoreGroup, SWT.CHECK);
// ignoreLockBtn.setText(Messages.getString("dialog.PreMachineTranslationDialog.lock"));
}
/**
* 从当前的数据库获取需要显示到界面上的数据
* @return ;
*/
private String[][] getTableViewerInput() {
String wPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
Iterator<Entry<String, List<XliffBean>>> it = xliffInofs.entrySet().iterator();
List<String[]> rows = new ArrayList<String[]>();
int index = 1;
while (it.hasNext()) {
Entry<String, List<XliffBean>> entry = it.next();
String filePath = entry.getKey();
String iFilePath = filePath.replace(wPath, ""); // 获取到项目为根的路径
List<XliffBean> xliffBeans = entry.getValue();
// for (int i = 0; i < xliffBeans.size(); i++) {
XliffBean xliffBean = xliffBeans.get(0);
String srcLang = xliffBean.getSourceLanguage();
String tagLang = xliffBean.getTargetLanguage();
String[] rowValue = new String[] { (index++) + "", iFilePath, srcLang, tagLang };
rows.add(rowValue);
// }
}
return rows.toArray(new String[][] {});
}
/**
* tableViewer的标签提供器
* @author Jason
*/
class TableViewerLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof String[]) {
String[] array = (String[]) element;
return array[columnIndex];
}
return null;
}
}
/**
* 显示图片区
* @param parent
*/
public void createLogoArea(Composite parent) {
new DialogLogoCmp(parent, SWT.NONE, Messages.getString("dialog.PreMachineTranslationDialog.title"),
Messages.getString("dialog.PreMachineTranslationDialog.desc"),
logoImage);
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
@Override
protected void okPressed() {
if(!bingBtn.getSelection() && !googleBtn.getSelection()){
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PreMachineTranslationDialog.tips"),
Messages.getString("dialog.PreMachineTranslationDialog.selecttips"));
return;
}
String msg = "";
if(bingBtn.getSelection()){
if(!paramerters.getPefrenceParameters().isBingState()){
msg +=Messages.getString("dialog.PreMachineTranslationDialog.bingtips");
}
}
if(googleBtn.getSelection()){
if(!paramerters.getPefrenceParameters().isGoogleState()){
msg +=Messages.getString("dialog.PreMachineTranslationDialog.goolge.tips");
}
}
if(!msg.isEmpty()){
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PreMachineTranslationDialog.tips"),msg
);
return;
}
paramerters.setBingTranslate(bingBtn.getSelection());
paramerters.setGoogleTranslate(googleBtn.getSelection());
paramerters.setIgnoreExactMatch(Activator.getDefault().getPreferenceStore().getBoolean(IPreferenceConstant.IGNORE_EXACT_MATCH));
paramerters.setIgnoreLock(Activator.getDefault().getPreferenceStore().getBoolean(IPreferenceConstant.INGORE_LOCK));
setReturnCode(OK);
close();
}
/** (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
Button btnSetting = createButton(parent, -1, Messages.getString("dialog.PreMachineTranslationDialog.btnSetting"), true);
super.createButtonsForButtonBar(parent);
btnSetting.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferenceUtil.openPreferenceDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow(), MachineTranslationPreferencePage.ID);
}
});
}
@Override
public boolean close() {
if (logoImage != null && !logoImage.isDisposed()) {
logoImage.dispose();
}
return super.close();
}
}
| 13,222 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExcutePreMachineTranlateHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/handler/ExcutePreMachineTranlateHandler.java | /**
* ExcutePreStoreMachineTranlateHandler.java
*
* Version information :
*
* Date:2013-7-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.handler;
import java.util.List;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.machinetranslation.PreMachineTransUitls;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class ExcutePreMachineTranlateHandler extends AbstractSelectProjectFilesHandler {
public static final Logger logger = LoggerFactory.getLogger(ExcutePreMachineTranlateHandler.class);
private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
@Override
public String[] getLegalFileExtensions() {
return CommonFunction.xlfExtesionArray;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler#execute(org.eclipse.core.commands.ExecutionEvent,
* java.util.List)
*/
@Override
public Object execute(ExecutionEvent event, List<IFile> list) {
if (!CommonFunction.checkEdition("U")) {
MessageDialog.openInformation(shell, Messages.getString("handler.ExcutePreMachineTranlateHandler.tips"),
Messages.getString("handler.ExcutePreMachineTranlateHandler.unsuportversion"));
return null;
}
// 首先验证是否是合并打开的文件 --robert 2012-10-17
if (isEditor) {
try {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorReference[] editorRefe = window.getActivePage().findEditors(new FileEditorInput(list.get(0)),
XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID);
if (editorRefe.length <= 0) {
return null;
}
IXliffEditor xlfEditor = (IXliffEditor) editorRefe[0].getEditor(true);
// 针对合并打开
if (xlfEditor.isMultiFile()) {
list = ResourceUtils.filesToIFiles(xlfEditor.getMultiFileList());
}
} catch (ExecutionException e) {
logger.error("", e);
}
}
CommonFunction.removeRepeateSelect(list);
PreMachineTransUitls.executeTranslation(list, shell);
return null;
}
}
| 3,438 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExecuteGoogleTransHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/handler/ExecuteGoogleTransHandler.java | /**
* ExecuteGoogleTransHandler.java
*
* Version information :
*
* Date:2012-6-11
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.handler;
import net.heartsome.cat.ts.machinetranslation.SimpleMatcherGoogleImpl;
import net.heartsome.cat.ts.machinetranslation.bean.PrefrenceParameters;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.ui.translation.view.MatchViewPart;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class ExecuteGoogleTransHandler extends AbstractHandler {
/**
* (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (!(editor instanceof IXliffEditor)) {
return null;
}
PrefrenceParameters ps = PrefrenceParameters.getInstance();
if (!ps.isGoogleState()) {
MessageDialog.openError(window.getShell(),
Messages.getString("handler.ExecuteGoogleTransHandler.msgTitle"),
Messages.getString("handler.ExecuteGoogleTransHandler.msg"));
return null;
}
final IXliffEditor xliffEditor = (IXliffEditor) editor;
final int[] selectedRowIndexs = xliffEditor.getSelectedRows();
if (selectedRowIndexs.length == 0) {
return null;
}
ISimpleMatcher matcher = new SimpleMatcherGoogleImpl();
IViewPart viewPart = window.getActivePage().findView(MatchViewPart.ID);
if (viewPart != null && viewPart instanceof MatchViewPart) {
MatchViewPart matchView = (MatchViewPart) viewPart;
matchView.manualExecSimpleTranslation(selectedRowIndexs[0], xliffEditor, matcher);
}
return null;
}
}
| 2,820 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExecuteBingTransHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/handler/ExecuteBingTransHandler.java | /**
* ExecuteBingTransHandler.java
*
* Version information :
*
* Date:2012-6-14
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.machinetranslation.handler;
import net.heartsome.cat.ts.machinetranslation.SimpleMatcherBingImpl;
import net.heartsome.cat.ts.machinetranslation.bean.PrefrenceParameters;
import net.heartsome.cat.ts.machinetranslation.resource.Messages;
import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.ui.translation.view.MatchViewPart;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class ExecuteBingTransHandler extends AbstractHandler {
/**
* (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (!(editor instanceof IXliffEditor)) {
return null;
}
// check the google translation state: check the key availability
PrefrenceParameters ps = PrefrenceParameters.getInstance();
if (!ps.isBingState()) {
MessageDialog.openError(window.getShell(), Messages.getString("handler.ExecuteBingTransHandler.msgTitle"),
Messages.getString("handler.ExecuteBingTransHandler.msg"));
return null;
}
final IXliffEditor xliffEditor = (IXliffEditor) editor;
final int[] selectedRowIndexs = xliffEditor.getSelectedRows();
if (selectedRowIndexs.length == 0) {
return null;
}
ISimpleMatcher matcher = new SimpleMatcherBingImpl();
IViewPart viewPart = window.getActivePage().findView(MatchViewPart.ID);
if (viewPart != null && viewPart instanceof MatchViewPart) {
MatchViewPart matchView = (MatchViewPart) viewPart;
matchView.manualExecSimpleTranslation(selectedRowIndexs[0], xliffEditor, matcher);
}
return null;
}
}
| 2,871 | 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.machinetranslation/src/net/heartsome/cat/ts/machinetranslation/resource/Messages.java | package net.heartsome.cat.ts.machinetranslation.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.machinetranslation.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 580 | 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.fuzzyTranslation/src/net/heartsome/cat/ts/fuzzytranslation/Activator.java | package net.heartsome.cat.ts.fuzzytranslation;
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.fuzzyTranslation"; //$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;
}
}
| 1,062 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExecuteFuzzyTranslationHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.fuzzyTranslation/src/net/heartsome/cat/ts/fuzzytranslation/handler/ExecuteFuzzyTranslationHandler.java | package net.heartsome.cat.ts.fuzzytranslation.handler;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.ts.core.file.RepeatRowSearcher;
import net.heartsome.cat.ts.core.file.XLFHandler;
import net.heartsome.cat.ts.fuzzytranslation.resource.Messages;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.utils.NattableUtil;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 执行繁殖翻译(繁殖翻译不求匹配率,不查询数据库,只在文件内部繁殖源文本相同的文本段)
* @author robert 2012-04-02
* @version
* @since JDK1.6
*/
public class ExecuteFuzzyTranslationHandler extends AbstractHandler {
private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IEditorPart editor = window.getActivePage().getActiveEditor();
if (!XLIFF_EDITOR_ID.equals(editor.getSite().getId())) {
return null;
}
final XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) editor;
final NattableUtil util = NattableUtil.getInstance(nattable);
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
// monitor.beginTask(Messages.getString("translation.ExecuteFuzzyTranslationHandler.task1"), 8);
// 首选获取有译文的trans-unit
monitor.beginTask(Messages.getString("translation.ExecuteFuzzyTranslationHandler.task2"), 10);
XLFHandler handler = nattable.getXLFHandler();
Map<String, List<String>> rowIdMap = new HashMap<String, List<String>>();
rowIdMap = RepeatRowSearcher.getRepeateRowsForFuzzy(handler);
monitor.worked(1);
util.propagateTranslations(rowIdMap, monitor);
monitor.done();
}
};
try {
new ProgressMonitorDialog(nattable.getEditorSite().getShell()).run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
nattable.autoResize();
return null;
}
}
| 2,745 | 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.fuzzyTranslation/src/net/heartsome/cat/ts/fuzzytranslation/resource/Messages.java | package net.heartsome.cat.ts.fuzzytranslation.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author robert 2012-08-29
* @version
* @since JDK1.6
*/
public class Messages {
private static final String BUNDLE_NAME = "net.heartsome.cat.ts.fuzzytranslation.resource.fuzzyTrans";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 590 | 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.p2update/src/net/heartsome/cat/p2update/Activator.java | package net.heartsome.cat.p2update;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
import org.eclipse.equinox.p2.ui.Policy;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
public static final Logger logger = LoggerFactory.getLogger(Activator.class);
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.ts.ui.p2update"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
public static BundleContext bundleContext;
@SuppressWarnings("rawtypes")
ServiceRegistration policyRegistration;
UpdatePolicy policy;
/**
* 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;
bundleContext = context;
// register the p2 UI policy
registerP2Policy(context);
loadUpdateSite();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
bundleContext = null;
// unregister the UI policy
policyRegistration.unregister();
policyRegistration = null;
super.stop(context);
}
/**
* Returns the shared instance
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
private void registerP2Policy(BundleContext context) {
policy = new UpdatePolicy();
policy.updateForPreferences();
policyRegistration = context.registerService(Policy.class.getName(), policy, null);
}
private void loadUpdateSite() throws InvocationTargetException {
// get the agent
final IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(Activator.bundleContext,
IProvisioningAgent.SERVICE_NAME);
// get the repository managers and define our repositories
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent
.getService(IMetadataRepositoryManager.SERVICE_NAME);
if (manager == null) {
logger.error("When load repository,Metadata manager was null");
return;
}
// Load artifact manager
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent
.getService(IArtifactRepositoryManager.SERVICE_NAME);
if (artifactManager == null) {
logger.error("When load repository,Artifact manager was null");
return;
}
// Load repository
try {
String url = getUrlString();
if (url == null) {
return;
}
URI repoLocation = new URI(url);
URI[] ex = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_ALL);
for(URI e : ex){
manager.removeRepository(e);
artifactManager.removeRepository(e);
}
manager.addRepository(repoLocation);
artifactManager.addRepository(repoLocation);
} catch (URISyntaxException e) {
logger.error("Caught URI syntax exception " + e.getMessage(), e);
throw new InvocationTargetException(e);
}
}
private String getUrlString() {
String version = System.getProperty("TSEdition");
SAXReader saxReader = new SAXReader();
Document document = null;
try {
String siteFile = getUpdateSiteFile();
if (siteFile == null) {
logger.error("Can not get the update site config file");
return null;
}
document = saxReader.read(new File(siteFile));
Element root = document.getRootElement();
Iterator<?> it = root.elementIterator("site");
String name;
while (it.hasNext()) {
Element e = (Element) it.next();
name = e.attributeValue("name");
if (name.equals(version))
return e.attributeValue("url");
}
} catch (Exception e) {
logger.error("", e);
}
return null;
}
private String getUpdateSiteFile() {
try {
String bundlePath = FileLocator.toFileURL(Activator.getDefault().getBundle().getEntry("")).getPath();
return bundlePath + "/configuration/p2config.xml";
} catch (IOException e) {
logger.error("", e);
}
return null;
}
}
| 4,827 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UpdatePolicy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/UpdatePolicy.java | package net.heartsome.cat.p2update;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.p2.engine.EngineActivator;
import org.eclipse.equinox.p2.operations.ProfileChangeOperation;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.Policy;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* 更新策略配置类
* @author Jason
* @version
* @since JDK1.6
*/
public class UpdatePolicy extends Policy {
@Override
public boolean continueWorkingWithOperation(ProfileChangeOperation operation, Shell shell) {
Assert.isTrue(operation.getResolutionResult() != null);
IStatus status = operation.getResolutionResult();
// user cancelled
if (status.getSeverity() == IStatus.CANCEL)
return false;
// Special case those statuses where we would never want to open a wizard
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
MessageDialog.openInformation(shell, P2UpdateUtil.CHECK_UPDATE_JOB_NAME, P2UpdateUtil.UPDATE_PROMPT_INFO_NO_UPDATE);
return false;
}
// there is no plan, so we can't continue. Report any reason found
if (operation.getProvisioningPlan() == null && !status.isOK()) {
StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
return false;
}
// Allow the wizard to open otherwise.
return true;
}
public void updateForPreferences() {
setRestartPolicy(RESTART_POLICY_PROMPT);
setRepositoriesVisible(false);
System.setProperty(EngineActivator.PROP_UNSIGNED_POLICY, EngineActivator.UNSIGNED_ALLOW);
}
}
| 1,765 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CheckUpdateHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/handler/CheckUpdateHandler.java | package net.heartsome.cat.p2update.handler;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.p2update.ui.UpdateWizard;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.equinox.p2.operations.RepositoryTracker;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob;
/**
* 更新检查Handler
*
* @author Jason
* @version
* @since JDK1.6
*/
public class CheckUpdateHandler extends PreloadingRepositoryHandler {
boolean hasNoRepos = false;
UpdateOperation operation;
@Override
protected String getProgressTaskName() {
return P2UpdateUtil.CHECK_UPDATE_JOB_NAME;
}
@Override
protected void doExecute(LoadMetadataRepositoryJob job) {
// TODO Auto-generated method stub
if (hasNoRepos) {
P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_CHECK);
return;
}
if (getProvisioningUI().getPolicy().continueWorkingWithOperation(operation, getShell())) {
UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), operation, operation.getSelectedUpdates());
TSWizardDialog dialog = new TSWizardDialog(getShell(), wizard);
dialog.create();
dialog.open();
}
}
@Override
protected void doPostLoadBackgroundWork(IProgressMonitor monitor) throws OperationCanceledException {
operation = getProvisioningUI().getUpdateOperation(null, null);
// check for updates
IStatus resolveStatus = operation.resolveModal(monitor);
if (resolveStatus.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
}
@Override
protected boolean preloadRepositories() {
hasNoRepos = false;
RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker();
if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) {
hasNoRepos = true;
return false;
}
return super.preloadRepositories();
}
}
| 2,079 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreloadingRepositoryHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/handler/PreloadingRepositoryHandler.java | /*******************************************************************************
* Copyright (c) 2008, 2010 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.p2update.handler;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
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.SubMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob;
import org.eclipse.equinox.p2.ui.ProvisioningUI;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.slf4j.LoggerFactory;
/**
* PreloadingRepositoryHandler provides background loading of repositories before executing the provisioning handler.
* @since 3.5
*/
public abstract class PreloadingRepositoryHandler extends AbstractHandler {
/**
* The constructor.
*/
public PreloadingRepositoryHandler() {
// constructor
}
/**
* Execute the command.
*/
public Object execute(ExecutionEvent event) {
// Look for a profile. We may not immediately need it in the
// handler, but if we don't have one, whatever we are trying to do
// will ultimately fail in a more subtle/low-level way. So determine
// up front if the system is configured properly.
String profileId = getProvisioningUI().getProfileId();
IProvisioningAgent agent = getProvisioningUI().getSession().getProvisioningAgent();
IProfile profile = null;
if (agent != null) {
IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
if (registry != null) {
profile = registry.getProfile(profileId);
}
}
if (profile == null) {
// Inform the user nicely
P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_CHECK);
return null;
} else {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
doExecuteAndLoad();
}
});
}
return null;
}
void doExecuteAndLoad() {
if (preloadRepositories()) {
// cancel any load that is already running
final IStatus[] checkStatus = new IStatus[1];
Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
public IStatus runModal(IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
IStatus status = super.runModal(sub.newChild(500));
if (status.getSeverity() == IStatus.CANCEL)
return status;
if (status.getSeverity() != IStatus.OK) {
// 记录检查错误
checkStatus[0] = status;
return Status.OK_STATUS;
}
try {
doPostLoadBackgroundWork(sub.newChild(500));
} catch (OperationCanceledException e) {
return Status.CANCEL_STATUS;
}
return status;
}
};
setLoadJobProperties(loadJob);
loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
if (waitForPreload()) {
loadJob.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
if (PlatformUI.isWorkbenchRunning())
if (event.getResult().isOK()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (checkStatus[0] != null) {
// 提示连接异常
P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
P2UpdateUtil.INFO_TYPE_CHECK);
return;
}
doExecute(loadJob);
}
});
}
}
});
loadJob.setUser(true);
loadJob.schedule();
} else {
loadJob.setSystem(true);
loadJob.setUser(false);
loadJob.schedule();
doExecute(null);
}
} else {
doExecute(null);
}
}
protected abstract String getProgressTaskName();
protected abstract void doExecute(LoadMetadataRepositoryJob job);
protected boolean preloadRepositories() {
return true;
}
protected void doPostLoadBackgroundWork(IProgressMonitor monitor) throws OperationCanceledException {
// default is to do nothing more.
}
protected boolean waitForPreload() {
return true;
}
protected void setLoadJobProperties(Job loadJob) {
loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true));
}
protected ProvisioningUI getProvisioningUI() {
return ProvisioningUI.getDefaultUI();
}
/**
* Return a shell appropriate for parenting dialogs of this handler.
* @return a Shell
*/
protected Shell getShell() {
return PlatformUI.getWorkbench().getModalDialogShellProvider().getShell();
}
}
| 5,535 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AutomaticUpdate.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/autoupdate/AutomaticUpdate.java | /**
* AutomaticUpdate.java
*
* Version information :
*
* Date:2012-9-4
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.p2update.autoupdate;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.p2update.ui.UpdateWizard;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
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.SubMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.operations.RepositoryTracker;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob;
import org.eclipse.equinox.p2.ui.ProvisioningUI;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 自动更新
* @author Jason
* @version
* @since JDK1.6
*/
public class AutomaticUpdate {
UpdateOperation operation;
public static final Logger logger = LoggerFactory.getLogger(P2UpdateUtil.class);
public void checkForUpdates() throws OperationCanceledException {
// 检查 propfile
String profileId = getProvisioningUI().getProfileId();
IProvisioningAgent agent = getProvisioningUI().getSession().getProvisioningAgent();
IProfile profile = null;
if (agent != null) {
IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
if (registry != null) {
profile = registry.getProfile(profileId);
}
}
if (profile == null) {
// Inform the user nicely
P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
return;
}
// 开始检查前先确定是否有repository
RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker();
if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) {
P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
return;
}
final IStatus[] checkStatus = new IStatus[1];
Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
public IStatus runModal(IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, P2UpdateUtil.CHECK_UPDATE_TASK_NAME, 1000);
// load repository
IStatus status = super.runModal(sub.newChild(500));
if (status.getSeverity() == IStatus.CANCEL) {
return status;
}
if (status.getSeverity() != Status.OK) {
// load repository error
checkStatus[0] = status;
}
operation = getProvisioningUI().getUpdateOperation(null, null);
// check for updates
IStatus resolveStatus = operation.resolveModal(sub.newChild(500));
if (resolveStatus.getSeverity() == IStatus.CANCEL) {
return Status.CANCEL_STATUS;
}
return Status.OK_STATUS;
}
};
loadJob.setName(P2UpdateUtil.ATUO_CHECK_UPDATE_JOB_NAME);
loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true));
loadJob.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
if (PlatformUI.isWorkbenchRunning())
if (event.getResult().isOK()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (checkStatus[0] != null) {
// 提示连接异常
P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
return;
}
doUpdate();
}
});
}
}
});
loadJob.setUser(true);
loadJob.schedule();
}
private void doUpdate() {
if (operation == null) {
return;
}
IStatus status = operation.getResolutionResult();
// user cancelled
if (status.getSeverity() == IStatus.CANCEL)
return;
// Special case those statuses where we would never want to open a wizard
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
return;
}
if (getProvisioningUI().getPolicy().continueWorkingWithOperation(operation, getShell())) {
UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), operation, operation.getSelectedUpdates());
TSWizardDialog dialog = new TSWizardDialog(getShell(), wizard);
dialog.create();
dialog.open();
}
}
protected ProvisioningUI getProvisioningUI() {
return ProvisioningUI.getDefaultUI();
}
protected Shell getShell() {
return PlatformUI.getWorkbench().getModalDialogShellProvider().getShell();
}
}
| 5,438 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UpdateWizardPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/ui/UpdateWizardPage.java | package net.heartsome.cat.p2update.ui;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.equinox.internal.p2.ui.ProvUIActivator;
import org.eclipse.equinox.internal.p2.ui.ProvUIMessages;
import org.eclipse.equinox.internal.p2.ui.dialogs.ILayoutConstants;
import org.eclipse.equinox.internal.p2.ui.dialogs.IUDetailsGroup;
import org.eclipse.equinox.internal.p2.ui.dialogs.ResolutionStatusPage;
import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot;
import org.eclipse.equinox.internal.p2.ui.model.QueriedElement;
import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig;
import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider;
import org.eclipse.equinox.internal.p2.ui.viewers.ProvElementContentProvider;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.operations.ProfileChangeOperation;
import org.eclipse.equinox.p2.operations.ProfileModificationJob;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.ProvisioningUI;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
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.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* 更新向导页,用于显示需要更新的程序内容
* @author Jason
* @version
* @since JDK1.6
*/
public class UpdateWizardPage extends ResolutionStatusPage {
ProvisioningUI ui;
UpdateOperation operation;
IUElementListRoot input;
TreeViewer treeViewer;
ProvElementContentProvider contentProvider;
IUDetailsLabelProvider labelProvider;
protected UpdateWizardPage(UpdateOperation operation,IUElementListRoot root, ProvisioningUI ui) {
super("MyUpdasteWizardPage1", ui, null);
this.ui = ui;
this.operation = operation;
this.input = root;
setTitle(P2UpdateUtil.UI_WIZARD_PAGE_TITLE);
setDescription(P2UpdateUtil.UI_WIZARD_PAGE_DESC);
}
public void createControl(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
composite.setLayout(gridLayout);
treeViewer = new TreeViewer(composite, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
GridData data = new GridData(GridData.FILL_BOTH);
Tree tree = treeViewer.getTree();
tree.setLayoutData(data);
tree.setHeaderVisible(true);
IUColumnConfig[] columns = getColumnConfig();
for (int i = 0; i < columns.length; i++) {
TreeColumn tc = new TreeColumn(tree, SWT.LEFT, i);
tc.setResizable(true);
tc.setText(columns[i].getColumnTitle());
tc.setWidth(columns[i].getWidthInPixels(tree));
}
contentProvider = new ProvElementContentProvider();
treeViewer.setContentProvider(contentProvider);
labelProvider = new IUDetailsLabelProvider(null, getColumnConfig(), getShell());
treeViewer.setLabelProvider(labelProvider);
setControl(composite);
final Runnable runnable = new Runnable() {
public void run() {
// updateStatus(input, operation);
setDrilldownElements(input, operation);
treeViewer.setInput(input);
}
};
if (operation != null && !operation.hasResolved()) {
try {
getContainer().run(true, false, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
operation.resolveModal(monitor);
parent.getDisplay().asyncExec(runnable);
}
});
} catch (Exception e) {
StatusManager.getManager().handle(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, e.getMessage(), e));
}
} else {
runnable.run();
}
}
public boolean performFinish() {
if (operation.getResolutionResult().getSeverity() != IStatus.ERROR) {
ProfileModificationJob job = (ProfileModificationJob) operation.getProvisioningJob(null);
job.setName(P2UpdateUtil.EXECUTE_UPDATE_JOB_NAME);
job.setTaskName(P2UpdateUtil.EXECUTE_UPDATE_Task_NAME);
getProvisioningUI().schedule(job, StatusManager.SHOW | StatusManager.LOG);
return true;
}
return false;
}
void setDrilldownElements(IUElementListRoot root, ProfileChangeOperation operation) {
if (operation == null || operation.getProvisioningPlan() == null)
return;
Object[] elements = root.getChildren(root);
for (int i = 0; i < elements.length; i++) {
if (elements[i] instanceof QueriedElement) {
((QueriedElement) elements[i]).setQueryable(operation.getProvisioningPlan().getAdditions());
}
}
}
@Override
protected void updateCaches(IUElementListRoot newRoot,
ProfileChangeOperation op) {
operation = (UpdateOperation) op;
if (newRoot != null) {
setDrilldownElements(newRoot, operation);
if (treeViewer != null) {
if (input != newRoot)
treeViewer.setInput(newRoot);
else
treeViewer.refresh();
}
input = newRoot;
}
}
@Override
protected boolean isCreated() {
return false;
}
@Override
protected IUDetailsGroup getDetailsGroup() {
return null;
}
@Override
protected IInstallableUnit getSelectedIU() {
return null;
}
@Override
protected Object[] getSelectedElements() {
return null;
}
@Override
protected String getDialogSettingsName() {
return null;
}
@Override
protected SashForm getSashForm() {
return null;
}
@Override
protected int getColumnWidth(int index) {
return 0;
}
@Override
protected String getClipboardText(Control control) {
return null;
}
}
| 5,831 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UpdateDescriptionPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/ui/UpdateDescriptionPage.java | package net.heartsome.cat.p2update.ui;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.equinox.internal.p2.ui.ProvUI;
import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement;
import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement;
import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.operations.Update;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.ProvisioningUI;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
/**
* 更新向导页,用于显示当前更新的文字描述内容
* @author Jason
* @version
* @since JDK1.6
*/
public class UpdateDescriptionPage extends WizardPage {
IUElementListRoot root;
ProvisioningUI ui;
UpdateOperation operation;
/**
* root 参数未使用
* @param operation
* @param root
* @param ui
*/
protected UpdateDescriptionPage(UpdateOperation operation, IUElementListRoot root, ProvisioningUI ui) {
super("MyUpdsateDescriptionPage");
setTitle(P2UpdateUtil.UI_WIZARD_DESC_PAGE_TITLE);
setDescription(P2UpdateUtil.UI_WIZARD_DESC_PAGE_DESC);
this.ui = ui;
this.root = root;
this.operation = operation;
}
public void createControl(Composite parent) {
Text text = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
Color color = text.getBackground();
text.setEditable(false);
text.setBackground(color);
text.setText(getUpdateDescDetailText());
setControl(text);
}
private String getUpdateDescDetailText() {
StringBuffer descBf = new StringBuffer();
Update[] updates = operation.getSelectedUpdates();
if (updates.length == 0) {
// no udpates;
setPageComplete(false);
return P2UpdateUtil.UPDATE_PROMPT_INFO_NO_UPDATE;
}
Update update = updates[0];
AvailableUpdateElement newElement = new AvailableUpdateElement(null, update.replacement, update.toUpdate,
ui.getProfileId(), ProvUI.getQueryContext(ui.getPolicy()).getShowProvisioningPlanChildren());
descBf.append(P2UpdateUtil.UI_WIZARD_DESC_PAGE_DESC_DETAIL).append(newElement.getIU().getVersion())
.append("\n\n");
newElement.setQueryable(operation.getProvisioningPlan().getAdditions());
Object[] children = newElement.getChildren(newElement);
StringBuffer temp = new StringBuffer();
if (children != null && children.length != 0) {
AvailableIUElement c = (AvailableIUElement) children[0];
String detail = c.getIU().getProperty(IInstallableUnit.PROP_DESCRIPTION, null);
if (detail == null)
detail = "";
temp.append(detail);
}
String descResult = "";
if(temp.length() != 0){
String lang = CommonFunction.getSystemLanguage();
String szh = "[-zh-]";
String sen = "[-en-]";
if(lang.equals("en")){
descResult = temp.substring(sen.length() + 1, temp.indexOf(szh) - 1);
}else if(lang.equals("zh")){
descResult = temp.substring(temp.indexOf(szh) + szh.length() + 1, temp.length());
}
}
return descBf.append(descResult).toString();
// String detail = "";
// Object[] elements = root.getChildren(root);
// if(elements.length > 0){
// AvailableUpdateElement element = (AvailableUpdateElement) elements[0];
// Object[] children = element.getChildren(element);
// if(children != null && children.length != 0){
// AvailableIUElement c = (AvailableIUElement) children[0];
// IInstallableUnit selectedIU = ElementUtils.elementToIU(c);
// detail = selectedIU.getProperty(IInstallableUnit.PROP_DESCRIPTION, null);
// if (detail == null)
// detail = "";
// }
// }
}
}
| 3,802 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UpdateWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/ui/UpdateWizard.java | package net.heartsome.cat.p2update.ui;
import java.util.ArrayList;
import net.heartsome.cat.p2update.util.P2UpdateUtil;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.p2.ui.ProvUI;
import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement;
import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot;
import org.eclipse.equinox.p2.operations.ProfileModificationJob;
import org.eclipse.equinox.p2.operations.Update;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.ui.Policy;
import org.eclipse.equinox.p2.ui.ProvisioningUI;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* 更新向导
* @author Jason
* @version
* @since JDK1.6
*/
public class UpdateWizard extends Wizard {
Update[] initialSelections;
UpdateOperation operation;
ProvisioningUI ui;
// UpdateWizardPage fristPage;
protected IUElementListRoot root;
public UpdateWizard(ProvisioningUI ui, UpdateOperation operation, Object[] initialSelections) {
Assert.isLegal(operation.hasResolved(), "Cannot create an update wizard on an unresolved operation"); //$NON-NLS-1$
setWindowTitle(P2UpdateUtil.UI_WIZARD_DIALOG_TITLE);
// setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_UPDATE));
this.operation = operation;
// this.initialSelections = (Update[]) initialSelections;
this.ui = ui;
// initializeResolutionModelElements(initialSelections);
setNeedsProgressMonitor(true);
}
@Override
public void addPages() {
// fristPage = new UpdateWizardPage(operation, root, ui);
// addPage(fristPage);
UpdateDescriptionPage descPage = new UpdateDescriptionPage(operation, root, ui);
addPage(descPage);
}
@Override
public boolean performFinish() {
if (operation.getResolutionResult().getSeverity() != IStatus.ERROR) {
ProfileModificationJob job = (ProfileModificationJob) operation.getProvisioningJob(null);
job.setName(P2UpdateUtil.EXECUTE_UPDATE_JOB_NAME);
job.setTaskName(P2UpdateUtil.EXECUTE_UPDATE_Task_NAME);
ui.schedule(job, StatusManager.SHOW | StatusManager.LOG);
return true;
}
return false;
}
protected void initializeResolutionModelElements(Object[] selectedElements) {
root = new IUElementListRoot();
ArrayList<AvailableUpdateElement> list = new ArrayList<AvailableUpdateElement>(selectedElements.length);
for (int i = 0; i < selectedElements.length; i++) {
if (selectedElements[i] instanceof AvailableUpdateElement) {
AvailableUpdateElement element = (AvailableUpdateElement) selectedElements[i];
AvailableUpdateElement newElement = new AvailableUpdateElement(root, element.getIU(),
element.getIUToBeUpdated(), getProfileId(), shouldShowProvisioningPlanChildren());
list.add(newElement);
} else if (selectedElements[i] instanceof Update) {
Update update = (Update) selectedElements[i];
AvailableUpdateElement newElement = new AvailableUpdateElement(root, update.replacement,
update.toUpdate, getProfileId(), shouldShowProvisioningPlanChildren());
list.add(newElement);
}
}
root.setChildren(list.toArray());
}
protected boolean shouldShowProvisioningPlanChildren() {
return ProvUI.getQueryContext(getPolicy()).getShowProvisioningPlanChildren();
}
protected Policy getPolicy() {
return ui.getPolicy();
}
protected String getProfileId() {
return ui.getProfileId();
}
}
| 3,485 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
P2UpdateUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.p2update/src/net/heartsome/cat/p2update/util/P2UpdateUtil.java | package net.heartsome.cat.p2update.util;
import net.heartsome.cat.p2update.resource.Messages;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
public class P2UpdateUtil {
public final static int INFO_TYPE_CHECK = 1;
public final static int INFO_TYPE_AUTO_CHECK = 2;
public static void openConnectErrorInfoDialog(Shell shell, int type) {
if (type == INFO_TYPE_AUTO_CHECK) {
MessageDialog.openInformation(shell, AUTO_UPDATE_PROMPT_INFO_TITLE, UPDATE_PROMPT_INFO_CONTENT);
} else if (type == INFO_TYPE_CHECK) {
MessageDialog.openInformation(shell, UPDATE_PROMPT_INFO_TITLE, UPDATE_PROMPT_INFO_CONTENT);
}
}
public final static String ATUO_CHECK_UPDATE_JOB_NAME = Messages.getString("ATUO_CHECK_UPDATE_JOB_NAME");
public final static String CHECK_UPDATE_JOB_NAME = Messages.getString("CHECK_UPDATE_JOB_NAME");;
public final static String CHECK_UPDATE_TASK_NAME = Messages.getString("CHECK_UPDATE_TASK_NAME");
public final static String EXECUTE_UPDATE_JOB_NAME = Messages.getString("EXECUTE_UPDATE_JOB_NAME");
public final static String EXECUTE_UPDATE_Task_NAME = Messages.getString("EXECUTE_UPDATE_Task_NAME");
public final static String AUTO_UPDATE_PROMPT_INFO_TITLE = Messages.getString("AUTO_UPDATE_PROMPT_INFO_TITLE");
public final static String UPDATE_PROMPT_INFO_TITLE = Messages.getString("UPDATE_PROMPT_INFO_TITLE");
public final static String UPDATE_PROMPT_INFO_CONTENT = Messages.getString("UPDATE_PROMPT_INFO_CONTENT");
public final static String UI_WIZARD_DIALOG_TITLE = Messages.getString("UI_WIZARD_DIALOG_TITLE");
public final static String UI_WIZARD_PAGE_TITLE = Messages.getString("UI_WIZARD_PAGE_TITLE");
public final static String UI_WIZARD_PAGE_DESC = Messages.getString("UI_WIZARD_PAGE_DESC");
public final static String UI_WIZARD_DESC_PAGE_TITLE = Messages.getString("UI_WIZARD_DESC_PAGE_TITLE");
public final static String UI_WIZARD_DESC_PAGE_DESC = Messages.getString("UI_WIZARD_DESC_PAGE_DESC");
public final static String UPDATE_PROMPT_INFO_NO_UPDATE = Messages.getString("UPDATE_PROMPT_INFO_NO_UPDATE");
public final static String UI_WIZARD_DESC_PAGE_DESC_DETAIL = Messages.getString("UI_WIZARD_DESC_PAGE_DESC_DETAIL");
}
| 2,236 | 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.p2update/src/net/heartsome/cat/p2update/resource/Messages.java | package net.heartsome.cat.p2update.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author Jason
* @version
* @since JDK1.6
*/
public class Messages {
private static final String BUNDLE_NAME = "net.heartsome.cat.p2update.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 553 | 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.help/src/net/heartsome/cat/ts/ui/help/Activator.java | package net.heartsome.cat.ts.ui.help;
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.help"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* 提供一个图片文件对插件的相对路径,返回该图片的描述信息。
* @param path
* 图片资源对插件的相对路径。
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
| 1,422 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelfHelpDisplay.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.help/src/net/heartsome/cat/ts/ui/help/SelfHelpDisplay.java | package net.heartsome.cat.ts.ui.help;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.help.IContext;
import org.eclipse.help.IHelpResource;
import org.eclipse.help.base.AbstractHelpDisplay;
import org.eclipse.help.internal.base.BaseHelpSystem;
import org.eclipse.help.internal.base.HelpBasePlugin;
import org.eclipse.help.internal.base.HelpBaseResources;
import org.eclipse.help.internal.server.WebappManager;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.program.Program;
@SuppressWarnings("restriction")
public class SelfHelpDisplay {
private String hrefOpenedFromHelpDisplay;
private static AbstractHelpDisplay helpDisplay;
private static final String HELP_DISPLAY_EXTENSION_ID = "org.eclipse.help.base.display"; //$NON-NLS-1$
private static final String HELP_DISPLAY_CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
private static class DefaultDisplay extends AbstractHelpDisplay {
public String getHelpHome(String hostname, int port, String tab) {
String helpURL = getFramesetURL();
if (tab != null) {
helpURL += "?tab=" + tab; //$NON-NLS-1$
}
return helpURL;
}
public String getHelpForTopic(String topic, String hostname, int port) {
return getFramesetIndexURL() + "?topic=" + topic; //$NON-NLS-1$
}
}
/**
* Constructor.
*/
public SelfHelpDisplay() {
super();
}
/**
* Displays help.
*/
public void displayHelp(boolean forceExternal) {
displayHelpURL(null, forceExternal);
}
/**
* Displays a help resource specified as a url.
* <ul>
* <li>a URL in a format that can be returned by
* {@link org.eclipse.help.IHelpResource#getHref() IHelpResource.getHref()}
* <li>a URL query in the format format
* <em>key=value&key=value ...</em> The valid keys are: "tab", "toc",
* "topic", "contextId". For example,
* <em>toc="/myplugin/mytoc.xml"&topic="/myplugin/references/myclass.html"</em>
* is valid.
* </ul>
*/
public void displayHelpResource(String href, boolean forceExternal) {
setHrefOpenedFromHelpDisplay(href);
if (href.startsWith("/file")) { //$NON-NLS-1$
displayHelpResource(href.substring(1), forceExternal);
return;
}
if (href != null && (href.startsWith("tab=") //$NON-NLS-1$
|| href.startsWith("toc=") //$NON-NLS-1$
|| href.startsWith("topic=") //$NON-NLS-1$
|| href.startsWith("contextId="))) { //$NON-NLS-1$ // assume it is a query string
displayHelpURL(href, forceExternal);
} else { // assume this is a topic
if (getNoframesURL(href) == null) {
try {
displayHelpURL(
"topic=" + URLEncoder.encode(href, "UTF-8"), forceExternal); //$NON-NLS-1$ //$NON-NLS-2$
} catch (UnsupportedEncodingException uee) {
}
} else if (href.startsWith("jar:") || href.startsWith("platform:")) { //$NON-NLS-1$ //$NON-NLS-2$
// topic from a jar/workspace to display without frames
displayHelpURL(
getBaseURL() + "nftopic/" + getNoframesURL(href), true); //$NON-NLS-1$
} else {
displayHelpURL(getNoframesURL(href), true);
}
}
}
/**
* Display help for the a given topic and related topics.
*
* @param context
* context for which related topics will be displayed
* @param topic
* related topic to be selected
*/
public void displayHelp(IContext context, IHelpResource topic,
boolean forceExternal) {
if (context == null || topic == null || topic.getHref() == null)
return;
String topicURL = getTopicURL(topic.getHref());
displayHelpResource(topicURL, false);
/*
* links tab removed 11/2007, Bug 120947
if (getNoframesURL(topicURL) == null) {
try {
String url = "tab=links" //$NON-NLS-1$
+ "&contextId=" //$NON-NLS-1$
+ URLEncoder.encode(getContextID(context), "UTF-8") //$NON-NLS-1$
+ "&topic=" //$NON-NLS-1$
+ URLEncoder.encode(topicURL, "UTF-8"); //$NON-NLS-1$
displayHelpURL(url, forceExternal);
} catch (UnsupportedEncodingException uee) {
}
} else if (topicURL.startsWith("jar:file:")) { //$NON-NLS-1$
// topic from a jar to display without frames
displayHelpURL(
getBaseURL() + "nftopic/" + getNoframesURL(topicURL), true); //$NON-NLS-1$
} else {
displayHelpURL(getNoframesURL(topicURL), true);
}
*/
}
/**
* Display help to search view for given query and selected topic.
*
* @param searchQuery
* search query in URL format key=value&key=value
* @param topic
* selected from the search results
*/
public void displaySearch(String searchQuery, String topic,
boolean forceExternal) {
if (searchQuery == null || topic == null)
return;
if (getNoframesURL(topic) == null) {
try {
String url = "tab=search&" //$NON-NLS-1$
+ searchQuery + "&topic=" //$NON-NLS-1$
+ URLEncoder.encode(getTopicURL(topic), "UTF-8"); //$NON-NLS-1$
displayHelpURL(url, forceExternal);
} catch (UnsupportedEncodingException uee) {
}
} else {
displayHelpURL(getNoframesURL(topic), true);
}
}
/**
* Displays the specified url. The url can contain query parameters to
* identify how help displays the document
*/
private void displayHelpURL(String helpURL, boolean forceExternal) {
if (!BaseHelpSystem.ensureWebappRunning()) {
return;
}
if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_STANDALONE) {
// wait for Display to be created
SelfDisplayUtils.waitForDisplay();
}
try {
if (helpURL == null || helpURL.length() == 0) {
helpURL = getHelpDisplay().getHelpHome( WebappManager.getHost(), WebappManager.getPort(), null);
} else if (helpURL.startsWith("tab=")) { //$NON-NLS-1$
String tab = helpURL.substring("tab=".length()); //$NON-NLS-1$
helpURL = getHelpDisplay().getHelpHome( WebappManager.getHost(), WebappManager.getPort(), tab);
} else if (helpURL.startsWith("topic=")) { //$NON-NLS-1$
String topic = helpURL.substring("topic=".length()); //$NON-NLS-1$
helpURL = getHelpDisplay().getHelpForTopic( topic, WebappManager.getHost(), WebappManager.getPort());
}
String systemname = System.getProperty("os.name").toUpperCase();
if (systemname.contains("LINUX") || systemname.contains("MAC OS X")) {
Program.launch(helpURL);
}else if (systemname.contains("WINDOW")) {
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(helpURL);
}
} catch (Exception e) {
HelpBasePlugin
.logError(
"An exception occurred while launching help. Check the log at " + Platform.getLogFileLocation().toOSString(), e); //$NON-NLS-1$
BaseHelpSystem.getDefaultErrorUtil()
.displayError(
NLS.bind(HelpBaseResources.HelpDisplay_exceptionMessage, Platform.getLogFileLocation().toOSString()));
}
}
/*
private String getContextID(IContext context) {
if (context instanceof Context) {
return ((Context)context).getId();
}
return HelpPlugin.getContextManager().addContext(context);
}
*/
private static String getBaseURL() {
return "http://" //$NON-NLS-1$
+ WebappManager.getHost() + ":" //$NON-NLS-1$
+ WebappManager.getPort() + "/help/"; //$NON-NLS-1$
}
private static String getFramesetURL() {
String tocPath = MessageFormat.format("topic/net.heartsome.cat.ts.ui.help/html/{0}/index.html", CommonFunction.getSystemLanguage());
return getBaseURL() + tocPath; //$NON-NLS-1$
}
private static String getFramesetIndexURL(){
return getBaseURL() + "index.jsp"; //$NON-NLS-1$
}
private String getTopicURL(String topic) {
if (topic == null)
return null;
if (topic.startsWith("../")) //$NON-NLS-1$
topic = topic.substring(2);
/*
* if (topic.startsWith("/")) { String base = "http://" +
* AppServer.getHost() + ":" + AppServer.getPort(); base +=
* "/help/content/help:"; topic = base + topic; }
*/
return topic;
}
/**
* If href contains URL parameter noframes=true return href with that
* paramter removed, otherwise returns null
*
* @param href
* @return String or null
*/
private String getNoframesURL(String href) {
if (href == null) {
return null;
}
int ix = href.indexOf("?noframes=true&"); //$NON-NLS-1$
if (ix >= 0) {
//remove noframes=true&
return href.substring(0, ix + 1)
+ href.substring(ix + "?noframes=true&".length()); //$NON-NLS-1$
}
ix = href.indexOf("noframes=true"); //$NON-NLS-1$
if (ix > 0) {
//remove &noframes=true
return href.substring(0, ix - 1)
+ href.substring(ix + "noframes=true".length()); //$NON-NLS-1$
}
// can be displayed in frames
return null;
}
public String getHrefOpenedFromHelpDisplay() {
return hrefOpenedFromHelpDisplay;
}
public void setHrefOpenedFromHelpDisplay(String hrefOpenedFromHelpDisplay) {
this.hrefOpenedFromHelpDisplay = hrefOpenedFromHelpDisplay;
}
private static void createHelpDisplay() {
IExtensionPoint point = Platform.getExtensionRegistry()
.getExtensionPoint(HELP_DISPLAY_EXTENSION_ID );
if (point != null) {
IExtension[] extensions = point.getExtensions();
if (extensions.length != 0) {
// We need to pick up the non-default configuration
IConfigurationElement[] elements = extensions[0]
.getConfigurationElements();
if (elements.length == 0)
return;
IConfigurationElement displayElement = elements[0];
// Instantiate the help display
try {
helpDisplay = (AbstractHelpDisplay) (displayElement
.createExecutableExtension(HELP_DISPLAY_CLASS_ATTRIBUTE));
} catch (CoreException e) {
HelpBasePlugin.logStatus(e.getStatus());
}
}
}
}
private static AbstractHelpDisplay getHelpDisplay() {
if (helpDisplay == null) {
createHelpDisplay();
}
if (helpDisplay == null) {
helpDisplay = new DefaultDisplay();
}
return helpDisplay;
}
}
| 10,087 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractSelfHelpUI.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.help/src/net/heartsome/cat/ts/ui/help/AbstractSelfHelpUI.java | package net.heartsome.cat.ts.ui.help;
import java.net.URL;
import org.eclipse.core.runtime.Platform;
import org.eclipse.help.IContext;
import org.eclipse.help.browser.IBrowser;
import org.eclipse.help.internal.base.BaseHelpSystem;
import org.eclipse.help.ui.internal.util.ErrorUtil;
import org.eclipse.osgi.service.environment.Constants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.help.AbstractHelpUI;
public class AbstractSelfHelpUI extends AbstractHelpUI {
private static AbstractSelfHelpUI instance;
class ExternalWorkbenchBrowser implements IBrowser {
public ExternalWorkbenchBrowser() {
}
private IWebBrowser getExternalBrowser() throws PartInitException {
IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
return support.getExternalBrowser();
}
public void close() {
}
public boolean isCloseSupported() {
return false;
}
public void displayURL(String url) throws Exception {
try {
IWebBrowser browser = getExternalBrowser();
if (browser != null) {
browser.openURL(new URL(url));
}
} catch (PartInitException pie) {
ErrorUtil.displayErrorDialog(pie.getLocalizedMessage());
}
}
public boolean isSetLocationSupported() {
return false;
}
public boolean isSetSizeSupported() {
return false;
}
public void setLocation(int x, int y) {
}
public void setSize(int width, int height) {
}
}
@SuppressWarnings("restriction")
public AbstractSelfHelpUI(){
super();
BaseHelpSystem.getInstance().setBrowserInstance(new ExternalWorkbenchBrowser());
}
public static AbstractSelfHelpUI getInstance() {
return instance;
}
@Override
public void displayHelp() {
SelfBaseHelpSystem.getHelpDisplay().displayHelp(useExternalBrowser(null));
}
@Override
public void displayContext(IContext context, int x, int y) {
}
@Override
public void displayHelpResource(String href) {
SelfBaseHelpSystem.getHelpDisplay().displayHelpResource(href, useExternalBrowser(href));
}
@Override
public boolean isContextHelpDisplayed() {
return false;
}
private boolean useExternalBrowser(String url) {
// On non Windows platforms, use external when modal window is displayed
if (!Constants.OS_WIN32.equalsIgnoreCase(Platform.getOS())) {
Display display = Display.getCurrent();
if (display != null) {
if (insideModalParent(display))
return true;
}
}
// Use external when no help frames are to be displayed, otherwise no
// navigation buttons.
if (url != null) {
if (url.indexOf("?noframes=true") > 0 //$NON-NLS-1$
|| url.indexOf("&noframes=true") > 0) { //$NON-NLS-1$
return true;
}
}
return false;
}
private boolean insideModalParent(Display display) {
return isDisplayModal(display.getActiveShell());
}
public static boolean isDisplayModal(Shell activeShell) {
while (activeShell != null) {
if ((activeShell.getStyle() & (SWT.APPLICATION_MODAL | SWT.PRIMARY_MODAL | SWT.SYSTEM_MODAL)) > 0)
return true;
activeShell = (Shell) activeShell.getParent();
}
return false;
}
}
| 3,343 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelfBaseHelpSystem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.help/src/net/heartsome/cat/ts/ui/help/SelfBaseHelpSystem.java | package net.heartsome.cat.ts.ui.help;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.help.HelpSystem;
import org.eclipse.help.ILiveHelpAction;
import org.eclipse.help.browser.IBrowser;
import org.eclipse.help.internal.HelpPlugin;
import org.eclipse.help.internal.base.BookmarkManager;
import org.eclipse.help.internal.base.HelpBasePlugin;
import org.eclipse.help.internal.base.HelpBaseResources;
import org.eclipse.help.internal.base.HelpProvider;
import org.eclipse.help.internal.base.util.IErrorUtil;
import org.eclipse.help.internal.browser.BrowserManager;
import org.eclipse.help.internal.search.LocalSearchManager;
import org.eclipse.help.internal.search.SearchManager;
import org.eclipse.help.internal.server.WebappManager;
import org.eclipse.help.internal.workingset.WorkingSetManager;
import org.osgi.framework.Bundle;
/**
* 引自 BaseHelpSystem 类
* @author robert
*/
@SuppressWarnings("restriction")
public class SelfBaseHelpSystem {
private static final SelfBaseHelpSystem instance = new SelfBaseHelpSystem();
public static final String BOOKMARKS = "bookmarks"; //$NON-NLS-1$
public static final String WORKING_SETS = "workingSets"; //$NON-NLS-1$
public static final String WORKING_SET = "workingSet"; //$NON-NLS-1$
public static final int MODE_WORKBENCH = 0;
public static final int MODE_INFOCENTER = 1;
public static final int MODE_STANDALONE = 2;
private int mode = MODE_WORKBENCH;
private SearchManager searchManager;
private WorkingSetManager workingSetManager;
private BookmarkManager bookmarkManager;
private boolean webappStarted = false;
private boolean webappRunning = false;
private IErrorUtil defaultErrorMessenger;
private IBrowser browser;
private IBrowser internalBrowser;
private SelfHelpDisplay helpDisplay = null;
private SelfBaseHelpSystem() {
super();
}
public static SelfBaseHelpSystem getInstance() {
return instance;
}
/*
* Returns the singleton search manager, which is the main interface to the
* help system's search capability.
*/
public static SearchManager getSearchManager() {
if (getInstance().searchManager == null) {
synchronized (SelfBaseHelpSystem.class) {
if (getInstance().searchManager == null) {
getInstance().searchManager = new SearchManager();
}
}
}
return getInstance().searchManager;
}
/*
* Returns the local search manager which deals only with the local content
* and is called by the global search manager.
*/
public static LocalSearchManager getLocalSearchManager() {
return getSearchManager().getLocalSearchManager();
}
public static synchronized WorkingSetManager getWorkingSetManager() {
if (getInstance().workingSetManager == null) {
getInstance().workingSetManager = new WorkingSetManager();
}
return getInstance().workingSetManager;
}
public static synchronized BookmarkManager getBookmarkManager() {
if (getInstance().bookmarkManager == null) {
getInstance().bookmarkManager = new BookmarkManager();
}
return getInstance().bookmarkManager;
}
/*
* Allows Help UI to plug-in a soft adapter that delegates all the work to
* the workbench browser support.
*/
public synchronized void setBrowserInstance(IBrowser browser) {
this.browser = browser;
}
public static synchronized IBrowser getHelpBrowser(boolean forceExternal) {
if (!forceExternal && !BrowserManager.getInstance().isAlwaysUseExternal()) {
if (getInstance().internalBrowser == null) {
getInstance().internalBrowser = BrowserManager.getInstance().createBrowser(false);
}
return getInstance().internalBrowser;
}
if (getInstance().browser == null) {
getInstance().browser = BrowserManager.getInstance().createBrowser(true);
}
return getInstance().browser;
}
public static synchronized SelfHelpDisplay getHelpDisplay() {
if (getInstance().helpDisplay == null)
getInstance().helpDisplay = new SelfHelpDisplay();
return getInstance().helpDisplay;
}
/*
* Shuts down the BaseHelpSystem.
*/
public static void shutdown() throws CoreException {
if (getInstance().bookmarkManager != null) {
getInstance().bookmarkManager.close();
getInstance().bookmarkManager = null;
}
if (getInstance().searchManager != null) {
getInstance().searchManager.close();
getInstance().searchManager = null;
}
if (getInstance().webappStarted) {
// stop the web app
WebappManager.stop("help"); //$NON-NLS-1$
}
}
/**
* Called by Platform after loading the plugin
*/
public static void startup() {
try {
setDefaultErrorUtil(new IErrorUtil() {
public void displayError(String msg) {
System.out.println(msg);
}
public void displayError(String msg, Thread uiThread) {
System.out.println(msg);
}
});
}
catch (Exception e) {
HelpBasePlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, HelpBasePlugin.PLUGIN_ID, 0,
"Error launching help.", e)); //$NON-NLS-1$
}
/*
* Assigns the provider responsible for providing help
* document content.
*/
HelpPlugin.getDefault().setHelpProvider(new HelpProvider());
}
public static boolean ensureWebappRunning() {
if (!getInstance().webappStarted) {
getInstance().webappStarted = true;
try {
// start the help web app
WebappManager.start("help"); //$NON-NLS-1$
} catch (Exception e) {
HelpBasePlugin.logError(HelpBaseResources.HelpWebappNotStarted, e);
return false;
}
getInstance().webappRunning = true;
}
return getInstance().webappRunning;
}
public static URL resolve(String href, boolean documentOnly) {
String url = null;
if (href == null || href.indexOf("://") != -1 //$NON-NLS-1$
|| isFileProtocol(href))
url = href;
else {
SelfBaseHelpSystem.ensureWebappRunning();
String base = getBase(documentOnly);
if (href.startsWith("/")) //$NON-NLS-1$
url = base + href;
else
url = base + "/" + href; //$NON-NLS-1$
}
try {
return new URL(url);
} catch (MalformedURLException e) {
return null;
}
}
public static URL resolve(String href, String servlet) {
String url = null;
if (href == null || href.indexOf("://") != -1 //$NON-NLS-1$
|| isFileProtocol(href)) {
url = href;
}
else {
SelfBaseHelpSystem.ensureWebappRunning();
String base = getBase(servlet);
if (href.startsWith("/")) { //$NON-NLS-1$
url = base + href;
}
else {
url = base + "/" + href; //$NON-NLS-1$
}
}
try {
return new URL(url);
}
catch (MalformedURLException e) {
return null;
}
}
private static boolean isFileProtocol(String href) {
// Test for file: or /file:
int index = href.indexOf("file:"); //$NON-NLS-1$
return ( index == 0 || (index == 1 && href.charAt(0) == '/' ));
}
public static String unresolve(URL url) {
return unresolve(url.toString());
}
public static String unresolve(String href) {
String[] baseVariants = { getBase("/help/topic"), //$NON-NLS-1$
getBase("/help/nftopic"), //$NON-NLS-1$
getBase("/help/ntopic"), //$NON-NLS-1$
getBase("/help/rtopic") }; //$NON-NLS-1$
for (int i = 0; i < baseVariants.length; i++) {
if (href.startsWith(baseVariants[i])) {
return href.substring(baseVariants[i].length());
}
}
return href;
}
private static String getBase(boolean documentOnly) {
String servlet = documentOnly ? "/help/nftopic" : "/help/topic";//$NON-NLS-1$ //$NON-NLS-2$
return getBase(servlet);
}
private static String getBase(String servlet) {
return "http://" //$NON-NLS-1$
+ WebappManager.getHost() + ":" //$NON-NLS-1$
+ WebappManager.getPort() + servlet;
}
/*
* Returns the mode of operation.
*/
public static int getMode() {
return getInstance().mode;
}
/*
* Sets the mode of operation.
*/
public static void setMode(int mode) {
getInstance().mode = mode;
HelpSystem.setShared(mode == MODE_INFOCENTER);
}
/*
* Sets the error messenger
*/
public static void setDefaultErrorUtil(IErrorUtil em) {
getInstance().defaultErrorMessenger = em;
}
/*
* Returns the default error messenger. When no UI is present, all errors
* are sent to System.out.
*/
public static IErrorUtil getDefaultErrorUtil() {
return getInstance().defaultErrorMessenger;
}
/**
* Obtains name of the Eclipse product
*
* @return String
*/
public static String getProductName() {
IProduct product = Platform.getProduct();
if (product == null) {
return ""; //$NON-NLS-1$
}
String name = product.getName();
return name == null ? "" : name; //$NON-NLS-1$
}
public static void runLiveHelp(String pluginID, String className, String arg) {
Bundle bundle = Platform.getBundle(pluginID);
if (bundle == null) {
return;
}
try {
Class c = bundle.loadClass(className);
Object o = c.newInstance();
//Runnable runnable = null;
if (o != null && o instanceof ILiveHelpAction) {
ILiveHelpAction helpExt = (ILiveHelpAction) o;
if (arg != null)
helpExt.setInitializationString(arg);
Thread runnableLiveHelp = new Thread(helpExt);
runnableLiveHelp.setDaemon(true);
runnableLiveHelp.start();
}
} catch (ThreadDeath td) {
throw td;
} catch (Exception e) {
}
}
/**
* Called when index.jsp is opened, check to see if we index.jsp is running outside out server in which
* case set the mode to infocenter
*/
public static void checkMode() {
if (!getInstance().webappStarted) {
setMode(MODE_INFOCENTER);
}
}
}
| 9,689 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelfDisplayUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.help/src/net/heartsome/cat/ts/ui/help/SelfDisplayUtils.java | package net.heartsome.cat.ts.ui.help;
import java.lang.reflect.Method;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
public class SelfDisplayUtils {
private static final String HELP_UI_PLUGIN_ID = "org.eclipse.help.ui"; //$NON-NLS-1$
private static final String LOOP_CLASS_NAME = "org.eclipse.help.ui.internal.HelpUIEventLoop"; //$NON-NLS-1$
static void runUI() {
invoke("run"); //$NON-NLS-1$
}
static void wakeupUI() {
invoke("wakeup"); //$NON-NLS-1$
}
static void waitForDisplay() {
invoke("waitFor"); //$NON-NLS-1$
}
private static void invoke(String method) {
try {
Bundle bundle = Platform.getBundle(HELP_UI_PLUGIN_ID);
if (bundle == null) {
return;
}
Class c = bundle.loadClass(LOOP_CLASS_NAME);
Method m = c.getMethod(method, new Class[]{});
m.invoke(null, new Object[]{});
} catch (Exception e) {
}
}
}
| 891 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelfHelpSystem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.help/src/net/heartsome/cat/ts/ui/help/SelfHelpSystem.java | package net.heartsome.cat.ts.ui.help;
import java.io.InputStream;
import org.eclipse.core.runtime.Platform;
import org.eclipse.help.IContext;
import org.eclipse.help.IIndex;
import org.eclipse.help.IToc;
import org.eclipse.help.internal.HelpPlugin;
import org.eclipse.help.internal.HelpPlugin.IHelpProvider;
@SuppressWarnings("restriction")
public class SelfHelpSystem {
private static boolean fShared;
/**
* This class is not intended to be instantiated.
*/
private SelfHelpSystem() {
// do nothing
}
/**
* Computes and returns context information for the given context id
* for the platform's current locale.
*
* @param contextId the context id, e.g. "org.my.plugin.my_id"
* @return the context, or <code>null</code> if none
*/
public static IContext getContext(String contextId) {
return HelpPlugin.getContextManager().getContext(contextId, Platform.getNL());
}
/**
* Computes and returns context information for the given context id
* and locale.
*
* @param contextId the context id, e.g. "org.my.plugin.my_id"
* @param locale the locale being requested, e.g. "en_US"
* @return the context, or <code>null</code> if none
*/
public static IContext getContext(String contextId, String locale) {
return HelpPlugin.getContextManager().getContext(contextId, locale);
}
/**
* Returns the list of all integrated tables of contents available. Each
* entry corresponds of a different help "book".
*
* @return an array of TOC's
*/
public static IToc[] getTocs() {
return HelpPlugin.getTocManager().getTocs(Platform.getNL());
}
/**
* Returns the keyword index available in the help system.
*
* @return the keyword index
* @since 3.2
*/
public static IIndex getIndex() {
return HelpPlugin.getIndexManager().getIndex(Platform.getNL());
}
/**
* Returns an open input stream on the contents of the specified help
* resource in the platform's current locale. The client is responsible for
* closing the stream when finished.
*
* @param href
* the URL (as a string) of the help resource
* <p>
* Valid href are as described in
* {@link org.eclipse.help.IHelpResource#getHref IHelpResource.getHref}
* </p>
* @return an input stream containing the contents of the help resource, or
* <code>null</code> if the help resource could not be found and
* opened
*/
public static InputStream getHelpContent(String href) {
return getHelpContent(href, Platform.getNL());
}
/**
* Returns an open input stream on the contents of the specified help
* resource for the speficied locale. The client is responsible for closing
* the stream when finished.
*
* @param href
* the URL (as a string) of the help resource
* <p>
* Valid href are as described in
* {@link org.eclipse.help.IHelpResource#getHref IHelpResource.getHref}
* </p>
* @param locale the locale code, e.g. en_US
* @return an input stream containing the contents of the help resource, or
* <code>null</code> if the help resource could not be found and
* opened
* @since 3.0
*/
public static InputStream getHelpContent(String href, String locale) {
IHelpProvider provider = HelpPlugin.getDefault().getHelpProvider();
if (provider != null) {
return provider.getHelpContent(href, locale);
}
return null;
}
/**
* Returns whether or not the help system, in its current mode of operation,
* can be shared by multiple (potentially remote) users. This is a hint to
* the help system implementation that it should not perform operations that
* are specific to the help system's local environment.
*
* <p>
* For example, when <code>true</code>, the default dynamic content producer
* implementation will not perform any filtering based on local system
* properties such as operating system or activities.
* </p>
* <p>
* If you are providing your own help implementation that is shared, you
* must notify the platform on startup by calling <code>setShared(true)</code>.
* </p>
*
* @return whether or not the help system can be shared by multiple users
* @since 3.2
*/
public static boolean isShared() {
return fShared;
}
/**
* Sets whether or not the help system, in its current mode of operation,
* can be shared by multiple (potentially remote) users. This is a hint to
* the help system implementation that it should not perform operations that
* are specific to the help system's local environment.
*
* <p>
* By default the help system is flagged as not shared. If you are providing
* your own help implementation that is shared, you must call this on startup
* with the parameter <code>true</code>.
* </p>
*
* @param shared whether or not the help system can be shared by multiple users
*/
public static void setShared(boolean shared) {
fShared = shared;
}
}
| 4,981 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbMatcher.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.tb/src/net/heartsome/cat/ts/tb/match/TbMatcher.java | /**
* TermMatcher.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.tb.match;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.ts.tb.match.extension.ITbMatch;
import net.heartsome.cat.ts.tb.resource.Messages;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SafeRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 术语匹配
* @author jason
* @version
* @since JDK1.6
*/
public class TbMatcher {
private final Logger logger = LoggerFactory.getLogger(TbMatcher.class);
private final String TERMMATCH_EXTENSION_ID = "net.heartsome.cat.ts.tb.match.extension";
private ITbMatch termMatch;
public TbMatcher() {
runExtension();
}
public Vector<Hashtable<String, String>> serachTransUnitTerms(String pureText, String srcLang, String tgtLang, boolean isSort) {
Vector<Hashtable<String, String>> terms = new Vector<Hashtable<String, String>>();
if (termMatch != null && pureText != null) {
termMatch.setTuSrcPureText(pureText);
termMatch.setTuSrcLanguage(srcLang);
termMatch.setTuTgtlanguage(tgtLang);
termMatch.setIsSortResult(isSort);
terms.addAll(termMatch.getTransUnitTerms());
}
return terms;
}
public void setCurrentProject(IProject project) {
if (termMatch != null) {
termMatch.setProject(project);
}
}
/**
* 针对项目检查当前导入器是否可用,主要判断是否存在数据模块和当前项目是否设置了术语库
* @param project
* 当前项目
* @return true可用,false不可用
*/
public boolean checkTbMatcher(IProject project) {
if (termMatch == null) {
return false;
}
return termMatch.checkTbMatcher(project);
}
/**
* 释放术语匹配所需要的所有资源
* ;
*/
public void clearResources() {
if(termMatch != null){
termMatch.clearResources();
}
}
/**
* 加载记忆库匹配实现 ;
*/
private void runExtension() {
IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(
TERMMATCH_EXTENSION_ID);
try {
for (IConfigurationElement e : config) {
final Object o = e.createExecutableExtension("class");
if (o instanceof ITbMatch) {
ISafeRunnable runnable = new ISafeRunnable() {
public void handleException(Throwable exception) {
logger.error(Messages.getString("match.TbMatcher.logger1"), exception);
}
public void run() throws Exception {
termMatch = (ITbMatch) o;
}
};
SafeRunner.run(runnable);
}
}
} catch (CoreException ex) {
logger.error(Messages.getString("match.TbMatcher.logger1"), ex);
}
}
}
| 3,423 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractTbMatch.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.tb/src/net/heartsome/cat/ts/tb/match/extension/AbstractTbMatch.java | /**
* AbstractTermMatch.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.tb.match.extension;
/**
* 术语匹配抽象
* @author jason
* @version
* @since JDK1.6
*/
public abstract class AbstractTbMatch implements ITbMatch {
protected String srcPureText;
protected String srcLanguage;
protected String tgtLanguage;
protected boolean isSort;
public AbstractTbMatch() {
srcPureText = "";
srcLanguage = "";
tgtLanguage = "";
isSort = false;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ITbMatch.term.extensionpoint.ITermMatch#setTuSrcPureText(java.lang.String)
*/
public void setTuSrcPureText(String srcPureText) {
this.srcPureText = srcPureText;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ITbMatch.term.extensionpoint.ITermMatch#setTuSrcLanguage(java.lang.String)
*/
public void setTuSrcLanguage(String lang) {
this.srcLanguage = lang;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ITbMatch.term.extensionpoint.ITermMatch#setTuTgtlanguage(java.lang.String)
*/
public void setTuTgtlanguage(String lang) {
this.tgtLanguage = lang;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tb.match.extension.ITbMatch#setIsSortResult(boolean)
*/
public void setIsSortResult(boolean isSort){
this.isSort = isSort;
}
}
| 1,867 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ITbMatch.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.tb/src/net/heartsome/cat/ts/tb/match/extension/ITbMatch.java | /**
* ITermMatch.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.tb.match.extension;
import java.util.Hashtable;
import java.util.Vector;
import org.eclipse.core.resources.IProject;
/**
* 术语匹配
* @author jason
* @version
* @since JDK1.6
*/
public interface ITbMatch {
/**
* 查找当前翻译单元的术语
* @return ;
*/
Vector<Hashtable<String, String>> getTransUnitTerms();
void clearResources();
/**
* 设置当前项目
* @param project ;
*/
void setProject(IProject project);
/**
* 针对当前项目检查当前匹配器是否可用
* @param project
* 当前项目
* @return ;
*/
boolean checkTbMatcher(IProject project);
/**
* 设置TransUnit的源文纯文本
* @param srcPureText ;
*/
void setTuSrcPureText(String srcPureText);
/**
* 设置TransUnit的源语言编码
* @param lang 语言编码,如:en-Us;
*/
void setTuSrcLanguage(String lang);
/**
* 设置TransUnit的目标语言编码
* @param lang 语言编码,如:en-US;
*/
void setTuTgtlanguage(String lang);
/**
* 是否排序查询是结果
* @param isSort ;
*/
void setIsSortResult(boolean isSort);
}
| 1,757 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbImporter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.tb/src/net/heartsome/cat/ts/tb/importer/TbImporter.java | /**
* TBImporter.java
*
* Version information :
*
* Date:2012-5-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.tb.importer;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.ts.tb.importer.extension.ITbImporter;
import net.heartsome.cat.ts.tb.resource.Messages;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TbImporter {
private static Logger logger = LoggerFactory.getLogger(TbImporter.class);
private final String TERMIMPORT_EXTENSION_ID = "net.heartsome.cat.ts.tb.importer.extension";
private ITbImporter tbImporter;
private static TbImporter instance;
public static TbImporter getInstance(){
if(instance == null){
instance = new TbImporter();
}
return instance;
}
private TbImporter(){
runExtension();
}
public boolean checkImporter(){
if(tbImporter == null){
return false;
}
return tbImporter.checkImporter();
}
/**
* 释放当前导入器的资源
* ;
*/
public void clearResources(){
instance = null;
if(tbImporter != null){
tbImporter.clearResources();
}
}
public void setProject(IProject project){
if(tbImporter != null){
tbImporter.setProject(project);
}
}
public int executeImport(String tbxStr, String srcLang,IProgressMonitor monitor) throws ImportException{
if(tbImporter != null){
return tbImporter.executeImport(tbxStr, srcLang, monitor);
}
return ITbImporter.IMPORT_STATE_FAILED;
}
/**
* 加载记忆库匹配实现 ;
*/
private void runExtension() {
IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(
TERMIMPORT_EXTENSION_ID);
try {
for (IConfigurationElement e : config) {
final Object o = e.createExecutableExtension("class");
if (o instanceof ITbImporter) {
ISafeRunnable runnable = new ISafeRunnable() {
public void handleException(Throwable exception) {
logger.error(Messages.getString("importer.TbImporter.logger1"), exception);
}
public void run() throws Exception {
tbImporter = (ITbImporter) o;
}
};
SafeRunner.run(runnable);
}
}
} catch (CoreException ex) {
logger.error(Messages.getString("importer.TbImporter.logger1"), ex);
}
}
}
| 3,171 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ITbImporter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.tb/src/net/heartsome/cat/ts/tb/importer/extension/ITbImporter.java | /**
* ITbImporter.java
*
* Version information :
*
* Date:2012-5-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.tb.importer.extension;
import net.heartsome.cat.common.core.exception.ImportException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* 将符合TBX标准的字符串导入到术语库中
* @author jason
* @version
* @since JDK1.6
*/
public interface ITbImporter {
/** 导入成功 */
int IMPORT_STATE_SUCCESSED = 0;
/** 导入失败 */
int IMPORT_STATE_FAILED = 1;
/** 当前无可用的库 */
int IMPORT_STATE_NODB = 2;
/**
* 设置当前项目,用于获取项目配置信息
* @param project
* ;
*/
void setProject(IProject project);
/**
* 执行导入
* @param tbxStr
* 符合TBX标准的字符串
* @param srcLang
* TBX源语言
* @return 导入标志(成功,失败...);
*/
int executeImport(String tbxStr, String srcLang,IProgressMonitor monitor) throws ImportException;
/**
* 检查导入器是否可用,主要针对当前系统是否有库相关插件或者是否设置了默认库
* @return ;
*/
boolean checkImporter();
/**
* 释放所使用的资源
* ;
*/
void clearResources();
}
| 1,801 | 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.tb/src/net/heartsome/cat/ts/tb/resource/Messages.java | package net.heartsome.cat.ts.tb.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.tb.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 548 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchWindowAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/ApplicationWorkbenchWindowAdvisor.java | package net.heartsome.cat.ts;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.ui.listener.PartAdapter2;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.p2update.autoupdate.AutomaticUpdate;
import net.heartsome.cat.ts.drop.EditorAreaDropAdapter;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.ui.preferencepage.IPreferenceConstants;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.ToolBarContributionItem;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.internal.WorkbenchPage;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.internal.help.WorkbenchHelpSystem;
import org.eclipse.ui.internal.ide.IDEInternalPreferences;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.wizards.IWizardCategory;
import org.eclipse.ui.wizards.IWizardDescriptor;
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 cheney,weachy
* @version
* @since JDK1.5
*/
@SuppressWarnings("restriction")
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
private static final String AUTO_UPDATE_FLAG = "AUTO_UPDATE_FLAG";
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationWorkbenchWindowAdvisor.class);
/**
* @param configurer
*/
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#createActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
*/
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#preWindowOpen()
*/
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
// show the shortcut bar and progress indicator, which are hidden by default
configurer.setShowCoolBar(true);
// 检查是否显示装态栏 robert 2011-11-04 true为显示,false为隐藏,默认显示.
IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
boolean visibleStatus = prefs.getBoolean(TsPreferencesConstant.TS_statusBar_status);
configurer.setShowStatusLine(visibleStatus);
configurer.setShowProgressIndicator(true);
// 添加“编辑区域”的传递者(org.eclipse.swt.dnd.Transfer)
configurer.addEditorAreaTransfer(LocalSelectionTransfer.getTransfer());
configurer.addEditorAreaTransfer(FileTransfer.getInstance());
// 添加“编辑区域”的释放拖拽监听
configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter(configurer.getWindow()));
// 注释整理
// TODO 根据注册的转换器插件,动态添加 XLIFF Editor 映射的文件后缀名。
// abw,html,htm,inx,properties,js,mif,doc,xls,ppt,docx,xlsx,pptx,ppsx,sxw,sxc,sxi,sxd,odt,ods,odp,odg,txt,ttx,po,pot,rc,resx,rtf,svg,xml
// String[] extensions = FileFormatUtils.getExtensions();
// for (String extension : extensions) {
// PlatformUI
// .getWorkbench()
// .getEditorRegistry()
// .setDefaultEditor(extension,
// "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor");
// }
// begin屏蔽掉向导中的General部分
// AbstractExtensionWizardRegistry wizardRegistry = (AbstractExtensionWizardRegistry) WorkbenchPlugin
// .getDefault().getNewWizardRegistry();
// IWizardCategory[] categories = WorkbenchPlugin.getDefault()
// .getNewWizardRegistry().getRootCategory().getCategories();
// for (IWizardDescriptor wizard : getAllWizards(categories)) {
// WorkbenchWizardElement wizardElement = (WorkbenchWizardElement) wizard;
// if (!allowedWizard(wizardElement.getId())) {
// wizardRegistry.removeExtension(wizardElement
// .getConfigurationElement().getDeclaringExtension(),
// new Object[] { wizardElement });
// }
// }
// end
}
private IWizardDescriptor[] getAllWizards(IWizardCategory... categories) {
List<IWizardDescriptor> results = new ArrayList<IWizardDescriptor>();
for (IWizardCategory wizardCategory : categories) {
results.addAll(Arrays.asList(wizardCategory.getWizards()));
results.addAll(Arrays.asList(getAllWizards(wizardCategory.getCategories())));
}
return results.toArray(new IWizardDescriptor[0]);
}
protected static final List<String> FILE_NEW__ALLOWED_WIZARDS = Collections.unmodifiableList(Arrays
.asList(new String[] {
// "org.eclipse.ui.wizards.new.project",// Basic wizards
// "org.eclipse.ui.wizards.new.folder",// Basic wizards
// "org.eclipse.ui.wizards.new.file" // Basic wizards
"net.heartsome.cat.ts.ui.wizards.new.folder", "net.heartsome.cat.database.ui.tb.wizard.createDb",
"net.heartsome.cat.database.ui.tm.wizad.newTmDb",
"net.heartsome.cat.ts.ui.wizards.NewProjectWizard" }));
protected boolean allowedWizard(String wizardId) {
return FILE_NEW__ALLOWED_WIZARDS.contains(wizardId);
}
@Override
public void postWindowOpen() {
IWorkbenchWindow workbenchWindow = getWindowConfigurer().getWindow();
// workbenchWindow.getShell().setMaximized(true);
restorEditorHistory();
saveEditorHistory();
final ICommandService commandService = (ICommandService) workbenchWindow.getService(ICommandService.class);
// 在程序主体窗口打开之前,更新打开工具栏的菜单,让它初始化菜单图片 --robert 2012-03-19
commandService.refreshElements("net.heartsome.cat.ts.openToolBarCommand", null);
// 添加监听
addViewPartVisibleListener(workbenchWindow);
addWorkplaceListener();
// 自动检查更新
automaticCheckUpdate();
// 设置将文件拖到导航视图时的模式为直接复制
setDragModle();
setListenerToPespective(commandService);
setIdToHelpSystem();
setProgressIndicatorVisible(false);
setInitLinkEnable();
// 处理 hunspell 内置词典内置文件
try {
CommonFunction.unZipHunspellDics();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addWorkplaceListener(){
IWorkspace workspace = ResourcesPlugin.getWorkspace();
workspace.addResourceChangeListener(new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
//刷新项目导航视图
Display.getDefault().syncExec(new Runnable() {
public void run() {
IViewPart findView = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.findView("net.heartsome.cat.common.ui.navigator.view");
if(null == findView){
return ;
}
IAction refreshActionHandler = findView.getViewSite().getActionBars()
.getGlobalActionHandler(ActionFactory.REFRESH.getId());
if(null == refreshActionHandler){
return;
}
refreshActionHandler.run();
}
});
}
});
}
@Override
public boolean preWindowShellClose() {
try {
ResourcesPlugin.getWorkspace().save(true, null);
} catch (CoreException e) {
LOGGER.error("Save workspace error.", e);
}
return super.preWindowShellClose();
}
private void addViewPartVisibleListener(final IWorkbenchWindow window) {
final ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
window.getActivePage().addPartListener(new PartAdapter2() {
private void setStates(String partId) {
if ("net.heartsome.cat.common.ui.navigator.view".equals(partId)) {
commandService.refreshElements("net.heartsome.cat.common.ui.navigator.command.OpenNavigatorView",
null);
} else if ("net.heartsome.cat.ts.ui.views.DocumentPropertiesViewPart".equals(partId)) {
commandService.refreshElements(
"net.heartsome.cat.ts.ui.handlers.OpenDocumentPropertiesViewCommand", null);
} else if ("net.heartsome.cat.ts.ui.translation.view.matchview".equals(partId)) {
commandService.refreshElements("net.heartsome.cat.ts.ui.translation.menu.command.openMatchView",
null);
} else if ("net.heartsome.cat.ts.ui.term.view.termView".equals(partId)) {
commandService.refreshElements("net.heartsome.cat.ts.ui.term.command.openTermView", null);
} else if ("net.heartsome.cat.ts.ui.qa.views.QAResultViewPart".equals(partId)) {
commandService.refreshElements("net.heartsome.cat.ts.ui.qa.handlers.OpenQAResultViewCommand", null);
}else if ("net.heartsome.cat.ts.websearch.ui.view.BrowserViewPart".equals(partId)) {
commandService.refreshElements("net.heartsome.cat.ts.websearch.showOrHideView", null);
}
}
/**
* 视图打开时
* @see org.eclipse.ui.IPartListener2#partOpened(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partOpened(final IWorkbenchPartReference partRef) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setStates(partRef.getId());
}
});
}
/**
* 视图关闭时
* @see org.eclipse.ui.IPartListener2#partClosed(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partClosed(IWorkbenchPartReference partRef) {
if (!partRef.getPage().getWorkbenchWindow().getWorkbench().isClosing()) {
setStates(partRef.getId());
}
// 关闭时,根据是否是合并打开的文件,如果是,标识其是否被存储--robert
if ("net.heartsome.cat.ts.ui.xliffeditor.nattable.editor".equals(partRef.getId())) {
if (partRef.getPage().getWorkbenchWindow().getWorkbench().isClosing()) {
IXliffEditor xlfEditor = (IXliffEditor) partRef.getPart(true);
xlfEditor.setStore(true);
}
}
}
});
}
/**
* 状态栏的显示与隐藏 robert 2011-11-03
*/
public void setStatusVisible(boolean visible) {
getWindowConfigurer().setShowProgressIndicator(visible);
getWindowConfigurer().setShowStatusLine(visible);
getWindowConfigurer().getWindow().getShell().layout();
}
/**
* 控制状态栏右边的后台进度条的显示 robert 2012-11-07
*/
public void setProgressIndicatorVisible(boolean isVisible){
boolean isProgessIndicatorVisble = getWindowConfigurer().getShowProgressIndicator();
if ((isProgessIndicatorVisble && isVisible) || (!isProgessIndicatorVisble && !isVisible)) {
return;
}
getWindowConfigurer().setShowStatusLine(false);
getWindowConfigurer().setShowProgressIndicator(isVisible);
getWindowConfigurer().setShowStatusLine(true);
getWindowConfigurer().getWindow().getShell().layout();
}
/**
* 当程序第一次运行时(或是重新换了命名空间),设置项目视图的 link with editor 按钮处于选中状态
* robert 2013-01-04
*/
private void setInitLinkEnable(){
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
boolean isInitialRun = !store.getBoolean(IPreferenceConstants.INITIAL_RUN);
if (isInitialRun) {
IViewPart navigator = getWindowConfigurer().getWindow().getActivePage().findView("net.heartsome.cat.common.ui.navigator.view");
CommonNavigator commonNavigator = (CommonNavigator) navigator;
commonNavigator.setLinkingEnabled(true);
store.setValue(IPreferenceConstants.INITIAL_RUN, true);
}
}
/**
* 删除 RCP 自带的工具栏按钮
*/
public void postWindowCreate() {
IActionBarConfigurer actionBarConfigurer = getWindowConfigurer().getActionBarConfigurer();
IContributionItem[] coolItems = actionBarConfigurer.getCoolBarManager().getItems();
for (int i = 0; i < coolItems.length; i++) {
if (coolItems[i] instanceof ToolBarContributionItem) {
ToolBarContributionItem toolbarItem = (ToolBarContributionItem) coolItems[i];
if (toolbarItem.getId().equals("org.eclipse.ui.WorkingSetActionSet")
|| toolbarItem.getId().equals("org.eclipse.ui.edit.text.actionSet.annotationNavigation")
|| toolbarItem.getId().equals("org.eclipse.ui.edit.text.actionSet.navigation")) {
toolbarItem.getToolBarManager().removeAll();
}
}
}
actionBarConfigurer.getCoolBarManager().update(true);
addAutoPluginMenu();
}
private void automaticCheckUpdate() {
// 自动检查更新
final IPreferenceStore prefStore = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
int updatePolicy = prefStore.getInt(IPreferenceConstants.SYSTEM_AUTO_UPDATE);
boolean flg = false;
if (updatePolicy == IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_NEVER) {
return;
} else if (updatePolicy == IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_STARTUP) {
// 启动时检查更新
flg = true;
} else if (updatePolicy == IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_MONTHLY) {
// 每月 xx 日检查更新
int day = prefStore.getInt(IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_MONTHLY_DATE);
Calendar c = Calendar.getInstance();
int cYear = c.get(Calendar.YEAR);
int cMoth = c.get(Calendar.MONTH) + 1;
int cDay = c.get(Calendar.DAY_OF_MONTH);
String preUpdateDay = prefStore.getString("AUTO_UPDATE_FLAG");
if (preUpdateDay.equals("")) {
if (cDay == day) {
flg = true;
prefStore.setValue("AUTO_UPDATE_FLAG", cYear + "-" + cMoth + "-" + cDay);
}
} else {
String[] ymdStr = preUpdateDay.split("-");
Calendar uc = Calendar.getInstance();
int uYeaer = Integer.parseInt(ymdStr[0]);
int uMonth = Integer.parseInt(ymdStr[1]);
int uDay = Integer.parseInt(ymdStr[2]);
uc.set(uYeaer, uMonth - 1, uDay);
if(cDay == day && c.getTime().compareTo(uc.getTime()) > 0){
flg = true;
prefStore.setValue("AUTO_UPDATE_FLAG", cYear + "-" + cMoth + "-" + cDay);
}else if( cDay > day && (uYeaer < cYear || uMonth < cMoth )){
flg = true;
prefStore.setValue("AUTO_UPDATE_FLAG", cYear + "-" + cMoth + "-" + cDay);
}
}
} else if (updatePolicy == IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_WEEKLY) {
// 每周 xx 日检查更新
int weekday = prefStore.getInt(IPreferenceConstants.SYSTEM_CHECK_UPDATE_WITH_WEEKLY_DATE);
Calendar c = Calendar.getInstance();
int cWeekDay = c.get(Calendar.DAY_OF_WEEK);
int cYear = c.get(Calendar.YEAR);
int cMoth = c.get(Calendar.MONTH) + 1;
int cDay = c.get(Calendar.DAY_OF_MONTH);
String preUpdateDay = prefStore.getString(AUTO_UPDATE_FLAG);
if (preUpdateDay.equals("")) {
if (cWeekDay == weekday) {
flg = true;
prefStore.setValue(AUTO_UPDATE_FLAG, cYear + "-" + cMoth + "-" + cDay);
}
} else {
String[] ymdStr = preUpdateDay.split("-");
Calendar uc = Calendar.getInstance();
int uYeaer = Integer.parseInt(ymdStr[0]);
uc.set(uYeaer, Integer.parseInt(ymdStr[1]) - 1, Integer.parseInt(ymdStr[2]));
if (cWeekDay == weekday && c.getTime().compareTo(uc.getTime()) > 0) {
flg = true;
prefStore.setValue(AUTO_UPDATE_FLAG, cYear + "-" + cMoth + "-" + cDay);
}else if(cWeekDay > weekday && (uYeaer < cYear || uc.get(Calendar.WEEK_OF_YEAR) < c.get(Calendar.WEEK_OF_YEAR))){
flg = true;
prefStore.setValue(AUTO_UPDATE_FLAG, cYear + "-" + cMoth + "-" + cDay);
}
}
}
if (!flg) {
return;
}
AutomaticUpdate checker = new AutomaticUpdate();
checker.checkForUpdates();
}
/**
* 设置在拖动文件到导航视图时的模式为直接复制,见类 {@link CopyFilesAndFoldersOperation} 的方法 CopyFilesAndFoldersOperation
* robert 09-26
*/
private void setDragModle(){
IPreferenceStore store= IDEWorkbenchPlugin.getDefault().getPreferenceStore();
store.setValue(IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_MODE,
IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_MODE_MOVE_COPY);
store.setValue(IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_VIRTUAL_FOLDER_MODE,
IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_MODE_MOVE_COPY);
}
/**
* 给默认透视图添加监听,当透视图发生改变时,触发相关事件 robert 2012-10-18
* @param commandService
*/
private void setListenerToPespective(final ICommandService commandService){
final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IPerspectiveListener perspectiveListener = new IPerspectiveListener() {
public void perspectiveChanged(IWorkbenchPage page,
IPerspectiveDescriptor perspective, String changeId) {
}
public void perspectiveActivated(IWorkbenchPage page,
IPerspectiveDescriptor perspective) {
// 改变透视图时,发出监听去检查品质检查结果视图的状态,从而让 视图 菜单的状态与之保持一致。
commandService.refreshElements("net.heartsome.cat.ts.ui.qa.handlers.OpenQAResultViewCommand", null);
// 显示状态栏与工具栏
IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
boolean statusVisible = preferenceStore.getBoolean(TsPreferencesConstant.TS_statusBar_status);
if (!statusVisible) {
preferenceStore.setValue(TsPreferencesConstant.TS_statusBar_status, false);
try {
handlerService.executeCommand("net.heartsome.cat.ts.command.openStatusBar", null);
} catch (Exception ex) {
throw new RuntimeException("CommandTest.exitcommand not found");
}
}
WorkbenchWindow window_1 = (WorkbenchWindow)window;
if (!window_1.getCoolBarVisible()) {
try {
window_1.toggleToolbarVisibility();
commandService.refreshElements("net.heartsome.cat.ts.command.openToolBar", null);
} catch (Exception ex) {
throw new RuntimeException("CommandTest.exitcommand not found");
}
}
}
};
window.addPerspectiveListener(perspectiveListener);
}
/**
* robert 2012-11-11
*/
private void setIdToHelpSystem(){
WorkbenchHelpSystem helpSystem = (WorkbenchHelpSystem)PlatformUI.getWorkbench().getHelpSystem(); //setDesiredHelpSystemId
// net.heartsome.cat.ts.ui.help.selfHelp 为 插件 net.heartsome.cat.ts.ui.help 与的扩展点 helpSupport 的 id
helpSystem.setDesiredHelpSystemId("net.heartsome.cat.ts.ui.help.selfHelp");
}
/**
* 重新恢复产品上次退时出所保存的编辑器,此修复针对 mac 下的 bug 2998 启动:某客户安装的软件只能使用一次. robert 2013-05-21
*/
private void restorEditorHistory(){
// 只针对 mac 下的用户
if (System.getProperty("os.name").indexOf("Mac") == -1) {
return;
}
final WorkbenchPage page = (WorkbenchPage) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
monitor.beginTask("", 10);
String tempEditorHistoryLC = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(Constant.TEMP_EDITOR_HISTORY).toOSString();
File tempEditorHistoryFile = new File(tempEditorHistoryLC);
if (!tempEditorHistoryFile.exists()) {
return;
}
monitor.worked(1);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
VTDGen vg = new VTDGen();
try {
boolean parseResult = vg.parseFile(tempEditorHistoryLC, true);
if (!parseResult) {
return;
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
int storeFileSum = 0;
ap.selectXPath("count(/editors/editor)");
storeFileSum = (int)ap.evalXPathToNumber();
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
subMonitor.beginTask("", storeFileSum);
ap.selectXPath("/editors/editor");
String editorId = null;
String localFilePath = null;
boolean activate = false;
IEditorReference activateEditorRefe = null;
IEditorReference firstEditor = null;
IFile curIFile = null;
int index = -1;
while(ap.evalXPath() != -1){
activate = false;
editorId = null;
localFilePath = null;
if ((index = vn.getAttrVal("id")) != -1) {
editorId = vn.toRawString(index);
}
if ((index = vn.getAttrVal("path")) != -1) {
localFilePath = vn.toRawString(index);
}
if (editorId == null || editorId.trim().length() <= 0 || localFilePath == null || localFilePath.trim().length() <= 0) {
continue;
}
if ((index = vn.getAttrVal("active")) != -1) {
if ("true".equals(vn.toRawString(index))) {
activate = true;
}
}
curIFile = root.getFileForLocation(new Path(localFilePath));
if (!curIFile.exists()) {
subMonitor.worked(1);
continue;
}
if (activate) {
activateEditorRefe = page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
}else {
if (firstEditor == null) {
firstEditor = page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
}else {
page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
}
PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
}
subMonitor.worked(1);
}
PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
if (activateEditorRefe != null) {
if (firstEditor != null) {
page.activate(firstEditor.getEditor(true));
}
page.activate(activateEditorRefe.getEditor(true));
}
subMonitor.done();
monitor.done();
} catch (Exception e) {
LOGGER.error("restore editor file error", e);
}
}
};
try {
new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()).run(true, true, runnable);
} catch (Exception e) {
LOGGER.error("restore editor file error", e);
}
}
/**
* 在退出程序时保存所有打开的编辑器,此修复针对 mac 下的 bug 2998 启动:某客户安装的软件只能使用一次. robert 2013-05-21
*/
private void saveEditorHistory(){
PlatformUI.getWorkbench().addWorkbenchListener(new IWorkbenchListener() {
public boolean preShutdown(IWorkbench workbench, boolean forced) {
// 只针对 mac 下的用户
if (System.getProperty("os.name").indexOf("Mac") == -1) {
return true;
}
FileOutputStream stream = null;
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
try {
String tempEditorHistoryLC = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(Constant.TEMP_EDITOR_HISTORY).toOSString();
File tempEditorHistoryFile = new File(tempEditorHistoryLC);
if (!tempEditorHistoryFile.exists()) {
stream = new FileOutputStream(tempEditorHistoryLC);
stream.write("<editors></editors>".getBytes("UTF-8"));
}
IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
IEditorReference[] refreArray = page.getEditorReferences();
StringBuffer sb = new StringBuffer();
String editorId = "";
String path = "";
String active = "false";
IEditorPart activeEditor = page.getActiveEditor();
IEditorInput activeInput = null;
if (activeEditor != null) {
activeInput = activeEditor.getEditorInput();
}
IEditorInput curInput = null;
for(IEditorReference refre : refreArray){
active = "false";
editorId = refre.getId();
curInput = refre.getEditorInput();
path = ((FileEditorInput)curInput).getFile().getFullPath().toOSString();
path = root.getLocation().append(path).toOSString();
if (activeInput != null && activeInput == curInput) {
active = "true";
}
sb.append("<editor id='" + editorId + "' path='" + path + "' active='" + active + "'/>\n");
}
VTDGen vg = new VTDGen();
if (!vg.parseFile(tempEditorHistoryLC, true)) {
stream = new FileOutputStream(tempEditorHistoryLC);
stream.write("<editors></editors>".getBytes("UTF-8"));
vg.parseFile(tempEditorHistoryLC, true);
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
// 先删除之前的记录
ap.selectXPath("/editors/editor");
while(ap.evalXPath() != -1){
xm.remove();
}
ap.selectXPath("/editors");
if (ap.evalXPath() != -1) {
xm.insertBeforeTail(sb.toString());
}
xm.output(tempEditorHistoryLC);
} catch (Exception e) {
e.printStackTrace();
}finally{
if (stream != null) {
try {
stream.close();
} catch (Exception e2) {
}
}
}
return true;
}
public void postShutdown(IWorkbench workbench) {
// TODO Auto-generated method stub
}
});
}
/**
* 在插件一栏上,添加自定义插件的菜单 robert 2012-03-07 ;
*/
private void addAutoPluginMenu() {
// IContributionItem[] mItems;
// IMenuManager mm = getWindowConfigurer().getActionBarConfigurer().getMenuManager();
// mItems = mm.getItems();
// for (int i = 0; i < mItems.length; i++) {
// if (mItems[i] instanceof MenuManager) {
// System.out.println();
// if (((MenuManager) mItems[i]).getId().equals("net.heartsome.cat.ts.ui.menu.plugin")) {
// MenuManager manager = ((MenuManager) mItems[i]);
//
// final PluginConfigManage pluginManage = new PluginConfigManage();
// List<PluginConfigBean> pluginList = pluginManage.getPluginCofigData();
//
// if (pluginList.size() > 0) {
// manager.add(new Separator());
// }
// Action action;
// for (int j = 0; j < pluginList.size(); j++) {
// final PluginConfigBean bean = pluginList.get(j);
// action = new Action() {
// @Override
// public void run() {
// pluginManage.executePlugin(bean);
// }
// };
// action.setId(bean.getId());
// action.setText(bean.getName());
// manager.add(action);
// }
// }
// }
// }
}
}
| 28,132 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CommandsPropertyTester.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/CommandsPropertyTester.java | package net.heartsome.cat.ts;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.State;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.RegistryToggleState;
import org.eclipse.ui.services.IServiceLocator;
public class CommandsPropertyTester extends PropertyTester {
public CommandsPropertyTester() {
// TODO Auto-generated constructor stub
}
public static final String NAMESPACE = "org.eclipse.core.commands"; //$NON-NLS-1$
public static final String PROPERTY_BASE = NAMESPACE + '.';
public static final String TOGGLE_PROPERTY_NAME = "toggle"; //$NON-NLS-1$
public static final String TOGGLE_PROPERTY = PROPERTY_BASE
+ TOGGLE_PROPERTY_NAME;
public boolean test(final Object receiver, final String property,
final Object[] args, final Object expectedValue) {
if (receiver instanceof IServiceLocator && args.length == 1
&& args[0] instanceof String) {
final IServiceLocator locator = (IServiceLocator) receiver;
if (TOGGLE_PROPERTY_NAME.equals(property)) {
final String commandId = args[0].toString();
final ICommandService commandService = (ICommandService) locator
.getService(ICommandService.class);
final Command command = commandService.getCommand(commandId);
final State state = command
.getState(RegistryToggleState.STATE_ID);
if (state != null) {
return state.getValue().equals(expectedValue);
}
}
}
return false;
}
}
| 1,513 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TsStartup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/TsStartup.java | package net.heartsome.cat.ts;
import org.eclipse.ui.IStartup;
public class TsStartup implements IStartup {
public void earlyStartup() {
}
}
| 149 | 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/src/net/heartsome/cat/ts/Activator.java | package net.heartsome.cat.ts;
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";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
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,153 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TSPerspective.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/TSPerspective.java | /**
* Perspective.java
*
* Version information :
*
* Date:Jan 27, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.ts;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
/**
* .
* @author Jason
* @version
* @since JDK1.6
*/
public class TSPerspective implements IPerspectiveFactory {
public final static String ID = "net.heartsome.cat.ts.perspective";
/**
* TS默认透视图。
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
*/
public void createInitialLayout(IPageLayout layout) {
// layout.createFolder() 默认显示。
// layout.createPlaceholderFolder() 默认不显示。
String editor = layout.getEditorArea();
// String rightFirst = "RIGHT_TOP";
String left = "LEFT";
String right = "RIGHT";
// String bottom = "RIGHT_BOTTOM";
IFolderLayout leftFolder = layout.createFolder(left, IPageLayout.LEFT, 0.20F, editor);
// IFolderLayout topFirstFolder = layout.createFolder(rightFirst, IPageLayout.TOP, 0.3F, editor);
IFolderLayout rightFolder = layout.createFolder(right, IPageLayout.RIGHT, 0.70F, editor);
// 显示术语匹配结果视图
// IFolderLayout bottomFolder = layout
// .createFolder(bottom, IPageLayout.TOP, 0.65F, editor);
// IPlaceholderFolderLayout pLayout = layout.createPlaceholderFolder(bottom, IPageLayout.RIGHT, 0.65F, editor);
leftFolder.addView("net.heartsome.cat.common.ui.navigator.view"); // 导航视图
rightFolder.addView("net.heartsome.cat.ts.ui.translation.view.matchview");
// topFirstFolder.addView("net.heartsome.cat.ts.ui.translation.view.matchview");
// bottomFolder.addView("net.heartsome.cat.ts.ui.term.view.termView"); // 术语匹配视图
// pLayout.addPlaceholder("net.heartsome.cat.ts.ui.qa.views.QAResultViewPart");
}
}
| 1,851 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationActionBarAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/ApplicationActionBarAdvisor.java | package net.heartsome.cat.ts;
import java.util.Arrays;
import java.util.List;
import net.heartsome.cat.ts.resource.Messages;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarContributionItem;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.ReopenEditorMenu;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.registry.ActionSetRegistry;
import org.eclipse.ui.internal.registry.IActionSetDescriptor;
import org.eclipse.ui.menus.IMenuService;
/**
* An action bar advisor is responsible for creating, adding, and disposing of the actions added to a workbench window.
* Each window will be populated with new actions.
*/
@SuppressWarnings("restriction")
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
private final IWorkbenchWindow window;
// Actions - important to allocate these only in makeActions, and then use
// them
// in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
// tool bar context menu
private IWorkbenchAction lockToolBarAction;
// file menu action
// private IWorkbenchAction newAction;
private IWorkbenchAction closeAction;
private IWorkbenchAction closeAllAction;
private IWorkbenchAction refreshAction;
private IWorkbenchAction exitAction;
// edit menu action
private IWorkbenchAction undoAction;
private IWorkbenchAction redoAction;
private IWorkbenchAction cutAction;
private IWorkbenchAction copyAction;
private IWorkbenchAction pasteAction;
private IWorkbenchAction deleteAction;
private IWorkbenchAction renameAction;
private IWorkbenchAction selectAllAction;
private IWorkbenchAction findAction;
// help menu action
private IWorkbenchAction helpAction;
// private IWorkbenchAction helpSearchAction;
// private IWorkbenchAction dynamicHelpAction;
// private Action aboutAction;
/**
* Indicates if the action builder has been disposed
*/
private boolean isDisposed = false;
/**
* The coolbar context menu manager.
*/
private MenuManager coolbarPopupMenuManager;
/**
* @param configurer
*/
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
window = configurer.getWindowConfigurer().getWindow();
}
@Override
protected void makeActions(final IWorkbenchWindow window) {
// Creates the actions and registers them.
// Registering is needed to ensure that key bindings work.
// The corresponding commands keybindings are defined in the plugin.xml
// file.
// Registering also provides automatic disposal of the actions when
// the window is closed.
// newAction = ActionFactory.NEW_WIZARD_DROP_DOWN.create(window);
// register(newAction);
// newAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator
// .getImageDescriptor(ImageConstant.FILE_NEW_PROJECT));
// newAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.newAction"));
closeAction = ActionFactory.CLOSE.create(window);
register(closeAction);
closeAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.closeAction"));
closeAllAction = ActionFactory.CLOSE_ALL.create(window);
register(closeAllAction);
closeAllAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.closeAllAction"));
refreshAction = ActionFactory.REFRESH.create(window);
register(refreshAction);
refreshAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.refreshAction"));
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
exitAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/file/logout.png"));
exitAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.exitAction"));
undoAction = ActionFactory.UNDO.create(window);
undoAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.undoAction"));
undoAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/undo.png"));
register(undoAction);
redoAction = ActionFactory.REDO.create(window);
redoAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.redoAction"));
redoAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/redo.png"));
register(redoAction);
cutAction = ActionFactory.CUT.create(window);
register(cutAction);
cutAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/cut.png"));
cutAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.cutAction"));
copyAction = ActionFactory.COPY.create(window);
copyAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.copyAction"));
copyAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/copy.png"));
register(copyAction);
pasteAction = ActionFactory.PASTE.create(window);
pasteAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.pasteAction"));
pasteAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/paste.png"));
register(pasteAction);
deleteAction = ActionFactory.DELETE.create(window);
deleteAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.deleteAction"));
deleteAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor("images/edit/delete.png"));
register(deleteAction);
renameAction = ActionFactory.RENAME.create(window);
register(renameAction);
renameAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.renameAction"));
selectAllAction = ActionFactory.SELECT_ALL.create(window);
selectAllAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.selectAllAction"));
register(selectAllAction);
findAction = ActionFactory.FIND.create(window);
findAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.findAction"));
findAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator
.getImageDescriptor("images/edit/search_replace.png"));
register(findAction);
lockToolBarAction = ActionFactory.LOCK_TOOL_BAR.create(window);
register(lockToolBarAction);
helpAction = ActionFactory.HELP_CONTENTS.create(window);
helpAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.helpAction"));
helpAction.setImageDescriptor(Activator.getImageDescriptor("images/help/help.png"));
register(helpAction);
// helpSearchAction = ActionFactory.HELP_SEARCH.create(window);
// helpSearchAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.helpSearchAction"));
// register(helpSearchAction);
//
// dynamicHelpAction = ActionFactory.DYNAMIC_HELP.create(window);
// dynamicHelpAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.dynamicHelpAction"));
// ImageDescriptor helpImageDescriptor = Activator.getImageDescriptor("images/find.png");
// dynamicHelpAction.setImageDescriptor(helpImageDescriptor);
// register(dynamicHelpAction);
// ImageDescriptor aboutImageDescriptor = Activator.getImageDescriptor("images/help/about.png");
// aboutAction = ActionFactory.ABOUT.create(window);
// aboutAction = new AboutAction(Messages.getString("ts.ApplicationActionBarAdvisor.aboutAction"),
// aboutImageDescriptor);
// aboutAction.setText(Messages.getString("ts.ApplicationActionBarAdvisor.aboutAction"));
// aboutAction.setImageDescriptor(aboutImageDescriptor);
// register(aboutAction);
removeUnusedAction();
}
@Override
protected void fillMenuBar(IMenuManager menuBar) {
menuBar.add(createFileMenu());
menuBar.add(createEditMenu());
menuBar.add(new GroupMarker("view"));
menuBar.add(new GroupMarker("translation"));
menuBar.add(new GroupMarker("project"));
menuBar.add(new GroupMarker("database"));
menuBar.add(new GroupMarker("qa"));
menuBar.add(createToolMenu());
menuBar.add(new GroupMarker("advance"));
// menuBar.add(createAutoPluginMenu());
menuBar.add(createHelpMenu());
}
@Override
protected void fillCoolBar(ICoolBarManager coolBar) {
// Set up the context Menu
coolbarPopupMenuManager = new MenuManager();
coolbarPopupMenuManager.add(new ActionContributionItem(lockToolBarAction));
coolBar.setContextMenuManager(coolbarPopupMenuManager);
IMenuService menuService = (IMenuService) window.getService(IMenuService.class);
menuService.populateContributionManager(coolbarPopupMenuManager, "popup:windowCoolbarContextMenu");
coolBar.add(new GroupMarker("group.file"));
// File Group
// IToolBarManager fileToolBar = new ToolBarManager(coolBar.getStyle());
// fileToolBar.add(new Separator(IWorkbenchActionConstants.NEW_GROUP));
// fileToolBar.add(new GroupMarker(IWorkbenchActionConstants.OPEN_EXT));
// fileToolBar.add(new GroupMarker(IWorkbenchActionConstants.SAVE_GROUP));
// // 为了使工具栏和菜单中的图片大小不一样,重新创建新建 Action
// newAction = ActionFactory.NEW_WIZARD_DROP_DOWN.create(window);
// register(newAction);
// ImageDescriptor newImage =
// net.heartsome.cat.ts.ui.Activator.getImageDescriptor(ImageConstant.TOOL_NEW_PROJECT);
// newAction.setImageDescriptor(newImage);
// // 解决在 Windows 下图片显示错误的问题
// newAction.setDisabledImageDescriptor(newImage);
// newAction.setToolTipText(Messages.getString("ts.ApplicationActionBarAdvisor.newAction"));
// fileToolBar.add(newAction);
// saveAction = ActionFactory.SAVE.create(window);
// register(saveAction);
// saveAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor(ImageConstant.TOOL_SAVE));
// saveAction.setToolTipText("保存");
// fileToolBar.add(saveAction);
// undoAction = ActionFactory.UNDO.create(window);
// register(undoAction);
// undoAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor(ImageConstant.TOOL_UNDO));
// undoAction.setToolTipText("撤销");
// fileToolBar.add(undoAction);
//
// redoAction = ActionFactory.REDO.create(window);
// register(redoAction);
// redoAction.setImageDescriptor(net.heartsome.cat.ts.ui.Activator.getImageDescriptor(ImageConstant.TOOL_REDO));
// redoAction.setToolTipText("重做");
// fileToolBar.add(redoAction);
// fileToolBar.add(new GroupMarker(IWorkbenchActionConstants.SAVE_EXT));
// fileToolBar.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
// Add to the cool bar manager
// coolBar.add(new ToolBarContributionItem(fileToolBar, IWorkbenchActionConstants.TOOLBAR_FILE));
coolBar.add(new GroupMarker("group.new.menu"));
coolBar.add(new GroupMarker("group.undoredo"));
coolBar.add(new GroupMarker("group.copySource"));
coolBar.add(new GroupMarker("group.search"));
//createToolItem(coolBar);
coolBar.add(new GroupMarker("group.findreplace"));
coolBar.add(new GroupMarker("group.completeTranslation"));
coolBar.add(new GroupMarker("group.approve"));
coolBar.add(new GroupMarker("group.addTerm"));
coolBar.add(new GroupMarker("group.preview"));
coolBar.add(new GroupMarker("group.tagoperation"));
coolBar.add(new GroupMarker("group.sourceoperation"));
coolBar.add(new GroupMarker("group.deleteTrans"));
coolBar.add(new GroupMarker("group.changeLayout"));
coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR));
coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_HELP));
// Help group
// IToolBarManager helpToolBar = new ToolBarManager(coolBar.getStyle());
// helpToolBar.add(new Separator(IWorkbenchActionConstants.GROUP_HELP));
// // 按照设计文档的要求,先注释 helpSearchAction
// // helpToolBar.add(helpSearchAction);
// // Add the group for applications to contribute
// helpToolBar.add(new GroupMarker("tagoperation"));
// helpToolBar.add(new GroupMarker("pretranslation"));
//
// // Add to the cool bar manager
// coolBar.add(new ToolBarContributionItem(helpToolBar, IWorkbenchActionConstants.TOOLBAR_HELP));
//coolBar.add(createToolItem(coolBar));
}
private IToolBarManager createToolItem(ICoolBarManager coolBar) {
IToolBarManager toolBar = new ToolBarManager(coolBar.getStyle());
coolBar.add(new ToolBarContributionItem(toolBar, "findreplace"));
toolBar.add(findAction);
return toolBar;
}
/**
* 创建工具菜单
* @return 返回工具菜单的 menu manager;
*/
private MenuManager createToolMenu() {
MenuManager menu = new MenuManager(Messages.getString("ts.ApplicationActionBarAdvisor.menu.tool"),
"net.heartsome.cat.ts.ui.menu.tool"); // &Tool
menu.add(new GroupMarker("pluginConfigure"));
menu.add(new GroupMarker("preference.groupMarker"));
// menu.add(preferenceAction);
return menu;
}
/**
* 创建文件菜单
* @return 返回文件菜单的 menu manager;
*/
private MenuManager createFileMenu() {
MenuManager menu = new MenuManager(Messages.getString("ts.ApplicationActionBarAdvisor.menu.file"),
IWorkbenchActionConstants.M_FILE); // &File
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START));
// 添加 new.ext group,这样 IDE 中定义的 Open File... 可以显示在最顶端
// menu.add(newAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.NEW_EXT));
menu.add(new Separator());
menu.add(closeAction);
menu.add(closeAllAction);
menu.add(refreshAction);
// menu.add(new Separator("net.heartsome.cat.ts.ui.menu.file.separator"));
menu.add(new GroupMarker("xliff.switch"));
menu.add(new GroupMarker("rtf.switch"));
menu.add(new GroupMarker("xliff.split"));
menu.add(new Separator());
// 设置保存文件记录条数为 5 条
WorkbenchPlugin.getDefault().getPreferenceStore().setValue(IPreferenceConstants.RECENT_FILES, 5);
// 添加文件访问列表
ContributionItemFactory REOPEN_EDITORS = new ContributionItemFactory("reopenEditors") { //$NON-NLS-1$
/* (non-javadoc) method declared on ContributionItemFactory */
public IContributionItem create(IWorkbenchWindow window) {
if (window == null) {
throw new IllegalArgumentException();
}
return new ReopenEditorMenu(window, getId(), false);
}
};
menu.add(REOPEN_EDITORS.create(window));
menu.add(exitAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_END));
return menu;
}
/**
* 创建编辑菜单
* @return 返回编辑菜单的 menu manager;
*/
private MenuManager createEditMenu() {
MenuManager menu = new MenuManager(Messages.getString("ts.ApplicationActionBarAdvisor.menu.edit"),
IWorkbenchActionConstants.M_EDIT); // &Edit
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_START));
// menu.add(undoAction);
// menu.add(redoAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT));
menu.add(new Separator());
menu.add(cutAction);
menu.add(copyAction);
menu.add(pasteAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT));
// menu.add(deleteAction);
menu.add(renameAction);
menu.add(new Separator());
menu.add(findAction);
menu.add(selectAllAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.FIND_EXT));
// menu.add(new Separator());
// menu.add(preferenceAction);
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_END));
return menu;
}
/**
* 创建帮助菜单
* @return 返回帮助菜单的 menu manager;
*/
private MenuManager createHelpMenu() {
MenuManager menu = new MenuManager(Messages.getString("ts.ApplicationActionBarAdvisor.menu.help"),
IWorkbenchActionConstants.M_HELP);
// menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_START));
menu.add(helpAction);
// menu.add(helpSearchAction);
// menu.add(dynamicHelpAction);
// menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_END));
menu.add(new GroupMarker("help.keyAssist"));
menu.add(new Separator());
menu.add(new GroupMarker("help.updatePlugin"));
menu.add(new Separator());
menu.add(new GroupMarker("help.license"));
// 关于菜单需要始终显示在最底端
menu.add(new GroupMarker("group.about"));
// ActionContributionItem aboutItem = new ActionContributionItem(aboutAction);
// aboutItem.setVisible(!Util.isMac());
// menu.add(aboutItem);
return menu;
}
/**
* 创建自定义的插件菜单 2012-03-07
* @return ;
*/
/*
* private MenuManager createAutoPluginMenu() { MenuManager menu = new MenuManager("asdfasd",
* "net.heartsome.cat.ts.ui.menu.plugin"); // menu = MenuManag
*
* // menu.appendToGroup(groupName, item) menu.add(helpSearchAction); return menu; }
*/
@Override
public void dispose() {
if (isDisposed) {
return;
}
isDisposed = true;
IMenuService menuService = (IMenuService) window.getService(IMenuService.class);
menuService.releaseContributions(coolbarPopupMenuManager);
coolbarPopupMenuManager.dispose();
super.dispose();
}
/**
* 移除无用的菜单项:<br/>
* File 菜单下的“open file...”和“Convert Line Delimiters To”
*/
private void removeUnusedAction() {
ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry();
IActionSetDescriptor[] actionSets = reg.getActionSets();
List<String> actionSetIds = Arrays.asList("org.eclipse.ui.actionSet.openFiles",
"org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo",
"org.eclipse.ui.actions.showKeyAssistHandler");
for (int i = 0; i < actionSets.length; i++) {
if (actionSetIds.contains(actionSets[i].getId())) {
IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension();
reg.removeExtension(ext, new Object[] { actionSets[i] });
}
}
}
}
| 18,437 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UnOpenAgainEditorPresentationFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/UnOpenAgainEditorPresentationFactory.java | package net.heartsome.cat.ts;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.presentations.defaultpresentation.DefaultMultiTabListener;
import org.eclipse.ui.internal.presentations.defaultpresentation.DefaultSimpleTabListener;
import org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder;
import org.eclipse.ui.internal.presentations.defaultpresentation.DefaultThemeListener;
import org.eclipse.ui.internal.presentations.util.PresentablePartFolder;
import org.eclipse.ui.internal.presentations.util.TabbedStackPresentation;
import org.eclipse.ui.presentations.IStackPresentationSite;
import org.eclipse.ui.presentations.StackPresentation;
import org.eclipse.ui.presentations.WorkbenchPresentationFactory;
/**
* 不使用 RCP 自带的 WorkbenchPresentationFactory,用于去除编辑器标题右键菜单中的“新建编辑器”菜单项
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class UnOpenAgainEditorPresentationFactory extends WorkbenchPresentationFactory {
private static int editorTabPosition = PlatformUI.getPreferenceStore()
.getInt(IWorkbenchPreferenceConstants.EDITOR_TAB_POSITION);
public StackPresentation createEditorPresentation(Composite parent,
IStackPresentationSite site) {
DefaultTabFolder folder = new DefaultTabFolder(parent,
editorTabPosition | SWT.BORDER, site
.supportsState(IStackPresentationSite.STATE_MINIMIZED),
site.supportsState(IStackPresentationSite.STATE_MAXIMIZED));
/*
* Set the minimum characters to display, if the preference is something
* other than the default. This is mainly intended for RCP applications
* or for expert users (i.e., via the plug-in customization file).
*
* Bug 32789.
*/
final IPreferenceStore store = PlatformUI.getPreferenceStore();
if (store
.contains(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS)) {
final int minimumCharacters = store
.getInt(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS);
if (minimumCharacters >= 0) {
folder.setMinimumCharacters(minimumCharacters);
}
}
PresentablePartFolder partFolder = new PresentablePartFolder(folder);
TabbedStackPresentation result = new TabbedStackPresentation(site,
partFolder, new StandardEditorSystemMenu(site));
DefaultThemeListener themeListener = new DefaultThemeListener(folder,
result.getTheme());
result.getTheme().addListener(themeListener);
new DefaultMultiTabListener(result.getApiPreferences(),
IWorkbenchPreferenceConstants.SHOW_MULTIPLE_EDITOR_TABS, folder);
new DefaultSimpleTabListener(result.getApiPreferences(),
IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS,
folder);
return result;
}
}
| 2,943 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StandardEditorSystemMenu.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/StandardEditorSystemMenu.java | package net.heartsome.cat.ts;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.presentations.SystemMenuClose;
import org.eclipse.ui.internal.presentations.SystemMenuCloseAll;
import org.eclipse.ui.internal.presentations.SystemMenuCloseOthers;
import org.eclipse.ui.internal.presentations.SystemMenuMaximize;
import org.eclipse.ui.internal.presentations.SystemMenuMinimize;
import org.eclipse.ui.internal.presentations.SystemMenuMove;
import org.eclipse.ui.internal.presentations.SystemMenuRestore;
import org.eclipse.ui.internal.presentations.UpdatingActionContributionItem;
import org.eclipse.ui.internal.presentations.util.ISystemMenu;
import org.eclipse.ui.presentations.IPresentablePart;
import org.eclipse.ui.presentations.IStackPresentationSite;
/**
* 定制编辑器右键菜单
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class StandardEditorSystemMenu implements ISystemMenu {
/* package */ MenuManager menuManager = new MenuManager();
private SystemMenuRestore restore;
private SystemMenuMove move;
private SystemMenuMinimize minimize;
private SystemMenuMaximize maximize;
private SystemMenuClose close;
private SystemMenuCloseOthers closeOthers;
private SystemMenuCloseAll closeAll;
/**
* Create the standard view menu
*
* @param site the site to associate the view with
*/
public StandardEditorSystemMenu(IStackPresentationSite site) {
restore = new SystemMenuRestore(site);
move = new SystemMenuMove(site, getMoveMenuText(), false);
minimize = new SystemMenuMinimize(site);
maximize = new SystemMenuMaximize(site);
close = new SystemMenuClose(site);
closeOthers = new SystemMenuCloseOthers(site);
closeAll = new SystemMenuCloseAll(site);
{ // Initialize system menu
menuManager.add(new GroupMarker("misc")); //$NON-NLS-1$
menuManager.add(new GroupMarker("restore")); //$NON-NLS-1$
menuManager.add(new UpdatingActionContributionItem(restore));
menuManager.add(move);
menuManager.add(new GroupMarker("size")); //$NON-NLS-1$
menuManager.add(new GroupMarker("state")); //$NON-NLS-1$
menuManager.add(new UpdatingActionContributionItem(minimize));
menuManager.add(new UpdatingActionContributionItem(maximize));
menuManager.add(new Separator("close")); //$NON-NLS-1$
menuManager.add(close);
menuManager.add(closeOthers);
menuManager.add(closeAll);
site.addSystemActions(menuManager);
} // End of system menu initialization
}
String getMoveMenuText() {
return WorkbenchMessages.EditorPane_moveEditor;
}
/* (non-Javadoc)
* @see org.eclipse.ui.internal.presentations.util.ISystemMenu#show(org.eclipse.swt.graphics.Point, org.eclipse.ui.presentations.IPresentablePart)
*/
public void show(Control parent, Point displayCoordinates, IPresentablePart currentSelection) {
restore.update();
move.setTarget(currentSelection);
move.update();
minimize.update();
maximize.update();
close.setTarget(currentSelection);
closeOthers.setTarget(currentSelection);
closeAll.update();
Menu aMenu = menuManager.createContextMenu(parent);
menuManager.update(true);
aMenu.setLocation(displayCoordinates.x, displayCoordinates.y);
aMenu.setVisible(true);
}
/**
* Dispose resources associated with this menu
*/
public void dispose() {
menuManager.dispose();
menuManager.removeAll();
}
}
| 4,009 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Application.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/Application.java | package net.heartsome.cat.ts;
import java.io.File;
import java.io.FileOutputStream;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.ui.Activator;
import net.heartsome.cat.ts.ui.preferencepage.IPreferenceConstants;
import net.heartsome.cat.ts.ui.util.PreferenceUtil;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* This class controls all aspects of the application's execution
*/
public class Application implements IApplication {
public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
try {
PreferenceUtil.initProductEdition();
deleteErrorMemoryInfo();
initSystemLan();
PreferenceUtil.checkCleanValue();
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
private void initSystemLan(){
int lanId = Activator.getDefault().getPreferenceStore().getInt(IPreferenceConstants.SYSTEM_LANGUAGE);
CommonFunction.setSystemLanguage(lanId == 0 ? "en" : "zh");
}
public void stop() {
final IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null) {
return;
}
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed()) {
workbench.close();
}
}
});
}
/**
* 删除错误记录文件,以修改产品第一次运行后,存储错误信息导致第二次打不开的情况 robert 2013-05-15
*/
private static void deleteErrorMemoryInfo(){
// 只针对 mac 下的用户
if (System.getProperty("os.name").indexOf("Mac") == -1) {
return;
}
String workbenchXmlPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(".metadata/.plugins/org.eclipse.ui.workbench/workbench.xml").toOSString();
VTDGen vg = new VTDGen();
boolean result = vg.parseFile(workbenchXmlPath, true);
if (!result) {
new File(workbenchXmlPath).delete();
return;
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
FileOutputStream stream = null;
try {
XMLModifier xm = new XMLModifier(vn);
// 删除节点 editor
ap.selectXPath("/workbench/window/page/editors/editor");
while (ap.evalXPath() != -1) {
xm.remove();
}
// 删除其他记录
ap.selectXPath("/workbench/window/page/navigationHistory");
if (ap.evalXPath() != -1) {
xm.remove();
}
xm.output(workbenchXmlPath);
} catch (Exception e) {
// do nothing
}finally{
if (stream != null) {
try {
stream.close();
} catch (Exception e2) {
}
}
}
}
}
| 3,083 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreferencesComparator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/PreferencesComparator.java | package net.heartsome.cat.ts;
import net.heartsome.cat.ts.ui.preferencepage.SystemPreferencePage;
import net.heartsome.cat.ts.ui.preferencepage.colors.ColorsPreferencePage;
import net.heartsome.cat.ts.ui.preferencepage.languagecode.LanguageCodesPreferencePage;
import net.heartsome.cat.ts.ui.preferencepage.translation.TranslationPreferencePage;
import org.eclipse.ui.internal.dialogs.WorkbenchPreferenceNode;
import org.eclipse.ui.model.ContributionComparator;
import org.eclipse.ui.model.IComparableContribution;
/**
* 用户对首选项菜单进行排序的类
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class PreferencesComparator extends ContributionComparator {
public int category(IComparableContribution c) {
if (c instanceof WorkbenchPreferenceNode) {
String id = ((WorkbenchPreferenceNode) c).getId();
if (SystemPreferencePage.ID.equals(id)) {
// 系统菜单
return 2;
} else if (LanguageCodesPreferencePage.ID.equals(id)) {
// 系统 > 语言代码菜单
return 3;
} else if (ColorsPreferencePage.ID.equals(id)) {
// 系统 > 颜色菜单
return 4;
} else if ("org.eclipse.ui.preferencePages.Keys".equals(id)) {
// 系统 > 快捷键菜单
return 5;
} else if ("org.eclipse.ui.net.proxy_preference_page_context".equals(id)) {
// 网络连接
return 6;
} else if ("net.heartsome.cat.ts.ui.qa.preference.QAPage".equals(id)) {
// 品质检查菜单
return 7;
} else if ("net.heartsome.cat.ts.ui.qa.preference.QAInstalPage".equals(id)) {
// 品质检查 > 批量检查设置菜单
return 8;
} else if ("net.heartsome.cat.ts.ui.qa.preference.NonTranslationQAPage".equals(id)) {
// 品质检查 > 非译元素菜单
return 9;
}
else if ("net.heartsome.cat.ts.ui.qa.preference.SpellPage".equals(id)) {
// 品质检查 > 拼写检查配置
return 11;
} else if ("net.heartsome.cat.ts.ui.qa.preference.FileAnalysisInstalPage".equals(id)) {
// 文件分析
return 12;
} else if ("net.heartsome.cat.ts.ui.qa.preference.EquivalentPage".equals(id)) {
// 文件分析 --> 加权系数设置
return 13;
} else if (TranslationPreferencePage.ID.equals(id)) {
// 翻译菜单
return 14;
} else if ("net.heartsome.cat.database.ui.tm.preference.tmpage".equals(id)) {
// 记忆库
return 15;
} else if ("net.heartsome.cat.database.ui.tb.preference.tbpage".equals(id)) {
// 术语库菜单
return 16;
} else if ("net.heartsome.cat.ts.pretranslation.preferencepage".equals(id)) {
// 预翻译
return 17;
} else if ("net.heartsome.cat.ts.machinetranslation.prefrence.MachineTranslationPreferencePage".equals(id)) {
// 修改google翻译的位置为机器翻译
return 18;
} else if ("net.heartsome.cat.ts.websearch.ui.preference.WebSearchPreferencePage".equals(id)) {
// bing
return 19;
} else if ("net.heartsome.cat.convert.ui.preference.FileTypePreferencePage".equals(id)) {
// 文件类型
return 20;
} else if ("net.heartsome.cat.converter.msexcel2007.preference.ExcelPreferencePage".equals(id)) {
// Microsoft Excel 2007
return 21;
} else if ("net.heartsome.cat.converter.pptx.preference.PPTXPreferencePage".equals(id)) {
// Microsoft PowerPoint 2007
return 22;
} else if ("net.heartsome.cat.converter.mif.preference.FrameMakerPreferencePage".equals(id)) {
// Adobe FrameMaker
return 23;
} else if ("net.heartsome.cat.ts.ui.preferencepage.ProjectPropertiesPreferencePage".equals(id)) {
// 项目属性
return 24;
} else {
return super.category(c);
}
} else {
return super.category(c);
}
}
}
| 3,716 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TsPreferencesConstant.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/TsPreferencesConstant.java | package net.heartsome.cat.ts;
/**
* TS系统级别参数常量
* @author jason
* @version
* @since JDK1.6
*/
public class TsPreferencesConstant {
/** 状态栏的显示状态 */
public final static String TS_statusBar_status = "net.heartsome.cat.ts.statusBarStatus";
}
| 282 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/ApplicationWorkbenchAdvisor.java | package net.heartsome.cat.ts;
import java.net.URL;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.application.IWorkbenchConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.model.ContributionComparator;
import org.eclipse.ui.model.IContributionService;
import org.osgi.framework.Bundle;
/**
* @author cheney
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
public static ApplicationWorkbenchWindowAdvisor WorkbenchWindowAdvisor = null;
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
WorkbenchWindowAdvisor = new ApplicationWorkbenchWindowAdvisor(configurer);
return WorkbenchWindowAdvisor;
}
@Override
public String getInitialWindowPerspectiveId() {
return TSPerspective.ID;
}
@Override
public IAdaptable getDefaultPageInput() {
return ResourcesPlugin.getWorkspace().getRoot();
}
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
// make sure we always save and restore workspace state
configurer.setSaveAndRestore(true);
IDE.registerAdapters();
declareWorkbenchImages();
}
/**
* 声明所需要使用的图片;
*/
private void declareWorkbenchImages() {
final String iconsPath = "$nl$/icons/full/"; //$NON-NLS-1$
final String pathElocaltool = iconsPath + "elcl16/"; // Enabled //$NON-NLS-1$
final String pathObject = iconsPath + "obj16/"; // Model object //$NON-NLS-1$
Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT, pathObject + "prj_obj.gif", true); //$NON-NLS-1$
declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, pathObject + "cprj_obj.gif", true); //$NON-NLS-1$
declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER, pathElocaltool + "gotoobj_tsk.gif", true); //$NON-NLS-1$
declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK, pathObject + "taskmrk_tsk.gif", true); //$NON-NLS-1$
declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK, pathObject + "bkmrk_tsk.gif", true); //$NON-NLS-1$
}
/**
* Declares an IDE-specific workbench image.
* @param symbolicName
* the symbolic name of the image
* @param path
* the path of the image file; this path is relative to the base of the IDE plug-in
* @param shared
* <code>true</code> if this is a shared image, and <code>false</code> if this is not a shared image
* @see IWorkbenchConfigurer#declareImage
*/
private void declareWorkbenchImage(Bundle ideBundle, String symbolicName, String path, boolean shared) {
URL url = FileLocator.find(ideBundle, new Path(path), null);
ImageDescriptor desc = ImageDescriptor.createFromURL(url);
getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
}
/**
* 对首选项菜单排序时,需要覆盖该方法
*/
public ContributionComparator getComparatorFor(String contributionType) {
if (contributionType.equals(IContributionService.TYPE_PREFERENCE)) {
return new PreferencesComparator();
}
else {
return super.getComparatorFor(contributionType);
}
}
}
| 3,752 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TsPreferencesInitializer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/TsPreferencesInitializer.java | package net.heartsome.cat.ts;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* TS系统级别参数初始化<br>
* 用于初始化系统级别的参数(是否显示状态栏)
*
* robert 2012-03-20
*/
public class TsPreferencesInitializer extends AbstractPreferenceInitializer {
public TsPreferencesInitializer() {
}
@Override
public void initializeDefaultPreferences() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
preferenceStore.setDefault(TsPreferencesConstant.TS_statusBar_status, true);
}
}
| 644 | 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/src/net/heartsome/cat/ts/dialog/AboutDialog.java | package net.heartsome.cat.ts.dialog;
import java.text.MessageFormat;
import net.heartsome.cat.ts.Activator;
import net.heartsome.cat.ts.resource.Messages;
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.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
/**
* 关于对话框
* @author peason
* @version
* @since JDK1.6
*/
public class AboutDialog extends Dialog {
private Image image;
private Font font;
public AboutDialog(Shell parentShell) {
super(parentShell);
image = Activator.getImageDescriptor("images/help/aboutR8.png").createImage();
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.AboutDialog.title"));
}
@Override
protected Control createDialogArea(Composite parent) {
final Composite tparent = (Composite) super.createDialogArea(parent);
GridLayoutFactory.swtDefaults().spacing(0, 0).extendedMargins(SWT.DEFAULT, SWT.DEFAULT, 0, 8).applyTo(tparent);
GridData parentData = new GridData(GridData.FILL_BOTH);
parentData.heightHint = 480;
parentData.widthHint = 445;
tparent.setLayoutData(parentData);
Composite cmpMain = new Composite(tparent, SWT.None);
cmpMain.setLayout(new GridLayout());
cmpMain.setLayoutData(new GridData(GridData.FILL_BOTH));
Color white = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
cmpMain.setBackground(white);
Label lblImage = new Label(cmpMain, SWT.CENTER);
lblImage.setImage(image);
// lblImage.setLayoutData(new GridData(GridData.FILL_BOTH));
lblImage.setBackground(white);
GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
Label lblVersion = new Label(cmpMain, SWT.BOLD);
FontData fontData = Display.getDefault().getSystemFont().getFontData()[0];
fontData.setStyle(fontData.getStyle() | SWT.BOLD);
this.font = new Font(lblVersion.getDisplay(), fontData);
lblVersion.setFont(this.font);
String version = System.getProperty("TSEdition");
if (version.equals("U")) {
lblVersion.setText(Messages.getString("dialog.AboutDialog.lblVersionU"));
} else if (version.equals("F")) {
lblVersion.setText(Messages.getString("dialog.AboutDialog.lblVersionF"));
} else if (version.equals("P")) {
lblVersion.setText(Messages.getString("dialog.AboutDialog.lblVersionP"));
} else if (version.equals("L")) {
lblVersion.setText(Messages.getString("dialog.AboutDialog.lblVersionL"));
}
lblVersion.setLayoutData(data);
lblVersion.setBackground(white);
Label lblVersion2 = new Label(cmpMain, SWT.None);
String version2 = System.getProperty("TSVersionDate");
lblVersion2.setText(MessageFormat.format(Messages.getString("dialog.AboutDialog.lblVersion2"),
version2.substring(0, version2.lastIndexOf(".")), version2.substring(version2.lastIndexOf(".") + 1)));
lblVersion2.setLayoutData(data);
lblVersion2.setBackground(white);
Composite cmpWeb = new Composite(cmpMain, SWT.None);
cmpWeb.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).extendedMargins(-5, 0, 0, 0).applyTo(cmpWeb);
cmpWeb.setBackground(white);
Label lblProduct = new Label(cmpWeb, SWT.None);
lblProduct.setText(Messages.getString("dialog.AboutDialog.lblProduct"));
lblProduct.setBackground(white);
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblProduct);
Link productLink = new Link(cmpWeb, SWT.NONE);
productLink.setText("<a>" + Messages.getString("dialog.AboutDialog.productLink") + "</a>");
productLink.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Program.launch(Messages.getString("dialog.AboutDialog.productLink"));
}
});
productLink.setBackground(white);
Label lblSupport = new Label(cmpWeb, SWT.None);
lblSupport.setText(Messages.getString("dialog.AboutDialog.lblSupport"));
lblSupport.setBackground(white);
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblSupport);
Link supportLink = new Link(cmpWeb, SWT.NONE);
supportLink.setText("<a>" + Messages.getString("dialog.AboutDialog.supportLink") + "</a>");
supportLink.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Program.launch(Messages.getString("dialog.AboutDialog.supportLink"));
}
});
supportLink.setBackground(white);
Label lblCopyRight = new Label(cmpMain, SWT.None);
lblCopyRight.setText(Messages.getString("dialog.AboutDialog.lblCopyRight"));
lblCopyRight.setLayoutData(data);
lblCopyRight.setBackground(white);
Composite cmpWarn = new Composite(tparent, SWT.None);
cmpWarn.setLayout(new GridLayout());
cmpWarn.setLayoutData(new GridData(GridData.FILL_BOTH));
Label lblWarn = new Label(cmpWarn, SWT.WRAP);
lblWarn.setLayoutData(new GridData(GridData.FILL_BOTH));
Point bodySize = parent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
GridData gd = (GridData) lblWarn.getLayoutData();
gd.widthHint = bodySize.x;
lblWarn.setText(Messages.getString("dialog.AboutDialog.lblWarn"));
return tparent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
}
@Override
public boolean close() {
if (image != null && !image.isDisposed()) {
image.dispose();
}
if (font != null && !font.isDisposed()) {
font.dispose();
}
return super.close();
}
}
| 6,253 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AboutHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/handler/AboutHandler.java | package net.heartsome.cat.ts.handler;
import net.heartsome.cat.ts.dialog.AboutDialog;
import net.heartsome.cat.ts.resource.Messages;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 关于...
* @author peason
* @version
* @since JDK1.6
*/
public class AboutHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell shell = HandlerUtil.getActiveShell(event);
String version = System.getProperty("TSEdition");
String version2 = System.getProperty("TSVersionDate");
if (version == null || version2 == null || version.equals("") || version2.equals("")) {
MessageDialog.openInformation(shell, Messages.getString("dialog.AboutDialog.msgTitle"),
Messages.getString("dialog.AboutDialog.msg"));
PlatformUI.getWorkbench().close();
} else {
AboutDialog dialog = new AboutDialog(shell);
dialog.open();
}
return null;
}
}
| 1,183 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
KeyAssistHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/handler/KeyAssistHandler.java | package net.heartsome.cat.ts.handler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.ts.ui.Constants;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.keys.BindingService;
import org.eclipse.ui.keys.IBindingService;
/**
* 帮助 -> 快捷键功能的 Handler
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings("restriction")
public class KeyAssistHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
final IWorkbench workbench = PlatformUI.getWorkbench();
IBindingService bindingService = (IBindingService) workbench.getService(IBindingService.class);
BindingService service = (BindingService) bindingService;
ArrayList<Binding> lstBinding = new ArrayList<Binding>(Arrays.asList(bindingService.getBindings()));
List<String> lstRemove = Constants.lstRemove;
Iterator<Binding> it = lstBinding.iterator();
while (it.hasNext()) {
Binding binding = it.next();
ParameterizedCommand pCommand = binding.getParameterizedCommand();
if (pCommand == null || lstRemove.contains(pCommand.getCommand().getId())) {
it.remove();
}
}
service.getKeyboard().openKeyAssistShell(lstBinding);
return null;
}
}
| 1,588 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenStatusBarHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/handler/OpenStatusBarHandler.java | package net.heartsome.cat.ts.handler;
import java.util.Map;
import net.heartsome.cat.ts.Activator;
import net.heartsome.cat.ts.ApplicationWorkbenchAdvisor;
import net.heartsome.cat.ts.ApplicationWorkbenchWindowAdvisor;
import net.heartsome.cat.ts.TsPreferencesConstant;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.menus.UIElement;
/**
* 主界面状态栏的显示与隐藏
* @author robert 2011-11-04
*/
public class OpenStatusBarHandler extends AbstractHandler implements IElementUpdater {
public Object execute(ExecutionEvent event) throws ExecutionException {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
boolean oldValue = preferenceStore.getBoolean(TsPreferencesConstant.TS_statusBar_status);
ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.WorkbenchWindowAdvisor;
configurer.setStatusVisible(!oldValue);
preferenceStore.setValue(TsPreferencesConstant.TS_statusBar_status, !oldValue);
ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
commandService.refreshElements(event.getCommand().getId(), null);
return null;
}
@SuppressWarnings("rawtypes")
public void updateElement(UIElement element, Map parameters) {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
boolean oldValue = preferenceStore.getBoolean(TsPreferencesConstant.TS_statusBar_status);
element.setIcon(oldValue ? Activator.getImageDescriptor("icons/enabled_co.png") : Activator
.getImageDescriptor("icons/disabled_co.png"));
}
}
| 1,923 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreferenceHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/handler/PreferenceHandler.java | package net.heartsome.cat.ts.handler;
import net.heartsome.cat.ts.ui.util.PreferenceUtil;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 首选项的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class PreferenceHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
if (window != null) {
PreferenceUtil.openPreferenceDialog(window, null);
}
return null;
}
}
| 722 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenToolBarHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/handler/OpenToolBarHandler.java | package net.heartsome.cat.ts.handler;
import java.util.Map;
import net.heartsome.cat.ts.Activator;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.menus.UIElement;
@SuppressWarnings("restriction")
public class OpenToolBarHandler extends AbstractHandler implements IElementUpdater{
public Object execute(ExecutionEvent event) throws ExecutionException {
final IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindowChecked(event);
if (activeWorkbenchWindow instanceof WorkbenchWindow) {
WorkbenchWindow window = (WorkbenchWindow) activeWorkbenchWindow;
window.toggleToolbarVisibility();
}
ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
commandService.refreshElements(event.getCommand().getId(), null);
return null;
}
@SuppressWarnings("rawtypes")
public void updateElement(final UIElement element, Map parameters) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
final IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWorkbenchWindow instanceof WorkbenchWindow) {
WorkbenchWindow window = (WorkbenchWindow) activeWorkbenchWindow;
boolean coolbarVisible = window.getCoolBarVisible();
element.setIcon(coolbarVisible ? Activator.getImageDescriptor("icons/enabled_co.png") : Activator
.getImageDescriptor("icons/disabled_co.png"));
}
}
});
}
}
| 1,913 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EditorAreaDropAdapter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/drop/EditorAreaDropAdapter.java | package net.heartsome.cat.ts.drop;
import java.util.Iterator;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An editor area drop adapter to handle transfer types <code>LocalSelectionTransfer</code> and
* <code>FileTransfer</code>.
* @author weachy
* @version
* @since JDK1.5
* @see org.eclipse.ui.internal.ide.EditorAreaDropAdapter
*/
@SuppressWarnings("restriction")
public class EditorAreaDropAdapter extends DropTargetAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(EditorAreaDropAdapter.class);
private IWorkbenchWindow window;
public EditorAreaDropAdapter(IWorkbenchWindow window) {
this.window = window;
}
public void dragEnter(DropTargetEvent event) {
// always indicate a copy
event.detail = DND.DROP_COPY;
}
public void dragOperationChanged(DropTargetEvent event) {
// always indicate a copy
event.detail = DND.DROP_COPY;
}
public void drop(final DropTargetEvent event) {
Display d = window.getShell().getDisplay();
final IWorkbenchPage page = window.getActivePage();
if (page != null) {
d.asyncExec(new Runnable() {
public void run() {
asyncDrop(event, page);
}
});
}
}
private void asyncDrop(DropTargetEvent event, IWorkbenchPage page) {
if (LocalSelectionTransfer.getTransfer().isSupportedType(event.currentDataType)) { // 处理“导航视图”拖拽过来的文件
if (!(event.data instanceof StructuredSelection)) {
return;
}
StructuredSelection selection = (StructuredSelection) event.data;
for (Iterator<?> iter = selection.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof IFile) {
IFile file = (IFile) o;
// 仅打开从导航视图中拖过来的 XLIFF 文件
if (CommonFunction.validXlfExtensionByFileName(file.getName())) {
try {
IDE.openEditor(page, file, true);
} catch (PartInitException e) {
LOGGER.error(" ", e);
// silently ignore problems opening the editor
}
}
}
}
} else if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { // 处理从工作空间以外拖拽过来的文件
// 从工作空间以外拖过来的文件不做处理
// String[] filePaths = (String[]) event.data;
// if (filePaths != null && filePaths.length != 0) {
// boolean isXliffFile = true; // 是 XLIFF 文件
// for (String filePath : filePaths) {
// if (!CommonFunction.validXlfExtensionByFileName(filePath)) {
// isXliffFile = false;
// break;
// }
// }
// if (isXliffFile) { // 全部都是 XLIFF 文件
// for (int i = 0; i < filePaths.length; i++) {
// IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(filePaths[i]));
// try {
// IDE.openEditorOnFileStore(page, fileStore);
// } catch (PartInitException e) {
// LOGGER.error("", e);
// // silently ignore problems opening the editor
// }
// }
// } else { // 否则,就弹出创建项目的对话框,要求创建项目。
// NewProjectAction action = new NewProjectAction(window);
// action.run();
// // TODO 如果成功创建项目,则把拖进来的文件自动拷贝到项目中来。
// // 未解决问题:无法获取是否已经成功创建(可能用户点击了“取消”)。
// }
// }
}
}
}
| 3,897 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProgressIndicatorManager.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts/src/net/heartsome/cat/ts/util/ProgressIndicatorManager.java | package net.heartsome.cat.ts.util;
import net.heartsome.cat.ts.Activator;
import net.heartsome.cat.ts.ApplicationWorkbenchAdvisor;
import net.heartsome.cat.ts.ApplicationWorkbenchWindowAdvisor;
import net.heartsome.cat.ts.TsPreferencesConstant;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
/**
* 状态栏最右侧的后台进度条管理(即控制其显示或隐藏),主要是针对 BUG 2652
* @author robert 2012-11-07
*/
public class ProgressIndicatorManager {
/** 能够隐藏后台进度条的标识,如果大于等于1,是不能隐藏的,标志还有其他程序在使用 */
private static int statusTag = 0;
/**
* 当进度条要显示出来时,显示状态栏右下方的后台进度条。
*/
public static void displayProgressIndicator(){
Display.getDefault().asyncExec(new Runnable() {
public void run() {
statusTag ++;
// 首先检查状态栏是否处于隐藏状态,如果是隐藏的,直接退出
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
boolean isVisible = preferenceStore.getBoolean(TsPreferencesConstant.TS_statusBar_status);
if (!isVisible) {
return;
}
ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.WorkbenchWindowAdvisor;
configurer.setProgressIndicatorVisible(true);
}
});
}
/**
* 进度条关闭后,隐藏状态栏右下方的后台进度条
*/
public static void hideProgressIndicator(){
Display.getDefault().asyncExec(new Runnable() {
public void run() {
statusTag --;
// 如果 状态标志 大于0,则不允隐藏后台进度条
if (statusTag > 0) {
return;
}
// 首先检查状态栏是否处于隐藏状态,如果是隐藏的,直接退出
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
boolean isVisible = preferenceStore.getBoolean(TsPreferencesConstant.TS_statusBar_status);
if (!isVisible) {
return;
}
ApplicationWorkbenchWindowAdvisor configurer = ApplicationWorkbenchAdvisor.WorkbenchWindowAdvisor;
configurer.setProgressIndicatorVisible(false);
}
});
}
}
| 2,253 | 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/src/net/heartsome/cat/ts/resource/Messages.java | package net.heartsome.cat.ts.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.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 542 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
QuickTranslationImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.quicktranslation/src/net/heartsome/cat/ts/quicktranslation/QuickTranslationImpl.java | /**
* QuickTranslationImpl.java
*
* Version information :
*
* Date:2012-6-19
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.quicktranslation;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.common.tm.MatchQuality;
import net.heartsome.cat.ts.core.bean.AltTransBean;
import net.heartsome.cat.ts.core.bean.Constants;
import net.heartsome.cat.ts.core.bean.TransUnitBean;
import net.heartsome.cat.ts.tb.match.TbMatcher;
import net.heartsome.cat.ts.tm.complexMatch.IComplexMatch;
import org.eclipse.core.resources.IProject;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class QuickTranslationImpl implements IComplexMatch {
private TbMatcher tbMatcher;
/**
*
*/
public QuickTranslationImpl() {
tbMatcher = new TbMatcher();
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tm.complexMatch.AbstractComplexMatch#executeTranslation()
*/
public Vector<AltTransBean> executeTranslation(TransUnitBean transUnitBean, IProject currentProject) {
Vector<AltTransBean> result = new Vector<AltTransBean>();
// 100%以上的记忆库匹配不做快译
if (transUnitBean == null) {
return result;
}
Vector<AltTransBean> tmalt = transUnitBean.getMatchesByToolId(Constants.TM_TOOLID);
if (tmalt.size() < 1) {
return result;
}
AltTransBean tmMatches = tmalt.get(0);
if (tmMatches == null) {
return result;
}
String tmQuality = tmMatches.getMatchProps().get("match-quality");
if (tmQuality.endsWith("%")) {
tmQuality = tmQuality.substring(0, tmQuality.length() - 1);
}
int tmQualityInt = Integer.parseInt(tmQuality);
if (tmQualityInt >= 100) {
return result;
}
String srcLang = tmMatches.getSrcLang();
String tgtLang = tmMatches.getTgtLang();
if (srcLang == null || srcLang.equals("")) {
return result;
}
if (tgtLang == null || tgtLang.equals("")) {
return result;
}
String tmSrcText = tmMatches.getSrcText();
if (tmSrcText == null || tmSrcText.equals("")) {
return result;
}
String tmTgtText = tmMatches.getTgtText();
if (tmTgtText == null || tmTgtText.equals("")) {
return result;
}
String tuSrcText = transUnitBean.getSrcText();
if (tuSrcText == null || tuSrcText.equals("")) {
return result;
}
tbMatcher.setCurrentProject(currentProject);
// 获取翻译单源文中的术语
Vector<Hashtable<String, String>> tuTerms = findTerms(tuSrcText, srcLang, tgtLang);
if (tuTerms.size() == 0) {
return result;
}
// 获取记忆库匹配中的术语
Vector<Hashtable<String, String>> tmTerms = findTerms(tmSrcText, srcLang, tgtLang);
if (tmTerms.size() == 0) {
return result;
}
int tuTermSize = tuTerms.size();
int tmTermSize = tmTerms.size();
if (tuTermSize > tmTermSize) {
int j = 0;
while (j < tuTermSize) {
Hashtable<String, String> tempTuTerm = tuTerms.get(j);
String tmpTuSrcWord = tempTuTerm.get(CON_SRCWORD);
for (Hashtable<String, String> tempTmTerm : tmTerms) {
if (tempTmTerm.get(CON_SRCWORD).equals(tmpTuSrcWord)) {
tuTerms.remove(j);
tmTerms.remove(tempTmTerm);
break;
}
}
tuTermSize = tuTerms.size();
j++;
}
} else {
int j = 0;
while (j < tmTermSize) {
Hashtable<String, String> tempTmTerm = tmTerms.get(j);
String tmpTmSrcWord = tempTmTerm.get(CON_SRCWORD);
for (Hashtable<String, String> tempTuTerm : tuTerms) {
if (tempTuTerm.get(CON_SRCWORD).equals(tmpTmSrcWord)) {
tmTerms.remove(j);
tuTerms.remove(tempTuTerm);
break;
}
}
tmTermSize = tmTerms.size();
j++;
}
}
tuTermSize = tuTerms.size();
tmTermSize = tmTerms.size();
if (tuTermSize == 0 || tmTermSize == 0) {
return result;
}
int replaceSize = tuTermSize < tmTermSize ? tuTermSize : tmTermSize;
for (int i = 0; i < replaceSize; i++) {
Hashtable<String, String> tmTerm = tmTerms.get(i);
String tmTermSrc = tmTerm.get(CON_SRCWORD);
String tmTermTgt = tmTerm.get(CON_TGTWORD);
Hashtable<String, String> tuTerm = tuTerms.get(i);
String tuTermSrc = tuTerm.get(CON_SRCWORD);
String tuTermTgt = tuTerm.get(CON_TGTWORD);
tmSrcText = tmSrcText.replace(tmTermSrc, tuTermSrc);
tmTgtText = tmTgtText.replace(tmTermTgt, tuTermTgt);
}
int quality = MatchQuality.similarity(tuSrcText, tmSrcText);
AltTransBean bean = new AltTransBean(tmSrcText, tmTgtText, srcLang, tgtLang, getMathcerOrigin(), getToolId());
bean.getMatchProps().put("match-quality", quality + "");
bean.setSrcContent(tmSrcText);
bean.setTgtContent(tmTgtText);
bean.getMatchProps().put("hs:matchType", getMatcherType());
result.add(bean);
return result;
}
private Vector<Hashtable<String, String>> findTerms(String srcText, String srcLang, String tgtLang) {
Vector<Hashtable<String, String>> terms = new Vector<Hashtable<String, String>>();
terms = tbMatcher.serachTransUnitTerms(srcText, srcLang, tgtLang, true);
// 根据术语的长度升序排列
Collections.sort(terms, new TermComparatorByLength());
// 处理查询结果--剔除重复(取最长的术语组),同时按术语在句子中出现的先后进行排序顺序
for (int i = 0; i < terms.size(); i++) {
Hashtable<String, String> termA = terms.get(i);
String srcWordA = termA.get(CON_SRCWORD);
for (int j = i + 1; j < terms.size(); j++) {
Hashtable<String, String> termB = terms.get(j);
String srcWordB = termB.get(CON_SRCWORD);
if (srcWordA.toLowerCase().indexOf(srcWordB.toLowerCase()) != -1) {
terms.remove(j);
j--;
}
}
}
// 根据术语在srcText中出现的顺序排序
Collections.sort(terms, new TermComparatorByIndex(srcText));
return terms;
}
/**
* 根据术语的长度进行升序排序
*/
final class TermComparatorByLength implements Comparator<Hashtable<String, String>> {
public TermComparatorByLength() {
}
public int compare(Hashtable<String, String> a, Hashtable<String, String> b) {
Integer a1 = a.get(CON_SRCWORD).length();
Integer b1 = b.get(CON_SRCWORD).length();
return b1 - a1;
}
}
/**
* 根据术语在当前文本段中的出现的顺序对术语列表进行排序
*/
final class TermComparatorByIndex implements Comparator<Hashtable<String, String>> {
private String srcText;
public TermComparatorByIndex(String srcText) {
this.srcText = srcText;
}
public int compare(Hashtable<String, String> a, Hashtable<String, String> b) {
Integer a1 = srcText.indexOf(a.get(CON_SRCWORD));
Integer b1 = srcText.indexOf(b.get(CON_SRCWORD));
return a1 - b1;
}
}
/** 快速翻译中使用的常量 */
public static final String CON_SRCWORD = "srcWord";
public static final String CON_TGTWORD = "tgtWord";
public String getToolId() {
return "Quick Translation";
}
public String getMatcherType() {
return "QT";
}
public String getMathcerOrigin() {
return "Heartsome Quick Translation";
}
}
| 7,509 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExecuteQuickTranslation.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.quicktranslation/src/net/heartsome/cat/ts/quicktranslation/handler/ExecuteQuickTranslation.java | /**
* ExecuteQuickTranslation.java
*
* Version information :
*
* Date:2012-6-20
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.quicktranslation.handler;
import net.heartsome.cat.ts.quicktranslation.QuickTranslationImpl;
import net.heartsome.cat.ts.tm.complexMatch.IComplexMatch;
import net.heartsome.cat.ts.ui.bean.TranslateParameter;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.ui.translation.view.MatchViewPart;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 针对选中的文本段执行快速翻译算法
* @author jason
* @version
* @since JDK1.6
*/
public class ExecuteQuickTranslation extends AbstractHandler {
/** (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
if(TranslateParameter.getInstance().isAutoQuickTrans()){
return null;
}
final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
final IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (!(editor instanceof IXliffEditor)) {
return null;
}
final IXliffEditor xliffEditor = (IXliffEditor) editor;
final int[] selectedRowIndexs = xliffEditor.getSelectedRows();
if(selectedRowIndexs.length == 0){
return null;
}
// TransUnitBean transUnitBean = xliffEditor.getRowTransUnitBean(selectedRowIndexs[selectedRowIndexs.length - 1]);
IComplexMatch matcher = new QuickTranslationImpl();
// FileEditorInput input = (FileEditorInput) editor.getEditorInput();
// IProject project = input.getFile().getProject();
// List<AltTransBean> newAltTrans = matcher.executeTranslation(transUnitBean, project);
// if(newAltTrans.size() == 0){
// return null;
// }
IViewPart viewPart = window.getActivePage().findView(MatchViewPart.ID);
if(viewPart != null && viewPart instanceof MatchViewPart){
MatchViewPart matchView = (MatchViewPart) viewPart;
matchView.manualExecComplexTranslation(selectedRowIndexs[0],xliffEditor, matcher);
// matchView.replaceMatchs(newAltTrans);
// matchView.refreshView(xliffEditor, selectedRowIndexs[selectedRowIndexs.length - 1]);
}
// IRunnableWithProgress runnable = new IRunnableWithProgress() {
// public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
// monitor.beginTask(Messages.getString("handler.ExecuteQuickTranslation.task1"), selectedRowIndexs.length);
// IComplexMatch matcher = new QuickTranslationImpl();
//
// FileEditorInput input = (FileEditorInput) editor.getEditorInput();
// IProject project = input.getFile().getProject();
//
// List<String> oldToolIds = new ArrayList<String>();
// oldToolIds.add(matcher.getToolId());
// Map<Integer, List<AltTransBean>> newAltTransMap = new HashMap<Integer, List<AltTransBean>>();
// Map<Integer, List<String>> oldAltTransToolIdMap = new HashMap<Integer, List<String>>();
// for(int selectedRowindex : selectedRowIndexs){
// TransUnitBean transUnitBean = xliffEditor.getRowTransUnitBean(selectedRowindex);
// List<AltTransBean> newAltTrans = matcher.executeTranslation(transUnitBean, project);
// if(newAltTrans.size() == 0){
// continue;
// }
// newAltTransMap.put(selectedRowindex, newAltTrans);
// oldAltTransToolIdMap.put(selectedRowindex, oldToolIds);
// monitor.worked(1);
// }
// if(newAltTransMap.size() != 0){
// xliffEditor.getXLFHandler().batchUpdateAltTrans(selectedRowIndexs, newAltTransMap, oldAltTransToolIdMap);
//
// window.getShell().getDisplay().asyncExec(new Runnable() {
// @Override
// public void run() {
// IViewPart viewPart = window.getActivePage().findView(MatchViewPart.ID);
// if(viewPart != null && viewPart instanceof MatchViewPart && selectedRowIndexs.length != 0){
// MatchViewPart matchView = (MatchViewPart) viewPart;
// matchView.refreshView(xliffEditor, selectedRowIndexs[selectedRowIndexs.length - 1]);
// }
// }
// });
// }
// monitor.done();
// }
// };
// try {
// new ProgressMonitorDialog(window.getShell()).run(true, false, runnable);
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
return null;
}
}
| 5,180 | 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.quicktranslation/src/net/heartsome/cat/ts/quicktranslation/resource/Messages.java | package net.heartsome.cat.ts.quicktranslation.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.quicktranslation.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 576 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/Activator.java | package net.heartsome.cat.common.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 {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.common.ui";
// 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,371 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HsImageLabel.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/HsImageLabel.java | /**
* ImageText.java
*
* Version information :
*
* Date:2012-6-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class HsImageLabel {
private Control control;
private Composite body;
private Label imageLabel;
private Label descriptionLabel;
private ImageDescriptor imageDescription;
private String description;
private Image image;
private Point size;
public HsImageLabel(String description, ImageDescriptor imageDescription) {
this.description = description;
this.imageDescription = imageDescription;
if (imageDescription != null) {
image = imageDescription.createImage();
}
}
public Composite createControl(Composite parent) {
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
Composite content = new Composite(parent, SWT.NONE);
GridLayout contentLayout = new GridLayout(2, false);
contentLayout.marginWidth = 0;
contentLayout.marginHeight = 0;
content.setLayout(contentLayout);
content.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
this.control = content;
imageLabel = createImageLabel(content);
if (imageLabel != null) {
imageLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
}
Composite composite = new Composite(content, SWT.NONE);
GridLayout comLayout = new GridLayout();
comLayout.marginWidth = 0;
comLayout.marginHeight = 0;
composite.setLayout(comLayout);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
descriptionLabel = createDescriptionLabel(composite);
if (descriptionLabel != null) {
descriptionLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
body = new Composite(composite, SWT.NONE);
GridLayout gd = new GridLayout();
gd.marginRight = 0;
gd.marginHeight = 0;
body.setLayout(gd);
if (body != null) {
body.setLayoutData(new GridData(GridData.FILL_BOTH));
}
return body;
}
public Point computeSize() {
return computeSize(130);
}
public Point computeSize(int width) {
if (size != null) {
return size;
}
Control control = getControl();
if (control != null) {
size = doComputeSize(width);
return size;
}
return new Point(0, 0);
}
protected Point doComputeSize(int width) {
Point bodySize = getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (descriptionLabel != null) {
GridData gd = (GridData) descriptionLabel.getLayoutData();
gd.widthHint = bodySize.x + width;
descriptionLabel.setText(description);
}
return bodySize;
}
protected Label createDescriptionLabel(Composite parent) {
Label result = null;
String description = getDescription();
if (description != null) {
result = new Label(parent, SWT.WRAP);
result.setFont(parent.getFont());
// result.setText(description);
}
return result;
}
protected Label createImageLabel(Composite parent) {
Label result = null;
if (image != null) {
result = new Label(parent, SWT.NONE);
result.setFont(parent.getFont());
result.setImage(image);
}
return result;
}
public void dispose() {
// deallocate SWT resources
if (image != null && !image.isDisposed()) {
image.dispose();
image = null;
}
}
public Control getControl() {
return control;
}
public ImageDescriptor getImageDescription() {
return imageDescription;
}
public String getDescription() {
return description;
}
}
| 4,450 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HSFontSettingComposite.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/HSFontSettingComposite.java | /**
* HSFontSettingComposite.java
*
* Version information :
*
* Date:2013-4-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.heartsome.cat.common.ui.resource.Messages;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
/**
* 字体设置组件
* @author Jason
* @version
* @since JDK1.6
*/
public class HSFontSettingComposite extends Composite {
// 界面组件
ComboViewer fontNameComboViewer;
ComboViewer fontSizeComboViewer;
Label previewFontText;
Font previewFont;
String title;
/**
* @param parent
* @param style
* @param title
* 此字体设计说明文字,如果为null,则不创建。
*/
public HSFontSettingComposite(Composite parent, int style, String title) {
super(parent, style);
GridLayout layout = new GridLayout(2, false);
layout.marginTop = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginWidth = 1;
this.title = title;
setLayout(layout);
createContent();
}
public FontData[] getFontSetingFont() {
return previewFont.getFontData();
}
public void initFont(String name, int size){
fontNameComboViewer.setSelection(new StructuredSelection(name));
fontSizeComboViewer.setSelection(new StructuredSelection(size));
FontData fd = new FontData();
fd.setName(name);
fd.setHeight(size);
if (previewFont != null && !previewFont.isDisposed()) {
previewFont.dispose();
}
previewFont = new Font(Display.getDefault(), fd);
previewFontText.setFont(previewFont);
}
@Override
public void dispose() {
if (previewFont != null && !previewFont.isDisposed()) {
previewFont.dispose();
}
super.dispose();
}
public void createContent() {
if (this.title != null && title.length() != 0) {
Label titleLabel = new Label(this, SWT.NONE);
titleLabel.setText(title);
GridData titleLabelGridData = new GridData();
titleLabelGridData.horizontalSpan = 2;
titleLabelGridData.horizontalAlignment = GridData.CENTER;
titleLabel.setLayoutData(titleLabelGridData);
}
Label lblFontName = new Label(this, SWT.NONE);
lblFontName.setText(Messages.getString("HSFontSettingComposite.fontNameLabel"));
fontNameComboViewer = new ComboViewer(this);
fontNameComboViewer.setContentProvider(new ArrayContentProvider());
Combo fontNameCombo = fontNameComboViewer.getCombo();
GridData fnGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
fontNameCombo.setLayoutData(fnGd);
fontNameComboViewer.setInput(getSystemFonts());
Label lblFontSize = new Label(this, SWT.NONE);
lblFontSize.setText(Messages.getString("HSFontSettingComposite.fontSizeLabel"));
fontSizeComboViewer = new ComboViewer(this);
fontSizeComboViewer.setContentProvider(new ArrayContentProvider());
Combo fontSize = fontSizeComboViewer.getCombo();
fontSize.setLayoutData(fnGd);
fontSizeComboViewer.setInput(new Integer[] { 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, });
Label lblFontPreview = new Label(this, SWT.None);
lblFontPreview.setText(Messages.getString("HSFontSettingComposite.fontPreViewLabel"));
previewFontText = new Label(this, SWT.READ_ONLY | SWT.BORDER);
previewFontText.setText("abcdefg ABCDEFG");
GridData previewFontTextGridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
previewFontTextGridData.heightHint = 50;
previewFontText.setLayoutData(previewFontTextGridData);
fontNameComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
String strFontName = fontNameComboViewer.getCombo().getText();
String intFontSize = fontSizeComboViewer.getCombo().getText();
if(strFontName == null || intFontSize == null || strFontName.length() == 0 || intFontSize.length() == 0){
return;
}
FontData fd = JFaceResources.getDefaultFont().getFontData()[0];
fd.setName(strFontName);
fd.setHeight(Integer.parseInt(intFontSize));
if (previewFont != null && !previewFont.isDisposed()) {
previewFont.dispose();
}
previewFont = new Font(Display.getDefault(), fd);
previewFontText.setFont(previewFont);
}
});
fontSizeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
String strFontName = fontNameComboViewer.getCombo().getText();
String intFontSize = fontSizeComboViewer.getCombo().getText();
if(strFontName == null || intFontSize == null || strFontName.length() == 0 || intFontSize.length() == 0){
return;
}
FontData fd = JFaceResources.getDefaultFont().getFontData()[0];
fd.setName(strFontName);
fd.setHeight(Integer.parseInt(intFontSize));
if (previewFont != null && !previewFont.isDisposed()) {
previewFont.dispose();
}
previewFont = new Font(Display.getDefault(), fd);
previewFontText.setFont(previewFont);
}
});
}
private String[] getSystemFonts() {
Set<String> s = new HashSet<String>();
// Add names of all bitmap fonts.
FontData[] fds = Display.getDefault().getFontList(null, false);
for (int i = 0; i < fds.length; ++i) {
s.add(fds[i].getName());
}
// Add names of all scalable fonts.
fds = Display.getDefault().getFontList(null, true);
for (int i = 0; i < fds.length; ++i) {
s.add(fds[i].getName());
}
// Sort the result and print it.
String[] fontNames = new String[s.size()];
s.toArray(fontNames);
Arrays.sort(fontNames); // sort
return fontNames;
}
}
| 6,926 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HSDropDownButton.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/HSDropDownButton.java | /**
* HSDropDownButton.java
*
* Version information :
*
* Date:2013-4-22
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class HSDropDownButton extends Button {
private final static int DEFAULT_SPACES = 15;
private String EMPTY_SPACE = getSpaceByWidth(DEFAULT_SPACES);
private final static Color COLOR__BLACK = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
private Menu menu;
public HSDropDownButton(Composite parent, int style) {
super(parent, SWT.PUSH);
setText("");
super.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// draw the arrow
Rectangle rect = getBounds();
Color oldForeground = e.gc.getForeground();
Color oldBackground = e.gc.getBackground();
int dx = -e.gc.getClipping().x;
int dy = -e.gc.getClipping().y;
e.gc.setForeground(COLOR__BLACK);
e.gc.setBackground(COLOR__BLACK);
e.gc.fillPolygon(new int[] { e.x + rect.width - 15 + dx, e.y + rect.height / 2 - 1 + dy,
e.x + rect.width - 8 + dx, e.y + rect.height / 2 - 1 + dy, e.x + rect.width - 12 + dx,
e.y + rect.height / 2 + 3 + dy });
e.gc.setForeground(oldForeground);
e.gc.setBackground(oldBackground);
}
});
super.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
Button button = (Button) event.widget;
Rectangle rect = button.getBounds();
Point p = button.toDisplay(rect.x, rect.y + rect.height);
getMenu().setLocation(p.x - rect.x, p.y - rect.y);
getMenu().setVisible(true);
}
});
menu = new Menu(getShell(), SWT.POP_UP);
}
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
@Override
protected void checkSubclass() {
}
@Override
public void setText(String string) {
if (string != null) {
super.setText(string + EMPTY_SPACE);
}
}
@Override
public String getText() {
return super.getText().trim();
}
public String getSpaceByWidth(int width) {
GC gc = new GC(Display.getDefault());
int spaceWidth = gc.getAdvanceWidth(' ');
gc.dispose();
int spacecount = width / spaceWidth;
StringBuilder b = new StringBuilder();
while (spacecount-- > 0) {
b.append(" ");
}
return b.toString();
}
}
| 3,460 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TSTitleAreaDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/wizard/TSTitleAreaDialog.java | /*******************************************************************************
* Copyright (c) 2000, 2010 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
* Konstantin Scheglov <[email protected] > - Fix for bug 41172
* [Dialogs] Bug with Image in TitleAreaDialog
* Sebastian Davids <[email protected]> - Fix for bug 82064
* [Dialogs] TitleAreaDialog#setTitleImage cannot be called before open()
*******************************************************************************/
package net.heartsome.cat.common.ui.wizard;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* A dialog that has a title area for displaying a title and an image as well as
* a common area for displaying a description, a message, or an error message.
* (此类与 org.eclipse.jface.dialogs.TitleAreaDialog 的区别在于向导的描述部分采用的 Label,TitleAreaDialog 采用的 Text)
* <p>
* This dialog class may be subclassed.
*/
public class TSTitleAreaDialog extends TrayDialog {
/**
* Image registry key for error message image.
*/
public static final String DLG_IMG_TITLE_ERROR = DLG_IMG_MESSAGE_ERROR;
/**
* Image registry key for banner image (value
* <code>"dialog_title_banner_image"</code>).
*/
public static final String DLG_IMG_TITLE_BANNER = "dialog_title_banner_image";//$NON-NLS-1$
/**
* Message type constant used to display an info icon with the message.
*
* @since 2.0
* @deprecated
*/
public final static String INFO_MESSAGE = "INFO_MESSAGE"; //$NON-NLS-1$
/**
* Message type constant used to display a warning icon with the message.
*
* @since 2.0
* @deprecated
*/
public final static String WARNING_MESSAGE = "WARNING_MESSAGE"; //$NON-NLS-1$
// Space between an image and a label
private static final int H_GAP_IMAGE = 5;
// Minimum dialog width (in dialog units)
private static final int MIN_DIALOG_WIDTH = 350;
// Minimum dialog height (in dialog units)
private static final int MIN_DIALOG_HEIGHT = 150;
private Label titleLabel;
private Label titleImageLabel;
private Label bottomFillerLabel;
private Label leftFillerLabel;
private RGB titleAreaRGB;
Color titleAreaColor;
private String message = ""; //$NON-NLS-1$
private String errorMessage;
private Label messageLabel;
private Composite workArea;
private Label messageImageLabel;
private Image messageImage;
private boolean showingError = false;
private boolean titleImageLargest = true;
private int messageLabelHeight;
private Image titleAreaImage;
private int xTrim;
private int yTrim;
/**
* Instantiate a new title area dialog.
*
* @param parentShell
* the parent SWT shell
*/
public TSTitleAreaDialog(Shell parentShell) {
super(parentShell);
}
/*
* @see Dialog.createContents(Composite)
*/
protected Control createContents(Composite parent) {
// create the overall composite
Composite contents = new Composite(parent, SWT.NONE);
contents.setLayoutData(new GridData(GridData.FILL_BOTH));
// initialize the dialog units
initializeDialogUnits(contents);
FormLayout layout = new FormLayout();
contents.setLayout(layout);
// Now create a work area for the rest of the dialog
workArea = new Composite(contents, SWT.NONE);
GridLayout childLayout = new GridLayout();
childLayout.marginHeight = 0;
childLayout.marginWidth = 0;
childLayout.verticalSpacing = 0;
workArea.setLayout(childLayout);
Control top = createTitleArea(contents);
resetWorkAreaAttachments(top);
workArea.setFont(JFaceResources.getDialogFont());
// initialize the dialog units
initializeDialogUnits(workArea);
// create the dialog area and button bar
dialogArea = createDialogArea(workArea);
buttonBar = createButtonBar(workArea);
// computing trim for later
Point rect = messageLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
xTrim = rect.x - 100;
yTrim = rect.y - 100;
// need to react to new size of title area
getShell().addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
layoutForNewMessage(true);
}
});
return contents;
}
/**
* Creates and returns the contents of the upper part of this dialog (above
* the button bar).
* <p>
* The <code>Dialog</code> implementation of this framework method creates
* and returns a new <code>Composite</code> with no margins and spacing.
* Subclasses should override.
* </p>
*
* @param parent
* The parent composite to contain the dialog area
* @return the dialog area control
*/
protected Control createDialogArea(Composite parent) {
// create the top level composite for the dialog area
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setFont(parent.getFont());
// Build the separator line
Label titleBarSeparator = new Label(composite, SWT.HORIZONTAL
| SWT.SEPARATOR);
titleBarSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return composite;
}
/**
* Creates the dialog's title area.
*
* @param parent
* the SWT parent for the title area widgets
* @return Control with the highest x axis value.
*/
private Control createTitleArea(Composite parent) {
// add a dispose listener
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (titleAreaColor != null) {
titleAreaColor.dispose();
}
}
});
// Determine the background color of the title bar
Display display = parent.getDisplay();
Color background;
Color foreground;
if (titleAreaRGB != null) {
titleAreaColor = new Color(display, titleAreaRGB);
background = titleAreaColor;
foreground = null;
} else {
background = JFaceColors.getBannerBackground(display);
foreground = JFaceColors.getBannerForeground(display);
}
parent.setBackground(background);
int verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
int horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
// Dialog image @ right
titleImageLabel = new Label(parent, SWT.CENTER);
titleImageLabel.setBackground(background);
if (titleAreaImage == null)
titleImageLabel.setImage(JFaceResources
.getImage(DLG_IMG_TITLE_BANNER));
else
titleImageLabel.setImage(titleAreaImage);
FormData imageData = new FormData();
imageData.top = new FormAttachment(0, 0);
// Note: do not use horizontalSpacing on the right as that would be a
// regression from
// the R2.x style where there was no margin on the right and images are
// flush to the right
// hand side. see reopened comments in 41172
imageData.right = new FormAttachment(100, 0); // horizontalSpacing
titleImageLabel.setLayoutData(imageData);
// Title label @ top, left
titleLabel = new Label(parent, SWT.LEFT);
JFaceColors.setColors(titleLabel, foreground, background);
titleLabel.setFont(JFaceResources.getBannerFont());
titleLabel.setText(" ");//$NON-NLS-1$
FormData titleData = new FormData();
titleData.top = new FormAttachment(0, verticalSpacing);
titleData.right = new FormAttachment(titleImageLabel);
titleData.left = new FormAttachment(0, horizontalSpacing);
titleLabel.setLayoutData(titleData);
// Message image @ bottom, left
messageImageLabel = new Label(parent, SWT.CENTER);
messageImageLabel.setBackground(background);
// Message label @ bottom, center
messageLabel = new Label(parent, SWT.WRAP | SWT.READ_ONLY);
JFaceColors.setColors(messageLabel, foreground, background);
messageLabel.setText(" \n "); // two lines//$NON-NLS-1$
messageLabel.setFont(JFaceResources.getDialogFont());
messageLabel.setBackground(JFaceColors.getBannerBackground(Display.getDefault()));
messageLabelHeight = messageLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
// Filler labels
leftFillerLabel = new Label(parent, SWT.CENTER);
leftFillerLabel.setBackground(background);
bottomFillerLabel = new Label(parent, SWT.CENTER);
bottomFillerLabel.setBackground(background);
setLayoutsForNormalMessage(verticalSpacing, horizontalSpacing);
determineTitleImageLargest();
if (titleImageLargest)
return titleImageLabel;
return messageLabel;
}
/**
* Determine if the title image is larger than the title message and message
* area. This is used for layout decisions.
*/
private void determineTitleImageLargest() {
int titleY = titleImageLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
int verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
int labelY = titleLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
labelY += verticalSpacing;
labelY += messageLabelHeight;
labelY += verticalSpacing;
titleImageLargest = titleY > labelY;
}
/**
* Set the layout values for the messageLabel, messageImageLabel and
* fillerLabel for the case where there is a normal message.
*
* @param verticalSpacing
* int The spacing between widgets on the vertical axis.
* @param horizontalSpacing
* int The spacing between widgets on the horizontal axis.
*/
private void setLayoutsForNormalMessage(int verticalSpacing,
int horizontalSpacing) {
FormData messageImageData = new FormData();
messageImageData.top = new FormAttachment(titleLabel, verticalSpacing);
messageImageData.left = new FormAttachment(0, H_GAP_IMAGE);
messageImageLabel.setLayoutData(messageImageData);
FormData messageLabelData = new FormData();
messageLabelData.top = new FormAttachment(titleLabel, verticalSpacing);
messageLabelData.right = new FormAttachment(titleImageLabel);
messageLabelData.left = new FormAttachment(messageImageLabel,
horizontalSpacing);
messageLabelData.height = messageLabelHeight;
if (titleImageLargest)
messageLabelData.bottom = new FormAttachment(titleImageLabel, 0,
SWT.BOTTOM);
messageLabel.setLayoutData(messageLabelData);
FormData fillerData = new FormData();
fillerData.left = new FormAttachment(0, horizontalSpacing);
fillerData.top = new FormAttachment(messageImageLabel, 0);
fillerData.bottom = new FormAttachment(messageLabel, 0, SWT.BOTTOM);
bottomFillerLabel.setLayoutData(fillerData);
FormData data = new FormData();
data.top = new FormAttachment(messageImageLabel, 0, SWT.TOP);
data.left = new FormAttachment(0, 0);
data.bottom = new FormAttachment(messageImageLabel, 0, SWT.BOTTOM);
data.right = new FormAttachment(messageImageLabel, 0);
leftFillerLabel.setLayoutData(data);
}
/**
* The <code>TitleAreaDialog</code> implementation of this
* <code>Window</code> methods returns an initial size which is at least
* some reasonable minimum.
*
* @return the initial size of the dialog
*/
protected Point getInitialSize() {
Point shellSize = super.getInitialSize();
return new Point(Math.max(
convertHorizontalDLUsToPixels(MIN_DIALOG_WIDTH), shellSize.x),
Math.max(convertVerticalDLUsToPixels(MIN_DIALOG_HEIGHT),
shellSize.y));
}
/**
* Retained for backward compatibility.
*
* Returns the title area composite. There is no composite in this
* implementation so the shell is returned.
*
* @return Composite
* @deprecated
*/
protected Composite getTitleArea() {
return getShell();
}
/**
* Returns the title image label.
*
* @return the title image label
*/
protected Label getTitleImageLabel() {
return titleImageLabel;
}
/**
* Display the given error message. The currently displayed message is saved
* and will be redisplayed when the error message is set to
* <code>null</code>.
*
* @param newErrorMessage
* the newErrorMessage to display or <code>null</code>
*/
public void setErrorMessage(String newErrorMessage) {
// Any change?
if (errorMessage == null ? newErrorMessage == null : errorMessage
.equals(newErrorMessage))
return;
errorMessage = newErrorMessage;
// Clear or set error message.
if (errorMessage == null) {
if (showingError) {
// we were previously showing an error
showingError = false;
}
// show the message
// avoid calling setMessage in case it is overridden to call
// setErrorMessage,
// which would result in a recursive infinite loop
if (message == null) // this should probably never happen since
// setMessage does this conversion....
message = ""; //$NON-NLS-1$
updateMessage(message);
messageImageLabel.setImage(messageImage);
setImageLabelVisible(messageImage != null);
} else {
// Add in a space for layout purposes but do not
// change the instance variable
String displayedErrorMessage = " " + errorMessage; //$NON-NLS-1$
updateMessage(displayedErrorMessage);
if (!showingError) {
// we were not previously showing an error
showingError = true;
messageImageLabel.setImage(JFaceResources
.getImage(DLG_IMG_TITLE_ERROR));
setImageLabelVisible(true);
}
}
layoutForNewMessage(false);
}
/**
* Re-layout the labels for the new message.
*
* @param forceLayout
* <code>true</code> to force a layout of the shell
*/
private void layoutForNewMessage(boolean forceLayout) {
int verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
int horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
// If there are no images then layout as normal
if (errorMessage == null && messageImage == null) {
setImageLabelVisible(false);
setLayoutsForNormalMessage(verticalSpacing, horizontalSpacing);
} else {
messageImageLabel.setVisible(true);
bottomFillerLabel.setVisible(true);
leftFillerLabel.setVisible(true);
/**
* Note that we do not use horizontalSpacing here as when the
* background of the messages changes there will be gaps between the
* icon label and the message that are the background color of the
* shell. We add a leading space elsewhere to compendate for this.
*/
FormData data = new FormData();
data.left = new FormAttachment(0, H_GAP_IMAGE);
data.top = new FormAttachment(titleLabel, verticalSpacing);
messageImageLabel.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(messageImageLabel, 0);
data.left = new FormAttachment(0, 0);
data.bottom = new FormAttachment(messageLabel, 0, SWT.BOTTOM);
data.right = new FormAttachment(messageImageLabel, 0, SWT.RIGHT);
bottomFillerLabel.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(messageImageLabel, 0, SWT.TOP);
data.left = new FormAttachment(0, 0);
data.bottom = new FormAttachment(messageImageLabel, 0, SWT.BOTTOM);
data.right = new FormAttachment(messageImageLabel, 0);
leftFillerLabel.setLayoutData(data);
FormData messageLabelData = new FormData();
messageLabelData.top = new FormAttachment(titleLabel,
verticalSpacing);
messageLabelData.right = new FormAttachment(titleImageLabel);
messageLabelData.left = new FormAttachment(messageImageLabel, 0);
messageLabelData.height = messageLabelHeight;
if (titleImageLargest)
messageLabelData.bottom = new FormAttachment(titleImageLabel,
0, SWT.BOTTOM);
messageLabel.setLayoutData(messageLabelData);
}
if (forceLayout) {
getShell().layout();
} else {
// Do not layout before the dialog area has been created
// to avoid incomplete calculations.
if (dialogArea != null)
workArea.getParent().layout(true);
}
int messageLabelUnclippedHeight = messageLabel.computeSize(messageLabel.getSize().x - xTrim, SWT.DEFAULT, true).y;
boolean messageLabelClipped = messageLabelUnclippedHeight > messageLabel.getSize().y - yTrim;
if (messageLabel.getData() instanceof ToolTip) {
ToolTip toolTip = (ToolTip) messageLabel.getData();
toolTip.hide();
toolTip.deactivate();
messageLabel.setData(null);
}
if (messageLabelClipped) {
ToolTip tooltip = new ToolTip(messageLabel, ToolTip.NO_RECREATE, false) {
protected Composite createToolTipContentArea(Event event, Composite parent) {
Composite result = new Composite(parent, SWT.NONE);
result.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
result.setLayout(new GridLayout());
Text text = new Text(result, SWT.WRAP);
text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
text.setText(messageLabel.getText());
GridData gridData = new GridData();
gridData.widthHint = messageLabel.getSize().x;
text.setLayoutData(gridData);
Dialog.applyDialogFont(result);
return result;
}
public Point getLocation(Point tipSize, Event event) {
return messageLabel.getShell().toDisplay(messageLabel.getLocation());
}
};
messageLabel.setData(tooltip);
tooltip.setPopupDelay(0);
tooltip.activate();
}
}
/**
* Set the message text. If the message line currently displays an error,
* the message is saved and will be redisplayed when the error message is
* set to <code>null</code>.
* <p>
* Shortcut for <code>setMessage(newMessage, IMessageProvider.NONE)</code>
* </p>
* This method should be called after the dialog has been opened as it
* updates the message label immediately.
*
* @param newMessage
* the message, or <code>null</code> to clear the message
*/
public void setMessage(String newMessage) {
setMessage(newMessage, IMessageProvider.NONE);
}
/**
* Sets the message for this dialog with an indication of what type of
* message it is.
* <p>
* The valid message types are one of <code>NONE</code>,
* <code>INFORMATION</code>,<code>WARNING</code>, or
* <code>ERROR</code>.
* </p>
* <p>
* Note that for backward compatibility, a message of type
* <code>ERROR</code> is different than an error message (set using
* <code>setErrorMessage</code>). An error message overrides the current
* message until the error message is cleared. This method replaces the
* current message and does not affect the error message.
* </p>
*
* @param newMessage
* the message, or <code>null</code> to clear the message
* @param newType
* the message type
* @since 2.0
*/
public void setMessage(String newMessage, int newType) {
Image newImage = null;
if (newMessage != null) {
switch (newType) {
case IMessageProvider.NONE:
break;
case IMessageProvider.INFORMATION:
newImage = JFaceResources.getImage(DLG_IMG_MESSAGE_INFO);
break;
case IMessageProvider.WARNING:
newImage = JFaceResources.getImage(DLG_IMG_MESSAGE_WARNING);
break;
case IMessageProvider.ERROR:
newImage = JFaceResources.getImage(DLG_IMG_MESSAGE_ERROR);
break;
}
}
showMessage(newMessage, newImage);
}
/**
* Show the new message and image.
*
* @param newMessage
* @param newImage
*/
private void showMessage(String newMessage, Image newImage) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=249915
if (newMessage == null)
newMessage = ""; //$NON-NLS-1$
// Any change?
if (message.equals(newMessage) && messageImage == newImage) {
return;
}
message = newMessage;
// Message string to be shown - if there is an image then add in
// a space to the message for layout purposes
String shownMessage = (newImage == null) ? message : " " + message; //$NON-NLS-1$
messageImage = newImage;
if (!showingError) {
// we are not showing an error
updateMessage(shownMessage);
messageImageLabel.setImage(messageImage);
setImageLabelVisible(messageImage != null);
layoutForNewMessage(false);
}
}
/**
* Update the contents of the messageLabel.
*
* @param newMessage
* the message to use
*/
private void updateMessage(String newMessage) {
messageLabel.setText(newMessage);
}
/**
* Sets the title to be shown in the title area of this dialog.
*
* @param newTitle
* the title show
*/
public void setTitle(String newTitle) {
if (titleLabel == null)
return;
String title = newTitle;
if (title == null)
title = "";//$NON-NLS-1$
titleLabel.setText(title);
}
/**
* Sets the title bar color for this dialog.
*
* @param color
* the title bar color
*/
public void setTitleAreaColor(RGB color) {
titleAreaRGB = color;
}
/**
* Sets the title image to be shown in the title area of this dialog.
*
* @param newTitleImage
* the title image to be shown
*/
public void setTitleImage(Image newTitleImage) {
titleAreaImage = newTitleImage;
if (titleImageLabel != null) {
titleImageLabel.setImage(newTitleImage);
determineTitleImageLargest();
Control top;
if (titleImageLargest)
top = titleImageLabel;
else
top = messageLabel;
resetWorkAreaAttachments(top);
}
}
/**
* Make the label used for displaying error images visible depending on
* boolean.
*
* @param visible
* If <code>true</code> make the image visible, if not then
* make it not visible.
*/
private void setImageLabelVisible(boolean visible) {
messageImageLabel.setVisible(visible);
bottomFillerLabel.setVisible(visible);
leftFillerLabel.setVisible(visible);
}
/**
* Reset the attachment of the workArea to now attach to top as the top
* control.
*
* @param top
*/
private void resetWorkAreaAttachments(Control top) {
FormData childData = new FormData();
childData.top = new FormAttachment(top);
childData.right = new FormAttachment(100, 0);
childData.left = new FormAttachment(0, 0);
childData.bottom = new FormAttachment(100, 0);
workArea.setLayoutData(childData);
}
/**
* Returns the current message text for this dialog. This message is
* displayed in the message line of the dialog when the error message
* is <code>null</code>. If there is a non-null error message, this
* message is not shown, but is stored so that it can be shown in
* the message line whenever {@link #setErrorMessage(String)} is called with
* a <code>null</code> parameter.
*
* @return the message text, which is never <code>null</code>.
*
* @see #setMessage(String)
* @see #setErrorMessage(String)
*
* @since 3.6
*/
public String getMessage() {
return message;
}
/**
* Returns the current error message being shown in the dialog, or
* <code>null</code> if there is no error message being shown.
*
* @return the error message, which may be <code>null</code>.
*
* @see #setErrorMessage(String)
* @see #setMessage(String)
*
* @since 3.6
*/
public String getErrorMessage() {
return errorMessage;
}
}
| 24,337 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TSWizardDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/wizard/TSWizardDialog.java | /*******************************************************************************
* Copyright (c) 2000, 2011 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
* Chris Gross ([email protected]) - patch for bug 16179
* Eugene Ostroukhov <[email protected]> - Bug 287887 [Wizards] [api] Cancel button has two distinct roles
* Paul Adams <[email protected]> - Bug 202534 - [Dialogs] SWT error in Wizard dialog when help is displayed and "Finish" is pressed
*******************************************************************************/
package net.heartsome.cat.common.ui.wizard;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.IPageChangeProvider;
import org.eclipse.jface.dialogs.IPageChangedListener;
import org.eclipse.jface.dialogs.IPageChangingListener;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.PageChangedEvent;
import org.eclipse.jface.dialogs.PageChangingEvent;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.IWizardContainer2;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.ProgressMonitorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.HelpEvent;
import org.eclipse.swt.events.HelpListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
/**
* A dialog to show a wizard to the end user.(此类与 org.eclipse.jface.wizard.WizardDialog 的区别只是继承的类不同)
* <p>
* In typical usage, the client instantiates this class with a particular
* wizard. The dialog serves as the wizard container and orchestrates the
* presentation of its pages.
* <p>
* The standard layout is roughly as follows: it has an area at the top
* containing both the wizard's title, description, and image; the actual wizard
* page appears in the middle; below that is a progress indicator (which is made
* visible if needed); and at the bottom of the page is message line and a
* button bar containing Help, Next, Back, Finish, and Cancel buttons (or some
* subset).
* </p>
* <p>
* Clients may subclass <code>WizardDialog</code>, although this is rarely
* required.
* </p>
*/
public class TSWizardDialog extends TSTitleAreaDialog implements IWizardContainer2,
IPageChangeProvider {
/**
* Image registry key for error message image (value
* <code>"dialog_title_error_image"</code>).
*/
public static final String WIZ_IMG_ERROR = "dialog_title_error_image"; //$NON-NLS-1$
// The wizard the dialog is currently showing.
private IWizard wizard;
// Wizards to dispose
private ArrayList createdWizards = new ArrayList();
// Current nested wizards
private ArrayList nestedWizards = new ArrayList();
// The currently displayed page.
private IWizardPage currentPage = null;
// The number of long running operation executed from the dialog.
private long activeRunningOperations = 0;
/**
* The time in milliseconds where the last job finished. 'Enter' key presses are ignored for the
* next {@link #RESTORE_ENTER_DELAY} milliseconds.
* <p>
* The value <code>-1</code> indicates that the traverse listener needs to be installed.
* </p>
*
* @since 3.6
*/
private long timeWhenLastJobFinished= -1;
// Tells whether a subclass provided the progress monitor part
private boolean useCustomProgressMonitorPart= true;
// The current page message and description
private String pageMessage;
private int pageMessageType = IMessageProvider.NONE;
private String pageDescription;
// The progress monitor
private ProgressMonitorPart progressMonitorPart;
private Cursor waitCursor;
private Cursor arrowCursor;
private MessageDialog windowClosingDialog;
// Navigation buttons
private Button backButton;
private Button nextButton;
private Button finishButton;
private Button cancelButton;
private Button helpButton;
private SelectionAdapter cancelListener;
private boolean isMovingToPreviousPage = false;
private Composite pageContainer;
private PageContainerFillLayout pageContainerLayout = new PageContainerFillLayout(
5, 5, 300, 225);
private int pageWidth = SWT.DEFAULT;
private int pageHeight = SWT.DEFAULT;
private static final String FOCUS_CONTROL = "focusControl"; //$NON-NLS-1$
/**
* A delay in milliseconds that reduces the risk that the user accidentally triggers a
* button by pressing the 'Enter' key immediately after a job has finished.
*
* @since 3.6
*/
private static final int RESTORE_ENTER_DELAY= 500;
private boolean lockedUI = false;
private ListenerList pageChangedListeners = new ListenerList();
private ListenerList pageChangingListeners = new ListenerList();
/**
* A layout for a container which includes several pages, like a notebook,
* wizard, or preference dialog. The size computed by this layout is the
* maximum width and height of all pages currently inserted into the
* container.
*/
protected class PageContainerFillLayout extends Layout {
/**
* The margin width; <code>5</code> pixels by default.
*/
public int marginWidth = 5;
/**
* The margin height; <code>5</code> pixels by default.
*/
public int marginHeight = 5;
/**
* The minimum width; <code>0</code> pixels by default.
*/
public int minimumWidth = 0;
/**
* The minimum height; <code>0</code> pixels by default.
*/
public int minimumHeight = 0;
/**
* Creates new layout object.
*
* @param mw
* the margin width
* @param mh
* the margin height
* @param minW
* the minimum width
* @param minH
* the minimum height
*/
public PageContainerFillLayout(int mw, int mh, int minW, int minH) {
marginWidth = mw;
marginHeight = mh;
minimumWidth = minW;
minimumHeight = minH;
}
/*
* (non-Javadoc) Method declared on Layout.
*/
public Point computeSize(Composite composite, int wHint, int hHint,
boolean force) {
if (wHint != SWT.DEFAULT && hHint != SWT.DEFAULT) {
return new Point(wHint, hHint);
}
Point result = null;
Control[] children = composite.getChildren();
if (children.length > 0) {
result = new Point(0, 0);
for (int i = 0; i < children.length; i++) {
Point cp = children[i].computeSize(wHint, hHint, force);
result.x = Math.max(result.x, cp.x);
result.y = Math.max(result.y, cp.y);
}
result.x = result.x + 2 * marginWidth;
result.y = result.y + 2 * marginHeight;
} else {
Rectangle rect = composite.getClientArea();
result = new Point(rect.width, rect.height);
}
result.x = Math.max(result.x, minimumWidth);
result.y = Math.max(result.y, minimumHeight);
if (wHint != SWT.DEFAULT) {
result.x = wHint;
}
if (hHint != SWT.DEFAULT) {
result.y = hHint;
}
return result;
}
/**
* Returns the client area for the given composite according to this
* layout.
*
* @param c
* the composite
* @return the client area rectangle
*/
public Rectangle getClientArea(Composite c) {
Rectangle rect = c.getClientArea();
rect.x = rect.x + marginWidth;
rect.y = rect.y + marginHeight;
rect.width = rect.width - 2 * marginWidth;
rect.height = rect.height - 2 * marginHeight;
return rect;
}
/*
* (non-Javadoc) Method declared on Layout.
*/
public void layout(Composite composite, boolean force) {
Rectangle rect = getClientArea(composite);
Control[] children = composite.getChildren();
for (int i = 0; i < children.length; i++) {
children[i].setBounds(rect);
}
}
/**
* Lays outs the page according to this layout.
*
* @param w
* the control
*/
public void layoutPage(Control w) {
w.setBounds(getClientArea(w.getParent()));
}
/**
* Sets the location of the page so that its origin is in the upper left
* corner.
*
* @param w
* the control
*/
public void setPageLocation(Control w) {
w.setLocation(marginWidth, marginHeight);
}
}
/**
* Creates a new wizard dialog for the given wizard.
*
* @param parentShell
* the parent shell
* @param newWizard
* the wizard this dialog is working on
*/
public TSWizardDialog(Shell parentShell, IWizard newWizard) {
super(parentShell);
setShellStyle(SWT.CLOSE | SWT.MAX | SWT.TITLE | SWT.BORDER
| SWT.APPLICATION_MODAL | SWT.RESIZE | getDefaultOrientation());
setWizard(newWizard);
// since VAJava can't initialize an instance var with an anonymous
// class outside a constructor we do it here:
cancelListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
cancelPressed();
}
};
}
/**
* About to start a long running operation triggered through the wizard.
* Shows the progress monitor and disables the wizard's buttons and
* controls.
*
* @param enableCancelButton
* <code>true</code> if the Cancel button should be enabled,
* and <code>false</code> if it should be disabled
* @return the saved UI state
*/
private Object aboutToStart(boolean enableCancelButton) {
Map savedState = null;
if (getShell() != null) {
// Save focus control
Control focusControl = getShell().getDisplay().getFocusControl();
if (focusControl != null && focusControl.getShell() != getShell()) {
focusControl = null;
}
boolean needsProgressMonitor = wizard.needsProgressMonitor();
// Set the busy cursor to all shells.
Display d = getShell().getDisplay();
waitCursor = new Cursor(d, SWT.CURSOR_WAIT);
setDisplayCursor(waitCursor);
if (useCustomProgressMonitorPart) {
cancelButton.removeSelectionListener(cancelListener);
// Set the arrow cursor to the cancel component.
arrowCursor = new Cursor(d, SWT.CURSOR_ARROW);
cancelButton.setCursor(arrowCursor);
}
// Deactivate shell
savedState = saveUIState(useCustomProgressMonitorPart && needsProgressMonitor && enableCancelButton);
if (focusControl != null) {
savedState.put(FOCUS_CONTROL, focusControl);
}
// Activate cancel behavior.
if (needsProgressMonitor) {
if (enableCancelButton || useCustomProgressMonitorPart) {
progressMonitorPart.attachToCancelComponent(cancelButton);
}
progressMonitorPart.setVisible(true);
}
// Install traverse listener once in order to implement 'Enter' and 'Space' key blocking
if (timeWhenLastJobFinished == -1) {
timeWhenLastJobFinished= 0;
getShell().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN || (e.detail == SWT.TRAVERSE_MNEMONIC && e.keyCode == 32)) {
// We want to ignore the keystroke when we detect that it has been received within the
// delay period after the last operation has finished. This prevents the user from accidentally
// hitting "Enter" or "Space", intending to cancel an operation, but having it processed exactly
// when the operation finished, thus traversing the wizard. If there is another operation still
// running, the UI is locked anyway so we are not in this code. This listener should fire only
// after the UI state is restored (which by definition means all jobs are done.
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=287887
if (timeWhenLastJobFinished != 0 && System.currentTimeMillis() - timeWhenLastJobFinished < RESTORE_ENTER_DELAY) {
e.doit= false;
return;
}
timeWhenLastJobFinished= 0;
}}
});
}
}
return savedState;
}
/**
* The Back button has been pressed.
*/
protected void backPressed() {
IWizardPage page = currentPage.getPreviousPage();
if (page == null) {
// should never happen since we have already visited the page
return;
}
// set flag to indicate that we are moving back
isMovingToPreviousPage = true;
// show the page
showPage(page);
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
protected void buttonPressed(int buttonId) {
switch (buttonId) {
case IDialogConstants.HELP_ID: {
helpPressed();
break;
}
case IDialogConstants.BACK_ID: {
backPressed();
break;
}
case IDialogConstants.NEXT_ID: {
nextPressed();
break;
}
case IDialogConstants.FINISH_ID: {
finishPressed();
break;
}
// The Cancel button has a listener which calls cancelPressed
// directly
}
}
/**
* Calculates the difference in size between the given page and the page
* container. A larger page results in a positive delta.
*
* @param page
* the page
* @return the size difference encoded as a
* <code>new Point(deltaWidth,deltaHeight)</code>
*/
private Point calculatePageSizeDelta(IWizardPage page) {
Control pageControl = page.getControl();
if (pageControl == null) {
// control not created yet
return new Point(0, 0);
}
Point contentSize = pageControl.computeSize(SWT.DEFAULT, SWT.DEFAULT,
true);
Rectangle rect = pageContainerLayout.getClientArea(pageContainer);
Point containerSize = new Point(rect.width, rect.height);
return new Point(Math.max(0, contentSize.x - containerSize.x), Math
.max(0, contentSize.y - containerSize.y));
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
protected void cancelPressed() {
if (activeRunningOperations <= 0) {
// Close the dialog. The check whether the dialog can be
// closed or not is done in <code>okToClose</code>.
// This ensures that the check is also evaluated when the user
// presses the window's close button.
setReturnCode(CANCEL);
close();
} else {
cancelButton.setEnabled(false);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#close()
*/
public boolean close() {
if (okToClose()) {
return hardClose();
}
return false;
}
/*
* (non-Javadoc) Method declared on Window.
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
// Register help listener on the shell
newShell.addHelpListener(new HelpListener() {
public void helpRequested(HelpEvent event) {
// call perform help on the current page
if (currentPage != null) {
currentPage.performHelp();
}
}
});
}
/**
* Creates the buttons for this dialog's button bar.
* <p>
* The <code>WizardDialog</code> implementation of this framework method
* prevents the parent composite's columns from being made equal width in
* order to remove the margin between the Back and Next buttons.
* </p>
*
* @param parent
* the parent composite to contain the buttons
*/
protected void createButtonsForButtonBar(Composite parent) {
((GridLayout) parent.getLayout()).makeColumnsEqualWidth = false;
if (wizard.isHelpAvailable()) {
helpButton = createButton(parent, IDialogConstants.HELP_ID,
IDialogConstants.HELP_LABEL, false);
}
if (wizard.needsPreviousAndNextButtons()) {
createPreviousAndNextButtons(parent);
}
finishButton = createButton(parent, IDialogConstants.FINISH_ID,
IDialogConstants.FINISH_LABEL, true);
cancelButton = createCancelButton(parent);
if (parent.getDisplay().getDismissalAlignment() == SWT.RIGHT) {
// Make the default button the right-most button.
// See also special code in org.eclipse.jface.dialogs.Dialog#initializeBounds()
finishButton.moveBelow(null);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#setButtonLayoutData(org.eclipse.swt.widgets.Button)
*/
protected void setButtonLayoutData(Button button) {
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
// On large fonts this can make this dialog huge
widthHint = Math.min(widthHint,
button.getDisplay().getBounds().width / 5);
Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
data.widthHint = Math.max(widthHint, minSize.x);
button.setLayoutData(data);
}
/**
* Creates the Cancel button for this wizard dialog. Creates a standard (<code>SWT.PUSH</code>)
* button and registers for its selection events. Note that the number of
* columns in the button bar composite is incremented. The Cancel button is
* created specially to give it a removeable listener.
*
* @param parent
* the parent button bar
* @return the new Cancel button
*/
private Button createCancelButton(Composite parent) {
// increment the number of columns in the button bar
((GridLayout) parent.getLayout()).numColumns++;
Button button = new Button(parent, SWT.PUSH);
button.setText(IDialogConstants.CANCEL_LABEL);
setButtonLayoutData(button);
button.setFont(parent.getFont());
button.setData(new Integer(IDialogConstants.CANCEL_ID));
button.addSelectionListener(cancelListener);
return button;
}
/**
* Return the cancel button if the id is a the cancel id.
*
* @param id
* the button id
* @return the button corresponding to the button id
*/
protected Button getButton(int id) {
if (id == IDialogConstants.CANCEL_ID) {
return cancelButton;
}
return super.getButton(id);
}
/**
* The <code>WizardDialog</code> implementation of this
* <code>Window</code> method calls call <code>IWizard.addPages</code>
* to allow the current wizard to add extra pages, then
* <code>super.createContents</code> to create the controls. It then calls
* <code>IWizard.createPageControls</code> to allow the wizard to
* pre-create their page controls prior to opening, so that the wizard opens
* to the correct size. And finally it shows the first page.
*/
protected Control createContents(Composite parent) {
// Allow the wizard to add pages to itself
// Need to call this now so page count is correct
// for determining if next/previous buttons are needed
wizard.addPages();
Control contents = super.createContents(parent);
// Allow the wizard pages to precreate their page controls
createPageControls();
// Show the first page
showStartingPage();
return contents;
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
// Build the Page container
pageContainer = createPageContainer(composite);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.widthHint = pageWidth;
gd.heightHint = pageHeight;
pageContainer.setLayoutData(gd);
pageContainer.setFont(parent.getFont());
// Insert a progress monitor
progressMonitorPart= createProgressMonitorPart(composite, new GridLayout());
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
progressMonitorPart.setLayoutData(gridData);
progressMonitorPart.setVisible(false);
// Build the separator line
Label separator = new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
applyDialogFont(progressMonitorPart);
return composite;
}
/**
* Hook method for subclasses to create a custom progress monitor part.
* <p>
* The default implementation creates a progress monitor with a stop button will be created.
* </p>
*
* @param composite the parent composite
* @param pmlayout the layout
* @return ProgressMonitorPart the progress monitor part
*/
protected ProgressMonitorPart createProgressMonitorPart(
Composite composite, GridLayout pmlayout) {
useCustomProgressMonitorPart= false;
return new ProgressMonitorPart(composite, pmlayout, true) {
String currentTask = null;
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.ProgressMonitorPart#setBlocked(org.eclipse.core.runtime.IStatus)
*/
public void setBlocked(IStatus reason) {
super.setBlocked(reason);
if (!lockedUI) {
getBlockedHandler().showBlocked(getShell(), this, reason,
currentTask);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.ProgressMonitorPart#clearBlocked()
*/
public void clearBlocked() {
super.clearBlocked();
if (!lockedUI) {
getBlockedHandler().clearBlocked();
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.ProgressMonitorPart#beginTask(java.lang.String,
* int)
*/
public void beginTask(String name, int totalWork) {
super.beginTask(name, totalWork);
currentTask = name;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.ProgressMonitorPart#setTaskName(java.lang.String)
*/
public void setTaskName(String name) {
super.setTaskName(name);
currentTask = name;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.ProgressMonitorPart#subTask(java.lang.String)
*/
public void subTask(String name) {
super.subTask(name);
// If we haven't got anything yet use this value for more
// context
if (currentTask == null) {
currentTask = name;
}
}
};
}
/**
* Creates the container that holds all pages.
*
* @param parent
* @return Composite
*/
private Composite createPageContainer(Composite parent) {
Composite result = new Composite(parent, SWT.NULL);
result.setLayout(pageContainerLayout);
return result;
}
/**
* Allow the wizard's pages to pre-create their page controls. This allows
* the wizard dialog to open to the correct size.
*/
private void createPageControls() {
// Allow the wizard pages to precreate their page controls
// This allows the wizard to open to the correct size
wizard.createPageControls(pageContainer);
// Ensure that all of the created pages are initially not visible
IWizardPage[] pages = wizard.getPages();
for (int i = 0; i < pages.length; i++) {
IWizardPage page = pages[i];
if (page.getControl() != null) {
page.getControl().setVisible(false);
}
}
}
/**
* Creates the Previous and Next buttons for this wizard dialog. Creates
* standard (<code>SWT.PUSH</code>) buttons and registers for their
* selection events. Note that the number of columns in the button bar
* composite is incremented. These buttons are created specially to prevent
* any space between them.
*
* @param parent
* the parent button bar
* @return a composite containing the new buttons
*/
private Composite createPreviousAndNextButtons(Composite parent) {
// increment the number of columns in the button bar
((GridLayout) parent.getLayout()).numColumns++;
Composite composite = new Composite(parent, SWT.NONE);
// create a layout with spacing and margins appropriate for the font
// size.
GridLayout layout = new GridLayout();
layout.numColumns = 0; // will be incremented by createButton
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
composite.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER
| GridData.VERTICAL_ALIGN_CENTER);
composite.setLayoutData(data);
composite.setFont(parent.getFont());
backButton = createButton(composite, IDialogConstants.BACK_ID,
IDialogConstants.BACK_LABEL, false);
nextButton = createButton(composite, IDialogConstants.NEXT_ID,
IDialogConstants.NEXT_LABEL, false);
// make sure screen readers skip visual '<', '>' chars on buttons:
final String backReaderText = IDialogConstants.BACK_LABEL.replace('<', ' ');
backButton.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = backReaderText;
}
});
final String nextReaderText = IDialogConstants.NEXT_LABEL.replace('>', ' ');
nextButton.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = nextReaderText;
}
});
return composite;
}
/**
* Creates and return a new wizard closing dialog without opening it.
*
* @return MessageDalog
*/
private MessageDialog createWizardClosingDialog() {
MessageDialog result = new MessageDialog(getShell(),
JFaceResources.getString("WizardClosingDialog.title"), //$NON-NLS-1$
null,
JFaceResources.getString("WizardClosingDialog.message"), //$NON-NLS-1$
MessageDialog.QUESTION,
new String[] { IDialogConstants.OK_LABEL }, 0) {
protected int getShellStyle() {
return super.getShellStyle() | SWT.SHEET;
}
};
return result;
}
/**
* The Finish button has been pressed.
*/
protected void finishPressed() {
// Wizards are added to the nested wizards list in setWizard.
// This means that the current wizard is always the last wizard in the
// list.
// Note that we first call the current wizard directly (to give it a
// chance to
// abort, do work, and save state) then call the remaining n-1 wizards
// in the
// list (to save state).
if (wizard.performFinish()) {
// Call perform finish on outer wizards in the nested chain
// (to allow them to save state for example)
for (int i = 0; i < nestedWizards.size() - 1; i++) {
((IWizard) nestedWizards.get(i)).performFinish();
}
// Hard close the dialog.
setReturnCode(OK);
hardClose();
}
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public IWizardPage getCurrentPage() {
return currentPage;
}
/**
* Returns the progress monitor for this wizard dialog (if it has one).
*
* @return the progress monitor, or <code>null</code> if this wizard
* dialog does not have one
*/
protected IProgressMonitor getProgressMonitor() {
return progressMonitorPart;
}
/**
* Returns the wizard this dialog is currently displaying.
*
* @return the current wizard
*/
protected IWizard getWizard() {
return wizard;
}
/**
* Closes this window.
*
* @return <code>true</code> if the window is (or was already) closed, and
* <code>false</code> if it is still open
*/
private boolean hardClose() {
// inform wizards
for (int i = 0; i < createdWizards.size(); i++) {
IWizard createdWizard = (IWizard) createdWizards.get(i);
try {
createdWizard.dispose();
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Policy.JFACE, IStatus.ERROR, e.getMessage(), e);
Policy.getLog().log(status);
}
// Remove this dialog as a parent from the managed wizard.
// Note that we do this after calling dispose as the wizard or
// its pages may need access to the container during
// dispose code
createdWizard.setContainer(null);
}
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=202534
// disposing the wizards could cause the image currently set in
// this dialog to be disposed. A subsequent repaint event during
// close would then fail. To prevent this case, we null out the image.
setTitleImage(null);
return super.close();
}
/**
* The Help button has been pressed.
*/
protected void helpPressed() {
if (currentPage != null) {
currentPage.performHelp();
}
}
/**
* The Next button has been pressed.
*/
protected void nextPressed() {
IWizardPage page = currentPage.getNextPage();
if (page == null) {
// something must have happened getting the next page
return;
}
// show the next page
showPage(page);
}
/**
* Notifies page changing listeners and returns result of page changing
* processing to the sender.
*
* @param eventType
* @return <code>true</code> if page changing listener completes
* successfully, <code>false</code> otherwise
*/
private boolean doPageChanging(IWizardPage targetPage) {
PageChangingEvent e = new PageChangingEvent(this, getCurrentPage(),
targetPage);
firePageChanging(e);
// Prevent navigation if necessary
return e.doit;
}
/**
* Checks whether it is alright to close this wizard dialog and performed
* standard cancel processing. If there is a long running operation in
* progress, this method posts an alert message saying that the wizard
* cannot be closed.
*
* @return <code>true</code> if it is alright to close this dialog, and
* <code>false</code> if it is not
*/
private boolean okToClose() {
if (activeRunningOperations > 0) {
synchronized (this) {
windowClosingDialog = createWizardClosingDialog();
}
windowClosingDialog.open();
synchronized (this) {
windowClosingDialog = null;
}
return false;
}
return wizard.performCancel();
}
/**
* Restores the enabled/disabled state of the given control.
*
* @param w
* the control
* @param h
* the map (key type: <code>String</code>, element type:
* <code>Boolean</code>)
* @param key
* the key
* @see #saveEnableStateAndSet
*/
private void restoreEnableState(Control w, Map h, String key) {
if (w != null) {
Boolean b = (Boolean) h.get(key);
if (b != null) {
w.setEnabled(b.booleanValue());
}
}
}
/**
* Restores the enabled/disabled state of the wizard dialog's buttons and
* the tree of controls for the currently showing page.
*
* @param state
* a map containing the saved state as returned by
* <code>saveUIState</code>
* @see #saveUIState
*/
private void restoreUIState(Map state) {
restoreEnableState(backButton, state, "back"); //$NON-NLS-1$
restoreEnableState(nextButton, state, "next"); //$NON-NLS-1$
restoreEnableState(finishButton, state, "finish"); //$NON-NLS-1$
restoreEnableState(cancelButton, state, "cancel"); //$NON-NLS-1$
restoreEnableState(helpButton, state, "help"); //$NON-NLS-1$
Object pageValue = state.get("page"); //$NON-NLS-1$
if (pageValue != null) {
((ControlEnableState) pageValue).restore();
}
}
/**
* This implementation of IRunnableContext#run(boolean, boolean,
* IRunnableWithProgress) blocks until the runnable has been run, regardless
* of the value of <code>fork</code>. It is recommended that
* <code>fork</code> is set to true in most cases. If <code>fork</code>
* is set to <code>false</code>, the runnable will run in the UI thread
* and it is the runnable's responsibility to call
* <code>Display.readAndDispatch()</code> to ensure UI responsiveness.
*
* UI state is saved prior to executing the long-running operation and is
* restored after the long-running operation completes executing. Any
* attempt to change the UI state of the wizard in the long-running
* operation will be nullified when original UI state is restored.
*
*/
public void run(boolean fork, boolean cancelable,
IRunnableWithProgress runnable) throws InvocationTargetException,
InterruptedException {
// The operation can only be canceled if it is executed in a separate
// thread.
// Otherwise the UI is blocked anyway.
Object state = null;
if (activeRunningOperations == 0) {
state = aboutToStart(fork && cancelable);
}
activeRunningOperations++;
try {
if (!fork) {
lockedUI = true;
}
ModalContext.run(runnable, fork, getProgressMonitor(), getShell()
.getDisplay());
lockedUI = false;
} finally {
// explicitly invoke done() on our progress monitor so that its
// label does not spill over to the next invocation, see bug 271530
if (getProgressMonitor() != null) {
getProgressMonitor().done();
}
// Stop if this is the last one
if (state != null) {
timeWhenLastJobFinished= System.currentTimeMillis();
stopped(state);
}
activeRunningOperations--;
}
}
/**
* Saves the enabled/disabled state of the given control in the given map,
* which must be modifiable.
*
* @param w
* the control, or <code>null</code> if none
* @param h
* the map (key type: <code>String</code>, element type:
* <code>Boolean</code>)
* @param key
* the key
* @param enabled
* <code>true</code> to enable the control, and
* <code>false</code> to disable it
* @see #restoreEnableState(Control, Map, String)
*/
private void saveEnableStateAndSet(Control w, Map h, String key,
boolean enabled) {
if (w != null) {
h.put(key, w.getEnabled() ? Boolean.TRUE : Boolean.FALSE);
w.setEnabled(enabled);
}
}
/**
* Captures and returns the enabled/disabled state of the wizard dialog's
* buttons and the tree of controls for the currently showing page. All
* these controls are disabled in the process, with the possible exception
* of the Cancel button.
*
* @param keepCancelEnabled
* <code>true</code> if the Cancel button should remain
* enabled, and <code>false</code> if it should be disabled
* @return a map containing the saved state suitable for restoring later
* with <code>restoreUIState</code>
* @see #restoreUIState
*/
private Map saveUIState(boolean keepCancelEnabled) {
Map savedState = new HashMap(10);
saveEnableStateAndSet(backButton, savedState, "back", false); //$NON-NLS-1$
saveEnableStateAndSet(nextButton, savedState, "next", false); //$NON-NLS-1$
saveEnableStateAndSet(finishButton, savedState, "finish", false); //$NON-NLS-1$
saveEnableStateAndSet(cancelButton, savedState, "cancel", keepCancelEnabled); //$NON-NLS-1$
saveEnableStateAndSet(helpButton, savedState, "help", false); //$NON-NLS-1$
if (currentPage != null) {
savedState
.put(
"page", ControlEnableState.disable(currentPage.getControl())); //$NON-NLS-1$
}
return savedState;
}
/**
* Sets the given cursor for all shells currently active for this window's
* display.
*
* @param c
* the cursor
*/
private void setDisplayCursor(Cursor c) {
Shell[] shells = getShell().getDisplay().getShells();
for (int i = 0; i < shells.length; i++) {
shells[i].setCursor(c);
}
}
/**
* Sets the minimum page size used for the pages.
*
* @param minWidth
* the minimum page width
* @param minHeight
* the minimum page height
* @see #setMinimumPageSize(Point)
*/
public void setMinimumPageSize(int minWidth, int minHeight) {
Assert.isTrue(minWidth >= 0 && minHeight >= 0);
pageContainerLayout.minimumWidth = minWidth;
pageContainerLayout.minimumHeight = minHeight;
}
/**
* Sets the minimum page size used for the pages.
*
* @param size
* the page size encoded as <code>new Point(width,height)</code>
* @see #setMinimumPageSize(int,int)
*/
public void setMinimumPageSize(Point size) {
setMinimumPageSize(size.x, size.y);
}
/**
* Sets the size of all pages. The given size takes precedence over computed
* sizes.
*
* @param width
* the page width
* @param height
* the page height
* @see #setPageSize(Point)
*/
public void setPageSize(int width, int height) {
pageWidth = width;
pageHeight = height;
}
/**
* Sets the size of all pages. The given size takes precedence over computed
* sizes.
*
* @param size
* the page size encoded as <code>new Point(width,height)</code>
* @see #setPageSize(int,int)
*/
public void setPageSize(Point size) {
setPageSize(size.x, size.y);
}
/**
* Sets the wizard this dialog is currently displaying.
*
* @param newWizard
* the wizard
*/
protected void setWizard(IWizard newWizard) {
wizard = newWizard;
wizard.setContainer(this);
if (!createdWizards.contains(wizard)) {
createdWizards.add(wizard);
// New wizard so just add it to the end of our nested list
nestedWizards.add(wizard);
if (pageContainer != null) {
// Dialog is already open
// Allow the wizard pages to precreate their page controls
// This allows the wizard to open to the correct size
createPageControls();
// Ensure the dialog is large enough for the wizard
updateSizeForWizard(wizard);
pageContainer.layout(true);
}
} else {
// We have already seen this wizard, if it is the previous wizard
// on the nested list then we assume we have gone back and remove
// the last wizard from the list
int size = nestedWizards.size();
if (size >= 2 && nestedWizards.get(size - 2) == wizard) {
nestedWizards.remove(size - 1);
} else {
// Assume we are going forward to revisit a wizard
nestedWizards.add(wizard);
}
}
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public void showPage(IWizardPage page) {
if (page == null || page == currentPage) {
return;
}
if (!isMovingToPreviousPage) {
// remember my previous page.
page.setPreviousPage(currentPage);
} else {
isMovingToPreviousPage = false;
}
// If page changing evaluation unsuccessful, do not change the page
if (!doPageChanging(page))
return;
// Update for the new page in a busy cursor if possible
if (getContents() == null) {
updateForPage(page);
} else {
final IWizardPage finalPage = page;
BusyIndicator.showWhile(getContents().getDisplay(), new Runnable() {
public void run() {
updateForPage(finalPage);
}
});
}
}
/**
* Update the receiver for the new page.
*
* @param page
*/
private void updateForPage(IWizardPage page) {
// ensure this page belongs to the current wizard
if (wizard != page.getWizard()) {
setWizard(page.getWizard());
}
// ensure that page control has been created
// (this allows lazy page control creation)
if (page.getControl() == null) {
page.createControl(pageContainer);
// the page is responsible for ensuring the created control is
// accessible via getControl.
Assert.isNotNull(page.getControl(), JFaceResources.format(
JFaceResources.getString("WizardDialog.missingSetControl"), //$NON-NLS-1$
new Object[] { page.getName() }));
// ensure the dialog is large enough for this page
updateSize(page);
}
// make the new page visible
IWizardPage oldPage = currentPage;
currentPage = page;
currentPage.setVisible(true);
if (oldPage != null) {
oldPage.setVisible(false);
}
// update the dialog controls
update();
}
/**
* Shows the starting page of the wizard.
*/
private void showStartingPage() {
currentPage = wizard.getStartingPage();
if (currentPage == null) {
// something must have happened getting the page
return;
}
// ensure the page control has been created
if (currentPage.getControl() == null) {
currentPage.createControl(pageContainer);
// the page is responsible for ensuring the created control is
// accessible via getControl.
Assert.isNotNull(currentPage.getControl());
// we do not need to update the size since the call
// to initialize bounds has not been made yet.
}
// make the new page visible
currentPage.setVisible(true);
// update the dialog controls
update();
}
/**
* A long running operation triggered through the wizard was stopped either
* by user input or by normal end. Hides the progress monitor and restores
* the enable state wizard's buttons and controls.
*
* @param savedState
* the saved UI state as returned by <code>aboutToStart</code>
* @see #aboutToStart
*/
private void stopped(Object savedState) {
if (getShell() != null && !getShell().isDisposed()) {
if (wizard.needsProgressMonitor()) {
progressMonitorPart.setVisible(false);
progressMonitorPart.removeFromCancelComponent(cancelButton);
}
Map state = (Map) savedState;
restoreUIState(state);
setDisplayCursor(null);
if (useCustomProgressMonitorPart) {
cancelButton.addSelectionListener(cancelListener);
cancelButton.setCursor(null);
arrowCursor.dispose();
arrowCursor = null;
}
waitCursor.dispose();
waitCursor = null;
Control focusControl = (Control) state.get(FOCUS_CONTROL);
if (focusControl != null && !focusControl.isDisposed()) {
focusControl.setFocus();
}
}
}
/**
* Updates this dialog's controls to reflect the current page.
*/
protected void update() {
// Update the window title
updateWindowTitle();
// Update the title bar
updateTitleBar();
// Update the buttons
updateButtons();
// Fires the page change event
firePageChanged(new PageChangedEvent(this, getCurrentPage()));
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public void updateButtons() {
boolean canFlipToNextPage = false;
boolean canFinish = wizard.canFinish();
if (backButton != null) {
backButton.setEnabled(currentPage.getPreviousPage() != null);
}
if (nextButton != null) {
canFlipToNextPage = currentPage.canFlipToNextPage();
nextButton.setEnabled(canFlipToNextPage);
}
finishButton.setEnabled(canFinish);
// finish is default unless it is disabled and next is enabled
if (canFlipToNextPage && !canFinish) {
getShell().setDefaultButton(nextButton);
} else {
getShell().setDefaultButton(finishButton);
}
}
/**
* Update the message line with the page's description.
* <p>
* A description is shown only if there is no message or error message.
* </p>
*/
private void updateDescriptionMessage() {
pageDescription = currentPage.getDescription();
setMessage(pageDescription);
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public void updateMessage() {
if (currentPage == null) {
return;
}
pageMessage = currentPage.getMessage();
if (pageMessage != null && currentPage instanceof IMessageProvider) {
pageMessageType = ((IMessageProvider) currentPage).getMessageType();
} else {
pageMessageType = IMessageProvider.NONE;
}
if (pageMessage == null) {
setMessage(pageDescription);
} else {
setMessage(pageMessage, pageMessageType);
}
setErrorMessage(currentPage.getErrorMessage());
}
/**
* Changes the shell size to the given size, ensuring that it is no larger
* than the display bounds.
*
* @param width
* the shell width
* @param height
* the shell height
*/
private void setShellSize(int width, int height) {
Rectangle size = getShell().getBounds();
size.height = height;
size.width = width;
getShell().setBounds(getConstrainedShellBounds(size));
}
/**
* Computes the correct dialog size for the current page and resizes its shell if necessary.
* Also causes the container to refresh its layout.
*
* @param page the wizard page to use to resize the dialog
* @since 2.0
*/
protected void updateSize(IWizardPage page) {
if (page == null || page.getControl() == null) {
return;
}
updateSizeForPage(page);
pageContainerLayout.layoutPage(page.getControl());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.IWizardContainer2#updateSize()
*/
public void updateSize() {
updateSize(currentPage);
}
/**
* Computes the correct dialog size for the given page and resizes its shell if necessary.
*
* @param page the wizard page
*/
private void updateSizeForPage(IWizardPage page) {
// ensure the page container is large enough
Point delta = calculatePageSizeDelta(page);
if (delta.x > 0 || delta.y > 0) {
// increase the size of the shell
Shell shell = getShell();
Point shellSize = shell.getSize();
setShellSize(shellSize.x + delta.x, shellSize.y + delta.y);
constrainShellSize();
}
}
/**
* Computes the correct dialog size for the given wizard and resizes its shell if necessary.
*
* @param sizingWizard the wizard
*/
private void updateSizeForWizard(IWizard sizingWizard) {
Point delta = new Point(0, 0);
IWizardPage[] pages = sizingWizard.getPages();
for (int i = 0; i < pages.length; i++) {
// ensure the page container is large enough
Point pageDelta = calculatePageSizeDelta(pages[i]);
delta.x = Math.max(delta.x, pageDelta.x);
delta.y = Math.max(delta.y, pageDelta.y);
}
if (delta.x > 0 || delta.y > 0) {
// increase the size of the shell
Shell shell = getShell();
Point shellSize = shell.getSize();
setShellSize(shellSize.x + delta.x, shellSize.y + delta.y);
}
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public void updateTitleBar() {
String s = null;
if (currentPage != null) {
s = currentPage.getTitle();
}
if (s == null) {
s = ""; //$NON-NLS-1$
}
setTitle(s);
if (currentPage != null) {
setTitleImage(currentPage.getImage());
updateDescriptionMessage();
}
updateMessage();
}
/*
* (non-Javadoc) Method declared on IWizardContainer.
*/
public void updateWindowTitle() {
if (getShell() == null) {
// Not created yet
return;
}
String title = wizard.getWindowTitle();
if (title == null) {
title = ""; //$NON-NLS-1$
}
getShell().setText(title);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IPageChangeProvider#getSelectedPage()
*/
public Object getSelectedPage() {
return getCurrentPage();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialog.IPageChangeProvider#addPageChangedListener()
*/
public void addPageChangedListener(IPageChangedListener listener) {
pageChangedListeners.add(listener);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialog.IPageChangeProvider#removePageChangedListener()
*/
public void removePageChangedListener(IPageChangedListener listener) {
pageChangedListeners.remove(listener);
}
/**
* Notifies any selection changed listeners that the selected page has
* changed. Only listeners registered at the time this method is called are
* notified.
*
* @param event
* a selection changed event
*
* @see IPageChangedListener#pageChanged
*
* @since 3.1
*/
protected void firePageChanged(final PageChangedEvent event) {
Object[] listeners = pageChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i) {
final IPageChangedListener l = (IPageChangedListener) listeners[i];
SafeRunnable.run(new SafeRunnable() {
public void run() {
l.pageChanged(event);
}
});
}
}
/**
* Adds a listener for page changes to the list of page changing listeners
* registered for this dialog. Has no effect if an identical listener is
* already registered.
*
* @param listener
* a page changing listener
* @since 3.3
*/
public void addPageChangingListener(IPageChangingListener listener) {
pageChangingListeners.add(listener);
}
/**
* Removes the provided page changing listener from the list of page
* changing listeners registered for the dialog.
*
* @param listener
* a page changing listener
* @since 3.3
*/
public void removePageChangingListener(IPageChangingListener listener) {
pageChangingListeners.remove(listener);
}
/**
* Notifies any page changing listeners that the currently selected dialog
* page is changing. Only listeners registered at the time this method is
* called are notified.
*
* @param event
* a selection changing event
*
* @see IPageChangingListener#handlePageChanging(PageChangingEvent)
* @since 3.3
*/
protected void firePageChanging(final PageChangingEvent event) {
Object[] listeners = pageChangingListeners.getListeners();
for (int i = 0; i < listeners.length; ++i) {
final IPageChangingListener l = (IPageChangingListener) listeners[i];
SafeRunnable.run(new SafeRunnable() {
public void run() {
l.handlePageChanging(event);
}
});
}
}
}
| 49,080 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PartAdapter2.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/listener/PartAdapter2.java | package net.heartsome.cat.common.ui.listener;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPartReference;
public class PartAdapter2 implements IPartListener2 {
public void partActivated(IWorkbenchPartReference partRef) {
}
public void partBroughtToTop(IWorkbenchPartReference partRef) {
}
public void partClosed(IWorkbenchPartReference partRef) {
}
public void partDeactivated(IWorkbenchPartReference partRef) {
}
public void partHidden(IWorkbenchPartReference partRef) {
}
public void partInputChanged(IWorkbenchPartReference partRef) {
}
public void partOpened(IWorkbenchPartReference partRef) {
}
public void partVisible(IWorkbenchPartReference partRef) {
}
}
| 715 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PartAdapter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/listener/PartAdapter.java | package net.heartsome.cat.common.ui.listener;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
public class PartAdapter implements IPartListener {
public void partActivated(IWorkbenchPart part) {
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
}
| 446 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ElementTreeSelectionDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/dialog/ElementTreeSelectionDialog.java | package net.heartsome.cat.common.ui.dialog;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
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.Tree;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.internal.WorkbenchMessages;
/**
* A class to select elements out of a tree structure.
*
* @since 2.0
*/
public class ElementTreeSelectionDialog extends SelectionStatusDialog {
private TreeViewer fViewer;
private ILabelProvider fLabelProvider;
private ITreeContentProvider fContentProvider;
private ISelectionStatusValidator fValidator = null;
private ViewerComparator fComparator;
private boolean fAllowMultiple = true;
private boolean fDoubleClickSelects = true;
private String fEmptyListMessage = WorkbenchMessages.ElementTreeSelectionDialog_nothing_available;
private IStatus fCurrStatus = new Status(IStatus.OK, PlatformUI.PLUGIN_ID,
IStatus.OK, "", null); //$NON-NLS-1$
private List fFilters;
private Object fInput;
private boolean fIsEmpty;
private int fWidth = 60;
private int fHeight = 18;
/**
* Constructs an instance of <code>ElementTreeSelectionDialog</code>.
* @param parent The parent shell for the dialog
* @param labelProvider the label provider to render the entries
* @param contentProvider the content provider to evaluate the tree structure
*/
public ElementTreeSelectionDialog(Shell parent,
ILabelProvider labelProvider, ITreeContentProvider contentProvider) {
super(parent);
fLabelProvider = labelProvider;
fContentProvider = contentProvider;
setResult(new ArrayList(0));
setStatusLineAboveButtons(true);
}
/**
* Sets the initial selection.
* Convenience method.
* @param selection the initial selection.
*/
public void setInitialSelection(Object selection) {
setInitialSelections(new Object[] { selection });
}
/**
* Sets the message to be displayed if the list is empty.
* @param message the message to be displayed.
*/
public void setEmptyListMessage(String message) {
fEmptyListMessage = message;
}
/**
* Specifies if multiple selection is allowed.
* @param allowMultiple
*/
public void setAllowMultiple(boolean allowMultiple) {
fAllowMultiple = allowMultiple;
}
/**
* Specifies if default selected events (double click) are created.
* @param doubleClickSelects
*/
public void setDoubleClickSelects(boolean doubleClickSelects) {
fDoubleClickSelects = doubleClickSelects;
}
/**
* Sets the sorter used by the tree viewer.
* @param sorter
* @deprecated as of 3.3, use {@link ElementTreeSelectionDialog#setComparator(ViewerComparator)} instead
*/
public void setSorter(ViewerSorter sorter) {
fComparator = sorter;
}
/**
* Sets the comparator used by the tree viewer.
* @param comparator
* @since 3.3
*/
public void setComparator(ViewerComparator comparator){
fComparator = comparator;
}
/**
* Adds a filter to the tree viewer.
* @param filter a filter.
*/
public void addFilter(ViewerFilter filter) {
if (fFilters == null) {
fFilters = new ArrayList(4);
}
fFilters.add(filter);
}
/**
* Sets an optional validator to check if the selection is valid.
* The validator is invoked whenever the selection changes.
* @param validator the validator to validate the selection.
*/
public void setValidator(ISelectionStatusValidator validator) {
fValidator = validator;
}
/**
* Sets the tree input.
* @param input the tree input.
*/
public void setInput(Object input) {
fInput = input;
}
/**
* Sets the size of the tree in unit of characters.
* @param width the width of the tree.
* @param height the height of the tree.
*/
public void setSize(int width, int height) {
fWidth = width;
fHeight = height;
}
/**
* Validate the receiver and update the ok status.
*
*/
protected void updateOKStatus() {
if (!fIsEmpty) {
if (fValidator != null) {
fCurrStatus = fValidator.validate(getResult());
updateStatus(fCurrStatus);
} else {
fCurrStatus = new Status(IStatus.OK, PlatformUI.PLUGIN_ID,
IStatus.OK, "", //$NON-NLS-1$
null);
}
} else {
fCurrStatus = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID,
IStatus.ERROR, fEmptyListMessage, null);
}
updateStatus(fCurrStatus);
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.window.Window#open()
*/
public int open() {
fIsEmpty = evaluateIfTreeEmpty(fInput);
super.open();
return getReturnCode();
}
private void access$superCreate() {
super.create();
}
/**
* Handles cancel button pressed event.
*/
protected void cancelPressed() {
setResult(null);
super.cancelPressed();
}
/*
* @see SelectionStatusDialog#computeResult()
*/
protected void computeResult() {
setResult(((IStructuredSelection) fViewer.getSelection()).toList());
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.window.Window#create()
*/
public void create() {
BusyIndicator.showWhile(null, new Runnable() {
public void run() {
access$superCreate();
fViewer.setSelection(new StructuredSelection(
getInitialElementSelections()), true);
updateOKStatus();
}
});
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
Label messageLabel = createMessageArea(composite);
TreeViewer treeViewer = createTreeViewer(composite);
GridData data = new GridData(GridData.FILL_BOTH);
data.widthHint = convertWidthInCharsToPixels(fWidth);
data.heightHint = convertHeightInCharsToPixels(fHeight);
Tree treeWidget = treeViewer.getTree();
treeWidget.setLayoutData(data);
treeWidget.setFont(parent.getFont());
if (fIsEmpty) {
messageLabel.setEnabled(false);
treeWidget.setEnabled(false);
}
return composite;
}
/**
* Creates and initializes the tree viewer.
*
* @param parent the parent composite
* @return the tree viewer
* @see #doCreateTreeViewer(Composite, int)
*/
protected TreeViewer createTreeViewer(Composite parent) {
int style = SWT.BORDER | (fAllowMultiple ? SWT.MULTI : SWT.SINGLE);
fViewer = doCreateTreeViewer(parent, style);
fViewer.setContentProvider(fContentProvider);
fViewer.setLabelProvider(fLabelProvider);
fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
access$setResult(((IStructuredSelection) event.getSelection())
.toList());
updateOKStatus();
}
});
fViewer.setComparator(fComparator);
if (fFilters != null) {
for (int i = 0; i != fFilters.size(); i++) {
fViewer.addFilter((ViewerFilter) fFilters.get(i));
}
}
if (fDoubleClickSelects) {
Tree tree = fViewer.getTree();
tree.addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent e) {
updateOKStatus();
if (fCurrStatus.isOK()) {
access$superButtonPressed(IDialogConstants.OK_ID);
}
}
});
}
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
updateOKStatus();
//If it is not OK or if double click does not
//select then expand
if (!(fDoubleClickSelects && fCurrStatus.isOK())) {
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection) {
Object item = ((IStructuredSelection) selection)
.getFirstElement();
if (fViewer.getExpandedState(item)) {
fViewer.collapseToLevel(item, 1);
} else {
fViewer.expandToLevel(item, 1);
}
}
}
}
});
fViewer.setInput(fInput);
return fViewer;
}
/**
* Creates the tree viewer.
*
* @param parent the parent composite
* @param style the {@link SWT} style bits
* @return the tree viewer
* @since 3.4
*/
protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
return new TreeViewer(new Tree(parent, style));
}
/**
* Returns the tree viewer.
*
* @return the tree viewer
*/
protected TreeViewer getTreeViewer() {
return fViewer;
}
private boolean evaluateIfTreeEmpty(Object input) {
Object[] elements = fContentProvider.getElements(input);
if (elements.length > 0) {
if (fFilters != null) {
for (int i = 0; i < fFilters.size(); i++) {
ViewerFilter curr = (ViewerFilter) fFilters.get(i);
elements = curr.filter(fViewer, input, elements);
}
}
}
return elements.length == 0;
}
/**
* Set the result using the super class implementation of
* buttonPressed.
* @param id
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void access$superButtonPressed(int id) {
super.buttonPressed(id);
}
/**
* Set the result using the super class implementation of
* setResult.
* @param result
* @see SelectionStatusDialog#setResult(int, Object)
*/
protected void access$setResult(List result) {
super.setResult(result);
}
/**
* @see org.eclipse.jface.window.Window#handleShellCloseEvent()
*/
protected void handleShellCloseEvent() {
super.handleShellCloseEvent();
//Handle the closing of the shell by selecting the close icon
if (getReturnCode() == CANCEL) {
setResult(null);
}
}
}
| 11,988 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileFolderSelectionDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/dialog/FileFolderSelectionDialog.java | package net.heartsome.cat.common.ui.dialog;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.ide.dialogs.IDEResourceInfoUtils;
import org.eclipse.ui.internal.ide.dialogs.IFileStoreFilter;
/**
* Selection dialog to select files and/or folders on the file system. Use
* setInput to set input to an IFileStore that points to a folder.
* 该类与 org.eclipse.ui.internal.ide.dialogs.FileFolderSelectionDialog 一样,
* 重写该类的目的是删除在选择文件后下方空白处显示的 OK 文本
*
* @since 2.1
*/
public class FileFolderSelectionDialog extends ElementTreeSelectionDialog {
/**
* Label provider for IFileStore objects.
*/
private static class FileLabelProvider extends LabelProvider {
private static final Image IMG_FOLDER = PlatformUI.getWorkbench()
.getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
private static final Image IMG_FILE = PlatformUI.getWorkbench()
.getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
if (element instanceof IFileStore) {
IFileStore curr = (IFileStore) element;
if (curr.fetchInfo().isDirectory()) {
return IMG_FOLDER;
}
return IMG_FILE;
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
if (element instanceof IFileStore) {
return ((IFileStore) element).getName();
}
return super.getText(element);
}
}
/**
* Content provider for IFileStore objects.
*/
private static class FileContentProvider implements ITreeContentProvider {
private static final Object[] EMPTY = new Object[0];
private IFileStoreFilter fileFilter;
/**
* Creates a new instance of the receiver.
*
* @param showFiles
* <code>true</code> files and folders are returned by the
* receiver. <code>false</code> only folders are returned.
*/
public FileContentProvider(final boolean showFiles) {
fileFilter = new IFileStoreFilter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.internal.ide.dialogs.IFileStoreFilter#accept(org.eclipse.core.filesystem.IFileStore)
*/
public boolean accept(IFileStore file) {
if (!file.fetchInfo().isDirectory() && showFiles == false) {
return false;
}
return true;
}
};
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IFileStore) {
IFileStore[] children = IDEResourceInfoUtils.listFileStores(
(IFileStore) parentElement, fileFilter,
new NullProgressMonitor());
if (children != null) {
return children;
}
}
return EMPTY;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
public Object getParent(Object element) {
if (element instanceof IFileStore) {
return ((IFileStore) element).getParent();
}
return null;
}
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
public Object[] getElements(Object element) {
return getChildren(element);
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
/**
* Viewer sorter that places folders first, then files.
*/
private static class FileViewerSorter extends ViewerComparator {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
*/
public int category(Object element) {
if (element instanceof IFileStore
&& !((IFileStore) element).fetchInfo().isDirectory()) {
return 1;
}
return 0;
}
}
/**
* Validates the selection based on the multi select and folder setting.
*/
private static class FileSelectionValidator implements
ISelectionStatusValidator {
private boolean multiSelect;
private boolean acceptFolders;
/**
* Creates a new instance of the receiver.
*
* @param multiSelect
* <code>true</code> if multi selection is allowed.
* <code>false</code> if only single selection is allowed.
* @param acceptFolders
* <code>true</code> if folders can be selected in the
* dialog. <code>false</code> only files and be selected.
*/
public FileSelectionValidator(boolean multiSelect, boolean acceptFolders) {
this.multiSelect = multiSelect;
this.acceptFolders = acceptFolders;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.dialogs.ISelectionStatusValidator#validate(java.lang.Object[])
*/
public IStatus validate(Object[] selection) {
int nSelected = selection.length;
String pluginId = IDEWorkbenchPlugin.IDE_WORKBENCH;
if (nSelected == 0 || (nSelected > 1 && multiSelect == false)) {
return new Status(IStatus.ERROR, pluginId, IStatus.ERROR,
IDEResourceInfoUtils.EMPTY_STRING, null);
}
for (int i = 0; i < selection.length; i++) {
Object curr = selection[i];
if (curr instanceof IFileStore) {
IFileStore file = (IFileStore) curr;
if (acceptFolders == false
&& file.fetchInfo().isDirectory()) {
return new Status(IStatus.ERROR, pluginId,
IStatus.ERROR,
IDEResourceInfoUtils.EMPTY_STRING, null);
}
}
}
return Status.OK_STATUS;
}
}
/**
* Creates a new instance of the receiver.
*
* @param parent
* @param multiSelect
* <code>true</code> if multi selection is allowed.
* <code>false</code> if only single selection is allowed.
* @param type
* one or both of <code>IResource.FILE</code> and
* <code>IResource.FOLDER</code>, ORed together. If
* <code>IResource.FILE</code> is specified files and folders
* are displayed in the dialog. Otherwise only folders are
* displayed. If <code>IResource.FOLDER</code> is specified
* folders can be selected in addition to files.
*/
public FileFolderSelectionDialog(Shell parent, boolean multiSelect, int type) {
super(parent, new FileLabelProvider(), new FileContentProvider(
(type & IResource.FILE) != 0));
setComparator(new FileViewerSorter());
setValidator(new FileSelectionValidator(multiSelect,
(type & IResource.FOLDER) != 0));
setShellStyle(getShellStyle() | SWT.SHEET);
}
}
| 7,195 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelectionStatusDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/dialog/SelectionStatusDialog.java | package net.heartsome.cat.common.ui.dialog;
import java.util.Arrays;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
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.Shell;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.internal.MessageLine;
/**
* An abstract base class for dialogs with a status bar and ok/cancel buttons.
* The status message must be passed over as StatusInfo object and can be
* an error, warning or ok. The OK button is enabled or disabled depending
* on the status.
*
* @since 2.0
*/
public abstract class SelectionStatusDialog extends SelectionDialog {
private MessageLine fStatusLine;
private IStatus fLastStatus;
private Image fImage;
private boolean fStatusLineAboveButtons = false;
/**
* Creates an instance of a <code>SelectionStatusDialog</code>.
* @param parent
*/
public SelectionStatusDialog(Shell parent) {
super(parent);
}
/**
* Controls whether status line appears to the left of the buttons (default)
* or above them.
*
* @param aboveButtons if <code>true</code> status line is placed above buttons; if
* <code>false</code> to the right
*/
public void setStatusLineAboveButtons(boolean aboveButtons) {
fStatusLineAboveButtons = aboveButtons;
}
/**
* Sets the image for this dialog.
* @param image the image.
*/
public void setImage(Image image) {
fImage = image;
}
/**
* Returns the first element from the list of results. Returns <code>null</code>
* if no element has been selected.
*
* @return the first result element if one exists. Otherwise <code>null</code> is
* returned.
*/
public Object getFirstResult() {
Object[] result = getResult();
if (result == null || result.length == 0) {
return null;
}
return result[0];
}
/**
* Sets a result element at the given position.
* @param position
* @param element
*/
protected void setResult(int position, Object element) {
Object[] result = getResult();
result[position] = element;
setResult(Arrays.asList(result));
}
/**
* Compute the result and return it.
*/
protected abstract void computeResult();
/*
* @see Window#configureShell(shell)
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (fImage != null) {
shell.setImage(fImage);
}
}
/**
* Update the dialog's status line to reflect the given status. It is safe to call
* this method before the dialog has been opened.
* @param status
*/
protected void updateStatus(IStatus status) {
fLastStatus = status;
if (fStatusLine != null && !fStatusLine.isDisposed()) {
updateButtonsEnableState(status);
}
}
/**
* Update the status of the ok button to reflect the given status. Subclasses
* may override this method to update additional buttons.
* @param status
*/
protected void updateButtonsEnableState(IStatus status) {
Button okButton = getOkButton();
if (okButton != null && !okButton.isDisposed()) {
okButton.setEnabled(!status.matches(IStatus.ERROR));
}
}
/*
* @see Dialog#okPressed()
*/
protected void okPressed() {
computeResult();
super.okPressed();
}
/*
* @see Window#create()
*/
public void create() {
super.create();
if (fLastStatus != null) {
updateStatus(fLastStatus);
}
}
/*
* @see Dialog#createButtonBar(Composite)
*/
protected Control createButtonBar(Composite parent) {
Font font = parent.getFont();
Composite composite = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
if (!fStatusLineAboveButtons) {
layout.numColumns = 2;
}
layout.marginHeight = 0;
layout.marginLeft = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.marginWidth = 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
composite.setFont(font);
if (!fStatusLineAboveButtons && isHelpAvailable()) {
createHelpControl(composite);
}
fStatusLine = new MessageLine(composite);
fStatusLine.setAlignment(SWT.LEFT);
GridData statusData = new GridData(GridData.FILL_HORIZONTAL);
fStatusLine.setErrorStatus(null);
fStatusLine.setFont(font);
if (fStatusLineAboveButtons && isHelpAvailable()) {
statusData.horizontalSpan = 2;
createHelpControl(composite);
}
fStatusLine.setLayoutData(statusData);
/*
* Create the rest of the button bar, but tell it not to
* create a help button (we've already created it).
*/
boolean helpAvailable = isHelpAvailable();
setHelpAvailable(false);
super.createButtonBar(composite);
setHelpAvailable(helpAvailable);
return composite;
}
}
| 5,465 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HsPreferenceDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/dialog/HsPreferenceDialog.java | /**
* HsPerferenceDialog.java
*
* Version information :
*
* Date:2012-6-12
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui.dialog;
import net.heartsome.cat.common.ui.resource.Messages;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.viewers.TreeViewer;
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.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.IContributionService;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class HsPreferenceDialog extends PreferenceDialog {
public HsPreferenceDialog(Shell parentShell, PreferenceManager manager) {
super(parentShell, manager);
setMinimumPageSize(450, 450);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout parentcomLayout = new GridLayout();
parentcomLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
parentcomLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
parentcomLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
parentcomLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(parentcomLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
applyDialogFont(composite);
GridLayout parentLayout = ((GridLayout) composite.getLayout());
parentLayout.numColumns = 4;
parentLayout.marginHeight = 0;
parentLayout.marginWidth = 0;
parentLayout.verticalSpacing = 0;
parentLayout.horizontalSpacing = 0;
composite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
Control treeControl = createTreeAreaContents(composite);
createSash(composite, treeControl);
Label versep = new Label(composite, SWT.SEPARATOR | SWT.VERTICAL);
GridData verGd = new GridData(GridData.FILL_VERTICAL | GridData.GRAB_VERTICAL);
versep.setLayoutData(verGd);
versep.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true));
Composite pageAreaComposite = new Composite(composite, SWT.NONE);
pageAreaComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout(1, true);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
pageAreaComposite.setLayout(layout);
// Build the Page container
Composite pageContainer = createPageContainer(pageAreaComposite);
GridData pageContainerData = new GridData(GridData.FILL_BOTH);
pageContainerData.horizontalIndent = IDialogConstants.HORIZONTAL_MARGIN;
pageContainer.setLayoutData(pageContainerData);
super.setPageContainer(pageContainer);
// Build the separator line
Label bottomSeparator = new Label(parent, SWT.HORIZONTAL | SWT.SEPARATOR);
bottomSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
return composite;
}
@Override
protected Control createTreeAreaContents(Composite parent) {
// 创建左侧树
Control result = super.createTreeAreaContents(parent);
TreeViewer treeViewer = getTreeViewer();
// 设置排序器
IContributionService cs = (IContributionService) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getService(IContributionService.class);
treeViewer.setComparator(cs.getComparatorFor(IContributionService.TYPE_PREFERENCE));
treeViewer.expandAll(); // 展开所有
return result;
}
public void setErrorMessage(String newErrorMessage) {
}
public void setMessage(String newMessage, int newType) {
}
public void updateMessage() {
}
public void updateTitle() {
}
}
| 4,618 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InnerTagUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/utils/InnerTagUtil.java | package net.heartsome.cat.common.ui.utils;
import static net.heartsome.cat.common.ui.innertag.PlaceHolderNormalModeBuilder.PATTERN;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.Matcher;
import net.heartsome.cat.common.innertag.InnerTagBean;
import net.heartsome.cat.common.innertag.TagStyle;
import net.heartsome.cat.common.innertag.TagType;
import net.heartsome.cat.common.innertag.factory.IInnerTagFactory;
import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder;
import net.heartsome.cat.common.innertag.factory.XliffInnerTagFactory;
import net.heartsome.cat.common.ui.innertag.PlaceHolderNormalModeBuilder;
import org.eclipse.jface.text.Position;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Display;
/**
* 内部标记工具类,本类只操作文本,标记着色的部分请参看 {@link innertagC}
* <p>
* 此类中有几个概念需要注意:
* <li>XmlTag: XML 格式的标记</li>
* <li>StyledTag: 显示在 UI 上的标记样式</li>
* <li>XmlValue: 源语言或目标语言的 XML 格式的值(XLIFF 文件中的值)</li>
* <li>DisplayValue: 源语言或目标语言的添加了标记样式的显示文本(UI 上的显示值)</li>
* </p>
* @author weachy
* @since JDK1.5
*/
public class InnerTagUtil {
private static PlaceHolderNormalModeBuilder placeHolderCreater = new PlaceHolderNormalModeBuilder();;
private InnerTagUtil() {
// Color borderColor = new Color(Display.getCurrent(), 0, 255, 255);
// Color textBgColor = new Color(Display.getCurrent(), 0, 205, 205);
// Color inxBgColor = new Color(Display.getCurrent(), 0, 139, 139);
// Color textFgColor = new Color(Display.getCurrent(), 0, 104, 139);
// Color inxFgColor = borderColor;
// Font font = new Font(Display.getDefault(), "宋体", 10, SWT.NORMAL);
}
/** 标记字体 */
public static Font tagFont = getTagFont();
private static Font getTagFont() {
return new Font(Display.getDefault(), "Arial", 8, SWT.BOLD);
}
/**
* 将带内部标记的文本由XML格式转换为显示格式的文本
* @param originalValue
* 原始的带内部标记的XML格式的文本
* @return ;
*/
public static TreeMap<String, InnerTagBean> parseXmlToDisplayValue(StringBuffer originalValue, TagStyle style) {
// 得到标签映射map(key: 内部标记;value: 内部标记实体)
TreeMap<String, InnerTagBean> tags = new TreeMap<String, InnerTagBean>(new Comparator<String>() {
public int compare(String str1, String str2) {
int num1 = InnerTagUtil.getStyledTagNum(str1);
int num2 = InnerTagUtil.getStyledTagNum(str2);
if (num1 == num2) {
return str1.indexOf(String.valueOf(num1)) - str2.indexOf(String.valueOf(num1));
}
return num1 - num2;
}
});
if (originalValue == null || originalValue.length() == 0) {
return tags;
}
placeHolderCreater.setStyle(style);
IInnerTagFactory innerTagFactory = new XliffInnerTagFactory(originalValue.toString(), placeHolderCreater);
originalValue.replace(0, originalValue.length(), innerTagFactory.getText()); // 提取标记之后的文本。
List<InnerTagBean> innerTagBeans = innerTagFactory.getInnerTagBeans();
if (innerTagBeans != null && innerTagBeans.size() > 0) {
for (int i = 0; i < innerTagBeans.size(); i++) {
String placeHolder = placeHolderCreater.getPlaceHolder(innerTagBeans, i);
tags.put(placeHolder, innerTagBeans.get(i));
// originalValue.replace(innerTagBean.getOffset(), innerTagBean.getOffset(), innerTag.toString());
}
}
return tags;
}
public static final char INVISIBLE_CHAR = '\u200A'; // 不可见字符(此字符为:不换行空格)
/**
* 根据 source 的内容显示内部标记
* @param originalValue
* 原始值
* @param srcOriginalValue
* Source 值
* @return ;
*/
public static Map<String, InnerTagBean> parseXmlToDisplayValueFromSource(String source, StringBuffer originalValue,
TagStyle style) {
// 得到标签映射map(key: 内部标记;value: 内部标记实体)
TreeMap<String, InnerTagBean> tags = new TreeMap<String, InnerTagBean>(new Comparator<String>() {
public int compare(String str1, String str2) {
int num1 = InnerTagUtil.getStyledTagNum(str1);
int num2 = InnerTagUtil.getStyledTagNum(str2);
if (num1 == num2) {
return str1.indexOf(String.valueOf(num1)) - str2.indexOf(String.valueOf(num1));
}
return num1 - num2;
}
});
if (originalValue == null || originalValue.length() == 0) {
return tags;
}
placeHolderCreater.setStyle(style);
IInnerTagFactory innerTagFactory = new XliffInnerTagFactory(source, placeHolderCreater);
List<InnerTagBean> sourceInnerTagBeans = innerTagFactory.getInnerTagBeans();
if (sourceInnerTagBeans != null && sourceInnerTagBeans.size() > 0) {
int index = -1;
for (int i = 0; i < sourceInnerTagBeans.size(); i++) {
InnerTagBean innerTagBean = sourceInnerTagBeans.get(i);
String placeHolder = placeHolderCreater.getPlaceHolder(sourceInnerTagBeans, i);
tags.put(placeHolder, innerTagBean);
// String xml1 = FindReplaceDocumentAdapter.escapeForRegExPattern(entry.getValue());
String xml = innerTagBean.getContent();
if ((index = originalValue.indexOf(xml, index)) != -1) { // 替换 Source 中存在的标记
originalValue.replace(index, index + xml.length(), placeHolder);
index += placeHolder.length();
}
}
}
String target = innerTagFactory.parseInnerTag(originalValue.toString()); // 替换目标文本中的错误标记
originalValue.replace(0, originalValue.length(), target);
return tags;
}
/**
* 将InnerTag转换回XML格式的标记
* @param text
* @return ;
*/
public static String parseDisplayToXmlValue(Map<String, InnerTagBean> tags, String text) {
StringBuffer sb = new StringBuffer(text);
for (Entry<String, InnerTagBean> entry : tags.entrySet()) {
String innerTag = entry.getKey();
String xmlTag = entry.getValue().getContent();
int index = -1;
while ((index = sb.indexOf(innerTag, index + 1)) > -1) {
sb.replace(index, index + innerTag.length(), xmlTag);
}
}
return sb.toString();
}
/**
* 转义“<”、“>”为“&lt;”、“&gt;”
* @param source
* 源文本
* @return 转义后的文本;
*/
public static String escapeTag(String source) {
return source.replace("&", "&").replace("<", "<").replace(">", ">");
}
/**
* 转义“&lt;”、“&gt;”为“<”、“>”
* @param source
* 源文本
* @return 转义后的文本;
*/
public static String resolveTag(String source) {
return source.replace("<", "<").replace(">", ">").replace("&", "&");
}
/**
* 得到内部标记的类型。
* @param innerTag
* 内部标记
* @return ;
*/
public static TagType getStyledTagType(String innerTag) {
int num = getStyledTagNum(innerTag);
String tagStartIndex = PlaceHolderNormalModeBuilder.createStyledTagStartIndex(num).toString();
String tagEndIndex = PlaceHolderNormalModeBuilder.createStyledTagEndIndex(num).toString();
if (innerTag.startsWith(tagStartIndex) && innerTag.endsWith(tagEndIndex)) {
return TagType.STANDALONE;
} else if (innerTag.startsWith(tagStartIndex)) {
return TagType.START;
} else if (innerTag.endsWith(tagEndIndex)) {
return TagType.END;
}
return null;
}
/**
* 得到内部标记索引号。
* @param innerTag
* 内部标记
* @return ;
*/
public static int getStyledTagNum(String innerTag) {
int res = 0;
for (int i = 0; i < innerTag.length(); i++) {
char ch = innerTag.charAt(i);
if (Character.isDigit(ch)) {
res = res * 10 + Integer.parseInt(String.valueOf(ch));
} else {
if (res > 0) {
return res;
}
}
}
return -1;
}
/**
* 获取忽略标记的值
* @param displayValue
* 带标记样式的文本。
* @return ;
*/
public static String getDisplayValueWithoutTags(String displayValue) {
StringBuffer t = new StringBuffer(displayValue);
Position[] tagRanges = getStyledTagRanges(displayValue);
for (int i = tagRanges.length - 1; i >= 0; i--) {
Position tagRange = tagRanges[i];
t.delete(tagRange.getOffset(), tagRange.getOffset() + tagRange.getLength());
}
return t.toString();
}
// private static Pattern PATTERN = Pattern.compile("(" + INVISIBLE_CHAR + "\\d+)?" + INVISIBLE_CHAR
// + "(x|bx|ex|g|bpt|ept|mrk|sub|ph|it)" + INVISIBLE_CHAR + "(\\d+" + INVISIBLE_CHAR + ")?");
/**
* 得到一段带标记样式的文本中,指定位置上的标记的索引范围。
* @param tagStyledText
* 带标记样式的文本。
* @param offset
* @return 若指定位置上不存在标记,则返回 null;
*/
public static Position getStyledTagRange(String tagStyledText, int offset) {
Matcher m = PATTERN.matcher(tagStyledText);
while (m.find()) {
int start = m.start();
int end = m.end();
if (start < offset && offset < end) {
return new Position(start, end - start);
}
}
return null;
}
/**
* 得到一段带标记样式的文本中所有标记的索引范围。
* @param tagStyledText
* 带标记样式的文本。
* @return ;
*/
public static Position[] getStyledTagRanges(String tagStyledText) {
Matcher m = PlaceHolderEditModeBuilder.PATTERN.matcher(tagStyledText);
ArrayList<Position> positions = new ArrayList<Position>();
while (m.find()) {
int start = m.start();
int end = m.end();
positions.add(new Position(start, end - start));
}
return positions.toArray(new Position[] {});
}
/**
* 得到一段带标记样式的文本中所有的标记。
* @param tagStyledText
* 带标记样式的文本。
* @return ;
*/
public static String[] getStyledTags(String tagStyledText) {
Matcher m = PlaceHolderEditModeBuilder.PATTERN.matcher(tagStyledText);
ArrayList<String> tags = new ArrayList<String>();
while (m.find()) {
int start = m.start();
int end = m.end();
tags.add(tagStyledText.substring(start, end));
}
return tags.toArray(new String[] {});
}
}
| 10,319 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenMessageUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/utils/OpenMessageUtils.java | /**
* OpenMessageUtils.java
*
* Version information :
*
* Date:2013-5-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.ui.Activator;
import net.heartsome.cat.common.ui.resource.Messages;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* 消息处理工具类,弹出消息提示给用户。
* @author Jason
* @version 1.0
* @since JDK1.6
*/
public final class OpenMessageUtils {
/**
* 弹出错误、警告或消息对话框
* @param severity
* 必须是 <code>IStatus.ERROR<code>,<code>IStatus.WARNING<code>,<code>IStatus.INFO<code>三者之一
* @param message
* 错误、警告或消息的文本信息,不能为null或空串;
*/
public static void openMessage(int severity, String message) {
IStatus status = getIStatus(severity, message);
String title = getMessageDlgTitle(severity);
if (title == null) {
return;
}
ErrorDialog.openError(Display.getCurrent().getActiveShell(), title, null, status);
}
/**
* 弹出 确认对话框 robert 2013-06-18
* @param message
* @return
*/
public static boolean openConfirmMessage(String message){
return MessageDialog.openConfirm(Display.getDefault().getActiveShell(),
Messages.getString("utils.OpenMesssageUtils.messageDialog.confirmTitle"), message);
}
/**
* 弹出错误或警告对话框,需要提供错误或警告的文本原因信息
* @param severity
* 必须是<code>IStatus.ERROR<code>,<code>IStatus.WARNING<code>
* @param message
* 错误、警告的文本信息,不能为null或空串;
* @param reasonMsg
* 错误或警告的文本原因信息,不能为null或空串;
*/
public static void openMessageWithReason(int severity, String message, String reasonMsg) {
Assert.isLegal(severity == IStatus.ERROR || severity == IStatus.WARNING);
Assert.isLegal(message != null && message.length() > 0);
IStatus status = getIStatus(severity, reasonMsg);
String title = getMessageDlgTitle(severity);
if (title == null) {
return;
}
ErrorDialog.openError(new Shell(Display.getDefault()), title, message, status);
}
/**
* 弹出错误或警告对话框,需要提供错误或警告的文本原因信息以及详细的异常<code>Throwable<code>
* @param message
* 错误或警告的文本信息,不能为null或空串
* @param reasonMsg
* 错误、警告的文本原因信息,不能为null或空串
* @param throwable
* <code>Throwable<code> 对象,错误或警告的详细异常信息;
*/
public static void openErrorMsgWithDetail(String message, String reasonMsg, Throwable throwable) {
Assert.isLegal(message != null && message.length() > 0);
Assert.isLegal(reasonMsg != null && reasonMsg.length() > 0);
Assert.isLegal(throwable != null);
IStatus status = throwable2MultiStatus(reasonMsg, throwable);
String title = getMessageDlgTitle(IStatus.ERROR);
if (title == null) {
return;
}
ErrorDialog.openError(new Shell(Display.getDefault()), title, message, status);
}
private static String getMessageDlgTitle(int severity) {
String title = null;
switch (severity) {
case IStatus.ERROR:
title = Messages.getString("utils.OpenMesssageUtils.messageDialog.ErrorTitle");
break;
case IStatus.WARNING:
title = Messages.getString("utils.OpenMesssageUtils.messageDialog.Warningtitle");
break;
case IStatus.INFO:
title = Messages.getString("utils.OpenMesssageUtils.messageDialog.Infotitle");
break;
default:
break;
}
return title;
}
private static IStatus getIStatus(int severity, String message) {
Assert.isLegal(severity == IStatus.ERROR || severity == IStatus.WARNING || severity == IStatus.INFO);
Assert.isLegal(message != null && message.length() > 0);
IStatus status = new Status(severity, Activator.PLUGIN_ID, message);
return status;
}
/**
* 将<code>Throwable<code>转化成<code>MultiStatus<code>对象,
* 让<code>MultiStatus<code>对象包含详细的<code>Throwable<code>详细的堆栈信息。
* @param message
* <code>MultiStatus<code>对象的消息
* @param throwable
* 异常对象
* @return 包含有详细的堆栈信息的<code>MultiStatus<code>对象;
*/
public static MultiStatus throwable2MultiStatus(String message, Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
// stack trace as a string
final String trace = sw.toString();
// Temp holder of child statuses
List<Status> childStatuses = new ArrayList<Status>();
// Split output by OS-independend new-line
String[] lines = trace.split(System.getProperty("line.separator")); //$NON-NLS-N$
int j = lines.length == 1 ? 0 : 1;
for (int i = j; i < lines.length; i++) {
String line = lines[i];
// build & add status
childStatuses.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, line));
}
// convert to array of statuses
MultiStatus ms = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, childStatuses.toArray(new Status[] {}),
message, throwable);
return ms;
}
/**
* Private constructor. Prevent instance
*/
private OpenMessageUtils() {
}
}
| 6,372 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenEditorUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/utils/OpenEditorUtil.java | package net.heartsome.cat.common.ui.utils;
import java.io.File;
import java.net.URI;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
/**
* 打开系统编辑器的工具类
* @author weachy
* @version
* @since JDK1.5
*/
public class OpenEditorUtil {
/**
* 使用系统默认编辑器打开文件
* @param filePath
* 文件路径;
*/
public static void OpenFileWithSystemEditor(String filePath) {
OpenFileWithSystemEditor(new File(filePath).toURI());
}
/**
* 使用系统默认编辑器打开文件
* @param page
* IWorkbenchPage 对象
* @param filePath
* 文件路径;
*/
public static void OpenFileWithSystemEditor(IWorkbenchPage page, String filePath) {
OpenFileWithSystemEditor(page, new File(filePath).toURI());
}
/**
* 使用系统默认编辑器打开文件
* @param uri
* ;
*/
public static void OpenFileWithSystemEditor(URI uri) {
OpenFileWithSystemEditor(getCurrentPage(), uri);
}
/**
* 使用系统默认编辑器打开文件
* @param page
* IWorkbenchPage 对象
* @param uri
* ;
*/
public static void OpenFileWithSystemEditor(IWorkbenchPage page, URI uri) {
try {
IDE.openEditor(page, uri, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID, true);
} catch (PartInitException e) {
e.printStackTrace();
}
}
/**
* 使用系统默认编辑器打开文件
* @param file
* IFile 对象(工作空间内的文件);
*/
public static void OpenFileWithSystemEditor(IFile file) {
try {
IDE.openEditor(getCurrentPage(), file, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
} catch (PartInitException e) {
e.printStackTrace();
}
}
/**
* 得到当前的 IWorkbenchPage 对象
* @return ;
*/
private static IWorkbenchPage getCurrentPage() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
}
| 2,083 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenViewHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/handlers/OpenViewHandler.java | /**
* OpenViewHandler.java
*
* Version information :
*
* Date:Jan 27, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.common.ui.handlers;
import java.util.Map;
import net.heartsome.cat.common.ui.Activator;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.menus.UIElement;
/**
* 打开视图的 Handler,视图 ID 作为参数在 plugin.xml 中指定。
* 修改handler类,切换查看菜单的图标,--robert 2012-03-20
*/
public class OpenViewHandler extends AbstractHandler implements IElementUpdater {
/**
* the command has been executed, so extract extract the needed information from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
String viewId = event.getParameter("ViewId");
if (viewId == null) {
return null;
}
IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IViewPart view = workbenchPage.findView(viewId);
if (view == null) {
try {
workbenchPage.showView(viewId);
} catch (PartInitException e) {
e.printStackTrace();
}
} else {
workbenchPage.hideView(view);
}
// ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
// commandService.refreshElements(event.getCommand().getId(), null);
return null;
}
@SuppressWarnings("rawtypes")
public void updateElement(final UIElement element, Map parameters) {
if (parameters.get("ViewId") == null) {
return;
}
final String viewId = (String) parameters.get("ViewId");
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null) {
return;
}
IWorkbenchPage workbenchPage = window.getActivePage();
if (workbenchPage == null) {
return;
}
IViewPart view = workbenchPage.findView(viewId);
if (view == null) {
element.setIcon(Activator.getImageDescriptor("icons/disabled_co.png"));
} else {
element.setIcon(Activator.getImageDescriptor("icons/enabled_co.png"));
}
}
});
}
}
| 2,565 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractSelectProjectFilesHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/handlers/AbstractSelectProjectFilesHandler.java | package net.heartsome.cat.common.ui.handlers;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.ui.resource.Messages;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 处理多选(在同一个项目中的)文件。支持选中项目、文件夹、文件。
* @author weachy
* @version
* @since JDK1.5
*/
public abstract class AbstractSelectProjectFilesHandler extends AbstractHandler {
public static final Logger LOGGER = LoggerFactory.getLogger(AbstractSelectProjectFilesHandler.class);
protected Shell shell;
/** 所选中的是否是编辑器 */
protected boolean isEditor;
public Object execute(ExecutionEvent event) throws ExecutionException {
shell = HandlerUtil.getActiveShell(event);
isEditor = false;
// UNDO 如果焦点在其他视图上时,获取的文件错误。
ISelection selection = HandlerUtil.getCurrentSelectionChecked(event);
if (selection == null || !(selection instanceof StructuredSelection) || selection.isEmpty()) {
MessageDialog.openInformation(shell,
Messages.getString("handlers.AbstractSelectProjectFilesHandler.msgTitle"),
Messages.getString("handlers.AbstractSelectProjectFilesHandler.msg1"));
return null;
}
StructuredSelection structuredSelection = (StructuredSelection) selection;
IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
String partId = HandlerUtil.getActivePartIdChecked(event);
if (part instanceof IEditorPart) { // 当前焦点在编辑器
IEditorInput editorInput = ((IEditorPart) part).getEditorInput();
IFile iFile = (IFile) editorInput.getAdapter(IFile.class);
isEditor = true;
ArrayList<IFile> list = new ArrayList<IFile>();
list.add(iFile); //代替 Arrays.asList(iFile)
return execute(event, list);
} else if ("net.heartsome.cat.common.ui.navigator.view".equals(partId)) { // 当前焦点在导航视图
ArrayList<IFile> list = new ArrayList<IFile>();
ArrayList<IFile> wrongFiles = new ArrayList<IFile>();
String projectName = null;
@SuppressWarnings("unchecked")
Iterator<IResource> iterator = structuredSelection.iterator();
while (iterator.hasNext()) {
IResource resource = iterator.next();
if (projectName == null) {
projectName = resource.getProject().getName();
} else {
if (!projectName.equals(resource.getProject().getName())) {
MessageDialog.openInformation(shell,
Messages.getString("handlers.AbstractSelectProjectFilesHandler.msgTitle"),
Messages.getString("handlers.AbstractSelectProjectFilesHandler.msg2"));
return null;
}
}
if (resource instanceof IFile) {
IFile file = (IFile) resource;
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);
}
}
} else if (resource instanceof IContainer) { // IContainer 包含 IFolder、IPorject。
try {
ResourceUtils.getFiles((IContainer) resource, list, getLegalFileExtensions());
} catch (CoreException e) {
LOGGER.error(MessageFormat.format(Messages
.getString("handlers.AbstractSelectProjectFilesHandler.msg3"), resource.getFullPath()
.toOSString()), e);
e.printStackTrace();
}
}
}
if (!wrongFiles.isEmpty()) {
String msg = Messages.getString("handlers.AbstractSelectProjectFilesHandler.msg4");
StringBuffer arg = new StringBuffer();
for (IFile iFile : wrongFiles) {
arg.append("\n").append(iFile.getFullPath().toOSString());
}
if (!MessageDialog.openConfirm(shell,
Messages.getString("handlers.AbstractSelectProjectFilesHandler.msgTitle"), MessageFormat.format(msg.toString(), arg.toString()))) {
return null;
}
}
return execute(event, list);
}
return null;
}
/**
* 获取合法的文件后缀名
* @return ;
*/
public abstract String[] getLegalFileExtensions();
/**
* 同 {@link #execute(ExecutionEvent)}
* @param event
* @param list
* 选中的文件列表。
* @return ;
*/
public abstract Object execute(ExecutionEvent event, List<IFile> list);
}
| 5,322 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PlaceHolderNormalModeBuilder.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/innertag/PlaceHolderNormalModeBuilder.java | package net.heartsome.cat.common.ui.innertag;
import static net.heartsome.cat.common.ui.utils.InnerTagUtil.INVISIBLE_CHAR;
import java.util.List;
import java.util.regex.Pattern;
import net.heartsome.cat.common.innertag.InnerTagBean;
import net.heartsome.cat.common.innertag.TagStyle;
import net.heartsome.cat.common.innertag.TagType;
import net.heartsome.cat.common.innertag.factory.IPlaceHolderBuilder;
import org.eclipse.core.runtime.Assert;
public class PlaceHolderNormalModeBuilder implements IPlaceHolderBuilder {
private static String BLANK_CHARACTER = "\u2006";
public static Pattern PATTERN = Pattern.compile(BLANK_CHARACTER + "(" + INVISIBLE_CHAR + "\\d+)?" + INVISIBLE_CHAR
+ "?((x|bx|ex|ph|g|bpt|ept|ph|it|mrk|sub)"+
"|(<(x|bx|ex|ph|bpt|ept|ph|it|mrk|sub)\\s*(\\w*\\s*=\\s*('|\")(.|\n)*('|\"))*>?(.|\n)*<?/(x|bx|ex|ph|bpt|ept|ph|it|mrk|sub)?>)"+
"|(<g(\\s*\\w*\\s*=\\s*('|\")(.|\n)*('|\"))*>)|</g>)?"
+ INVISIBLE_CHAR + "?(\\d+" + INVISIBLE_CHAR + ")?" + BLANK_CHARACTER+"?");
private TagStyle style;
/**
* 得到内部标记的占位符。
* @param innerTagBeans
* 内部标记集合(不能为null)
* @param index
* 当前标记所在索引
* @return 内部标记占位符;
*/
public String getPlaceHolder(List<InnerTagBean> innerTagBeans, int index) {
Assert.isNotNull(innerTagBeans);
InnerTagBean innerTagBean = innerTagBeans.get(index);
int tagIndex = innerTagBean.getIndex();
StringBuffer tagContent = new StringBuffer();
StringBuffer innerTag = new StringBuffer();
if (innerTagBean.getType() == TagType.START) {
StringBuffer id = createStyledTagStartIndex(tagIndex);
if (style == TagStyle.SIMPLE || style == TagStyle.INDEX) {
innerTag.append(id);
if (style == TagStyle.SIMPLE) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getName()).append(INVISIBLE_CHAR);
innerTag.append(tagContent); // 形如“|_1| g_|” (“_”代指不可见字符)
}
} else if (style == TagStyle.FULL) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getContent()).append(INVISIBLE_CHAR);
innerTag.append(id).append(tagContent);// 形如“|_1| g_|” (“_”代指不可见字符)
}
} else if (innerTagBean.getType() == TagType.END) {
StringBuffer id = createStyledTagEndIndex(tagIndex);
if (style == TagStyle.SIMPLE || style == TagStyle.INDEX) {
if (style == TagStyle.SIMPLE) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getName()).append(INVISIBLE_CHAR);
innerTag.append(tagContent); // 形如“|_1| g_|” (“_”代指不可见字符)
}
innerTag.append(id);
} else if (style == TagStyle.FULL) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getContent()).append(INVISIBLE_CHAR);
innerTag.append(tagContent).append(id);
}
} else if (innerTagBean.getType() == TagType.STANDALONE) {
StringBuffer id = createStyledTagStartIndex(tagIndex);
StringBuffer endId = createStyledTagEndIndex(tagIndex);
if (style == TagStyle.SIMPLE || style == TagStyle.INDEX) {
innerTag.append(id);
if (style == TagStyle.SIMPLE) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getName()).append(INVISIBLE_CHAR);
innerTag.append(tagContent).append(endId);// 形如“|_1| ph |1_|”;(“_”代指不可见字符)
}
} else if (style == TagStyle.FULL) {
tagContent.append(INVISIBLE_CHAR).append(innerTagBean.getContent()).append(INVISIBLE_CHAR);
innerTag.append(id).append(tagContent).append(endId);
}
}
return innerTag.insert(0, BLANK_CHARACTER).append(BLANK_CHARACTER).toString();
}
/**
* 此方法暂时无使用价值,无实现。
* @see net.heartsome.cat.common.innertag.factory.IPlaceHolderBuilder#getIndex(java.lang.String)
*/
public int getIndex(List<InnerTagBean> innerTagBeans, String placeHolder) {
// TODO 显示模式下此方法暂时用不到,不做实现
return -1;
}
/**
* 得到开始部分的标记索引
* @param index
* 标记索引号
* @return ;
*/
public static StringBuffer createStyledTagStartIndex(int index) {
return new StringBuffer().append(INVISIBLE_CHAR).append(index);
}
/**
* 得到结尾部分的标记索引
* @param index
* 标记索引号
* @return ;
*/
public static StringBuffer createStyledTagEndIndex(int index) {
return new StringBuffer().append(index).append(INVISIBLE_CHAR);
}
public void setStyle(TagStyle style) {
this.style = style;
}
}
| 4,519 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InnerTag.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/innertag/InnerTag.java | package net.heartsome.cat.common.ui.innertag;
import net.heartsome.cat.common.innertag.InnerTagBean;
import net.heartsome.cat.common.innertag.TagStyle;
import net.heartsome.cat.common.innertag.TagType;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Widget;
public class InnerTag extends Canvas {
/** 此 Style 用来加快内部标记重绘的速度,以及消除闪屏现象 */
private static final int DEFAULT_STYLE_OPTIONS = SWT.NO_REDRAW_RESIZE | SWT.DOUBLE_BUFFERED;
// private static final int LINE_WIDTH = 1; // 线宽
private InnerTagBean innerTagBean;
// private Point tagSize;
//
// private Color bgColor;
// private Color fgColor;
private boolean isSelected = false;
private InnerTagRender tagRender;
/**
* 构造一个内部标记组件。
* @param parent
* 父容器。
* @param style
* 组件样式。参见 SWT 组件样式相关内容:{@link Widget#getStyle()}、{@link SWT}。
* @param tagContent
* 标记内容。
* @param tagName
* 标记名称。
* @param tagIndex
* 标记索引。
* @param tagType
* 标记类型。
* @param tagStyle
* 标记样式。
*/
public InnerTag(Composite parent, int style, String tagContent, String tagName, int tagIndex, TagType tagType,
TagStyle tagStyle) {
this(parent, style, new InnerTagBean(tagIndex, tagName, tagContent, tagType), tagStyle);
}
/**
* 构造一个内部标记组件。
* @param parent
* 父容器。
* @param style
* 组件样式。参见 SWT 组件样式相关内容:{@link Widget#getStyle()}、{@link SWT}。
* @param innerTagBean
* 内部标记实体
* @param tagStyle
* 标记样式。
*/
public InnerTag(Composite parent, int style, InnerTagBean innerTagBean, TagStyle tagStyle) {
super(parent, style | DEFAULT_STYLE_OPTIONS);
this.setInnerTagBean(innerTagBean);
this.setToolTipText(resetRegularString(innerTagBean.getContent()));
this.setBackground(parent.getBackground());
tagRender = new InnerTagRender(this);
init();
}
private String resetRegularString(String input) {
input = input.replaceAll("&", "&");
input = input.replaceAll("<", "<");
input = input.replaceAll(">", ">");
input = input.replaceAll(""", "\"");
return input;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof InnerTag)) {
return false;
}
InnerTag that = (InnerTag) obj;
return this.getInnerTagBean().equals(that.getInnerTagBean());
}
/**
* 计算标记组件尺寸。参见 Control 组件的 computeSize 方法。
* @param wHint
* 组件宽度
* @param hHint
* 组件高度
* @param changed
* 尺寸是否可变
*/
@Override
public Point computeSize(int wHint, int hHint, boolean changed) {
Point p = tagRender.calculateTagSize(innerTagBean);
// return super.computeSize(p.x, p.y, changed);
return p;
}
// 初始化组件。
private void init() {
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
tagRender.draw(e.gc, innerTagBean, 0, 0);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
Control parent = getParent();
if(parent instanceof StyledText){
StyledText text = (StyledText) parent;
Point size = getSize();
Point p = getLocation();
int offset = text.getOffsetAtLocation(p);
int mouseX = e.x;
if(mouseX > size.x / 2 ){
text.setCaretOffset(offset + 1);
} else {
text.setCaretOffset(offset);
}
}
}
});
}
public boolean isSelected() {
return isSelected;
};
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
/**
* 各种标记绘制样式效果。
* @param args
* ;
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(800, 600);
GridLayout gl = new GridLayout();
shell.setLayout(gl);
//
// Color borderColor = new Color(display, 0, 255, 255);
// Color textBgColor = new Color(display, 0, 205, 205);
// Color indexBgColor = new Color(display, 0, 139, 139);
// Color textFgColor = new Color(display, 0, 104, 139);
// Color indexFgColor = borderColor;
//
// Font font = new Font(Display.getDefault(), "Arial", 8, SWT.BOLD);
//
// InnerTag tag1 = new InnerTag(shell, SWT.NONE, "<ph id=\"1\" /><this>& is a ph text.</ph>", "ph",
// 4333,
// STANDALONE, FULL);
// tag1.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag1.setFont(font);
// tag1.pack();
//
// InnerTag tag2 = new InnerTag(shell, SWT.NONE, "<ph id=\"2\" />this is a ph text.</ph>", "ph", 2, STANDALONE,
// SIMPLE);
// tag2.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag2.setFont(font);
// tag2.pack();
//
// InnerTag tag3 = new InnerTag(shell, SWT.NONE, "<ph id=\"3\" />this is a ph text.</ph>", "ph", 3, STANDALONE,
// INDEX);
// tag3.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag3.setFont(font);
// tag3.pack();
//
// InnerTag tag4 = new InnerTag(shell, SWT.NONE, "<bx id=\"1\" />", "bx", 4, START, FULL);
// tag4.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag4.setFont(font);
// tag4.pack();
//
// InnerTag tag5 = new InnerTag(shell, SWT.NONE, "<bx id=\"2\" />", "bx", 5, START, SIMPLE);
// tag5.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag5.setFont(font);
// tag5.pack();
//
// InnerTag tag6 = new InnerTag(shell, SWT.NONE, "<bx id=\"3\" />", "bx", 6, START, INDEX);
// tag6.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag6.setFont(font);
// tag6.pack();
//
// InnerTag tag7 = new InnerTag(shell, SWT.NONE, "<ex id=\"3\" />", "ex", 6, END, INDEX);
// tag7.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag7.setFont(font);
// tag7.pack();
//
// InnerTag tag8 = new InnerTag(shell, SWT.NONE, "<ex id=\"2\" />", "ex", 5, END, SIMPLE);
// tag8.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag8.setFont(font);
// tag8.pack();
// //
// InnerTagControl tag9 = new InnerTagControl(shell, SWT.NONE, "", "", 4, STANDALONE, TagStyle.FULL);
// tag9.initColor(textFgColor, textBgColor, indexFgColor, indexBgColor, borderColor);
// tag9.setFont(font);
// tag9.pack();
//
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
public void setInnerTagBean(InnerTagBean innerTagBean) {
this.innerTagBean = innerTagBean;
}
public InnerTagBean getInnerTagBean() {
return innerTagBean;
}
}
| 7,518 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InnerTagRender.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/innertag/InnerTagRender.java | /**
* InnerTagRender.java
*
* Version information :
*
* Date:2013-3-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.ui.innertag;
import net.heartsome.cat.common.bean.ColorConfigBean;
import net.heartsome.cat.common.innertag.InnerTagBean;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* 内部标记渲染器
* @author Jason
* @version
* @since JDK1.6
*/
public class InnerTagRender {
/** 标记字体 */
private static Font TAG_FONT = new Font(Display.getDefault(), "Arial", 7, SWT.BOLD);
private static final int MARGIN_H = 2; // 文本的水平边距
private static final int MARGIN_V = 2; // 文本的垂直边距
private InnerTag tag;
public static void main(String[] args) {
Display ds = Display.getDefault();
Shell shell = new Shell(ds);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!ds.readAndDispatch()) {
ds.sleep();
}
}
}
public InnerTagRender() {
}
public InnerTagRender(InnerTag tag) {
this.tag = tag;
}
public Point calculateTagSize(InnerTagBean innerTagBean) {
GC gc = new GC(Display.getDefault());
gc.setFont(TAG_FONT);
Point tempSize = gc.textExtent(String.valueOf(innerTagBean.getIndex()));
// System.out.println("textSize: "+ tempSize);
Point tagSize = new Point(tempSize.x + MARGIN_H * 2, tempSize.y + MARGIN_V * 2);
int sawtooth = tagSize.y / 2;
switch (innerTagBean.getType()) {
case STANDALONE:
tagSize.x += tagSize.y;
break;
default:
tagSize.x += sawtooth;
break;
}
// System.out.println("TagSize :"+tagSize);
gc.dispose();
return tagSize;
}
public void draw(GC gc, InnerTagBean innerTagBean, int x, int y) {
Point tagSize = calculateTagSize(innerTagBean);
if (tag != null && tag.isSelected()) {
Color b = gc.getBackground();
gc.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_SELECTION));
gc.fillRectangle(0, 0, tagSize.x, tagSize.y);
gc.setBackground(b);
}
int[] tagAreaPoints = calculateTagArea(tagSize, innerTagBean, x, y);
String strInx = String.valueOf(innerTagBean.getIndex());
Color gcBgColor = gc.getBackground();
Color gcFgColor = gc.getForeground();
Font gcFont = gc.getFont();
gc.setFont(TAG_FONT);
// gc.setBackground(ColorConfigBean.getInstance().getTm90Color());
// Point p = calculateTagSize(innerTagBean);
// gc.fillRectangle(x, y, p.x, p.y);
if (innerTagBean.isWrongTag()) {
gc.setBackground(ColorConfigBean.getInstance().getWrongTagColor());
} else {
gc.setBackground(ColorConfigBean.getInstance().getTagBgColor());
}
gc.setForeground(ColorConfigBean.getInstance().getTagFgColor());
gc.fillPolygon(tagAreaPoints);
// gc.drawPolygon(tagAreaPoints);
if (innerTagBean.isWrongTag()) {
gc.setBackground(ColorConfigBean.getInstance().getWrongTagColor());
} else {
gc.setBackground(ColorConfigBean.getInstance().getTagBgColor());
}
gc.setForeground(ColorConfigBean.getInstance().getTagFgColor());
switch (innerTagBean.getType()) {
case START:
gc.drawText(strInx, tagAreaPoints[0] + MARGIN_H, tagAreaPoints[1] + MARGIN_V);
break;
default:
gc.drawText(strInx, tagAreaPoints[2] + MARGIN_H, tagAreaPoints[3] + MARGIN_V);
break;
}
gc.setBackground(gcBgColor);
gc.setForeground(gcFgColor);
gc.setFont(gcFont);
}
private int[] calculateTagArea(Point tagSize, InnerTagBean innerTagBean, int x, int y) {
int sawtooth = tagSize.y / 2;
int[] pointArray = null;
int x1 = x;
int y1 = y;
int y2 = y1 + tagSize.y / 2;
int y3 = y1 + tagSize.y;
switch (innerTagBean.getType()) {
case START:
int x3 = x1 + tagSize.x;
int x2 = x3 - sawtooth;
pointArray = new int[] { x1, y1, x2, y1, x3, y2, x2, y3, x1, y3 };
// System.out.println( ""+ x1 +" "+ y1+", "+ x2+" "+ y1+ ", "+ x3+" "+ y2+", "+ x2+" "+ y3+ ", "+x1+" "+
// y3);
// System.out.println( ""+ (x1+MARGIN_H) +" "+ (y1+MARGIN_V));
break;
case END:
x2 = x1 + sawtooth;
x3 = x1 + tagSize.x;
// System.out.println( ""+ x1 +" "+ y2+", "+ x2+" "+ y1+ ", "+x3+" "+y1+","+ x3+" "+ y3+", "+ x2+" "+ y3);
pointArray = new int[] { x1, y2, x2, y1, x3, y1, x3, y3, x2, y3 };
break;
case STANDALONE:
int x4 = x1 + tagSize.x;
x2 = x1 + sawtooth;
x3 = x4 - sawtooth;
// System.out.println( ""+ x1 +" "+ y2+", "+ x2+" "+ y1+ ", "+x3+" "+y1+","+x4+" "+y2+","+ x3+" "+ y3+", "+
// x2+" "+ y3);
pointArray = new int[] { x1, y2, x2, y1, x3, y1, x4, y2, x3, y3, x2, y3 };
break;
default:
break;
}
return pointArray;
}
}
| 5,234 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui/src/net/heartsome/cat/common/ui/resource/Messages.java | package net.heartsome.cat.common.ui.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.common.ui.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 556 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShieldWorkbenchCommandStartup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield.workbench/src/net/heartsome/cat/common/ui/shield/workbench/ShieldWorkbenchCommandStartup.java | package net.heartsome.cat.common.ui.shield.workbench;
import java.util.Set;
import net.heartsome.cat.common.ui.shield.AbstractShieldCommandStartup;
/**
* 在工作台初始化后,移除不需要用到的 workbench(org.eclipse.ui 插件提供) command。
* @author cheney
* @since JDK1.6
*/
public class ShieldWorkbenchCommandStartup extends AbstractShieldCommandStartup {
private final static String CONF_FILE_PATH = "/unusedWorkbenchCommand.ini";
@Override
protected Set<String> getUnusedCommandSet() {
return readUnusedCommandFromFile(CONF_FILE_PATH);
}
}
| 579 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
LocaleService.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/locale/LocaleService.java | package net.heartsome.cat.common.locale;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import net.heartsome.cat.common.core.CoreActivator;
import net.heartsome.cat.common.file.LanguageConfiger;
/**
* 对语言、国家/区域、字符集进行操作的方法定义
* @author cheney
* @since JDK1.6
*/
public final class LocaleService {
private static String[] pageCodes;
private static Map<String, Language> defaultLanguage;
private static LanguageConfiger langConfiger = new LanguageConfiger();
private LocaleService() {
// 防止此类被实例化
}
/**
* 获取语言配置对象
* @return ;
*/
public static LanguageConfiger getLanguageConfiger(){
if(langConfiger == null){
langConfiger = new LanguageConfiger();
}
return langConfiger;
}
/**
* Java 平台支持的字符集名称
* @return Java 平台支持的字符集名称;
*/
public static String[] getPageCodes() {
if (pageCodes == null) {
TreeMap<String, Charset> charsets = new TreeMap<String, Charset>(Charset.availableCharsets());
Set<String> keys = charsets.keySet();
String[] pageCodes = new String[keys.size()];
Iterator<String> i = keys.iterator();
int j = 0;
while (i.hasNext()) {
Charset cset = charsets.get(i.next());
pageCodes[j++] = cset.displayName();
}
LocaleService.pageCodes = pageCodes;
}
return pageCodes;
}
/**
* 平台(HS 应用)支持的语言集的名称
* @return 平台(HS 应用)支持的语言集的代码名称;
*/
public static String[] getLanguageCodes() {
Map<String, Language> languageMap = getDefaultLanguage();
int size = languageMap.keySet().size();
String[] result = new String[size];
return languageMap.keySet().toArray(result);
}
/**
* 平台(HS 应用)支持的语言集的名称
* @return 平台(HS 应用)支持的语言集的代码名称;
*/
public static String[] getLanguages() {
Map<String, Language> languageMap = getDefaultLanguage();
int size = languageMap.keySet().size();
String[] result = new String[size];
TreeMap<String, Language> tree = new TreeMap<String, Language>(languageMap);
int i = 0;
for (Language language : tree.values()) {
result[i++] = getLanguageDisplayString(language);
}
return result;
}
/**
* 得到该语言用于显示的字符串格式。<br/>
* 例如:zh-CN Chinese(People's Republic)
* @param language
* @return ;
*/
private static String getLanguageDisplayString(Language language) {
if (language == null) {
return "";
}
return language.getCode() + " " + language.getName();
}
/**
* 解析语言代码 xml 文件,如果解析失败,则返回空 map
* @param isBidi
* true 即标识 xml 文件中有 bidi 属性,以及返回 code、bidi 对应的 map;否则返回 code、语言名称对应的 map
* @return 根据 isBidi 标识,返回相应的 map;
*/
private static Map<String, Language> getLanguageConfiguration() {
if(langConfiger == null){
langConfiger = new LanguageConfiger();
}
return langConfiger.getAllLanguage();
}
/**
* 把以文件形式存储的语言代码转换成字符串的形式
* @return ;
*/
public static String getLanguageConfigAsString() {
StringBuffer result = new StringBuffer();
InputStream is = CoreActivator.getConfigurationFileInputStream(CoreActivator.LANGUAGE_CODE_PATH);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
result.append("\n");
}
reader.close();
// 默认的语言代码文件是跟插件打包在一起的,不会出现读取文件失败的问题,所以在此忽略相关异常
} catch (FileNotFoundException e) {
// 忽略此异常
e.printStackTrace();
} catch (IOException e) {
// 忽略此异常
e.printStackTrace();
}
return result.toString();
}
/**
* 得到语言代码
* @param language
* 语言
* @return 语言代码,如果没有此代码,则返回空字符串;
*/
public static String getLanguageCodeByLanguage(String language) {
String result = "";
if (language == null) {
return result;
}
language = language.trim();
if (language.equals("")) {
return result;
}
int index = language.indexOf(" ");
if (index > -1) {
return language.substring(0, index);
}
return result;
}
/**
* 得到语言名称
* @param language
* 语言
* @return 语言名称,如果没有此名称,则返回空字符串;
*/
public static String getLanguageNameByLanguage(String language) {
String result = "";
if (language == null) {
return result;
}
language = language.trim();
if (language.equals("")) {
return result;
}
int index = language.indexOf(" ");
if (index > -1) {
return language.substring(index + 1);
}
return result;
}
/**
* 根据语言代码得到某种语言
* @param LanguageCode
* 语言代码
* @return 语言,如果没有此语言,则返回空字符串;
*/
public static String getLanguage(String LanguageCode) {
String result = "";
if (LanguageCode == null) {
return result;
}
Map<String, Language> languageMap = getDefaultLanguage();
Language language = languageMap.get(LanguageCode);
return getLanguageDisplayString(language);
}
/**
* @param languageName
* 语言名称
* @return 语言名称对应的语言代码,如果没有此名称对应的代码,则返回空字符串;
*/
public static String getLanguageCode(String languageName) {
String result = "";
if (languageName == null) {
return result;
}
Map<String, Language> languageMap = getDefaultLanguage();
Set<String> keySet = languageMap.keySet();
for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
String key = iterator.next();
Language language = languageMap.get(key);
if (languageName.equals(language.getName())) {
result = key;
}
}
return result;
}
/**
* @param languageCode
* 语言代码
* @return 语言代码对应的名称,如果没有此代码对应的名称,则返回空字符串;
*/
public static String getLanguageName(String languageCode) {
String result = "";
if (languageCode == null || languageCode.trim().equals("")) {
return result;
}
Map<String, Language> languageMap = getDefaultLanguage();
if (languageMap.containsKey(languageCode)) {
result = languageMap.get(languageCode).getName();
}
return result;
}
/**
* 支持双向的语言集
* @return 返回支持双向的语言集;
*/
public static String[] getBidirectionalLangs() {
return new String[0];
}
/**
* @param country
* 国家代码
* @return 国家代码对应的国家名称;
*/
public static String getCountryName(String country) {
return "";
}
/**
* ISO 639 中定义的语言名称
* @param languageCode
* 语言代码
* @return 返回 ISO 639 中定义的语言名称;
*/
public static String getISO639(String languageCode) {
return "";
}
/**
* 默认或用户更新设置后的语言 Map
* @return 返回默认或用户更新设置后的语言 Map;
*/
public static Map<String, Language> getDefaultLanguage() {
if (defaultLanguage == null) {
defaultLanguage = getLanguageConfiguration();
}
return defaultLanguage;
}
/**
* 验证集合中的字符串是否为语言代码
* @param languages
* @return ;
*/
public static boolean verifyLanguages(Vector<String> languages) {
Map<String, Language> languageMap = getDefaultLanguage();
for (String langCode : languages) {
if (!languageMap.containsKey(langCode)) {
return false;
}
}
return true;
}
}
| 8,036 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Language.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/locale/Language.java | package net.heartsome.cat.common.locale;
import java.util.Locale;
/**
* 标识为每一个语言设置实体
* @author cheney
* @since JDK1.6
*/
public class Language {
// 语言代码
private String code;
// 语言名称
private String name;
// 语言图标
private String imagePath;
// 是否双向
private boolean bidi;
// 此语言对应的 locale
private Locale locale;
public Language(String code, String name, String imagePath, boolean bidi) {
this.code = code;
this.name = name;
this.bidi = bidi;
this.imagePath = imagePath;
}
/**
* 语言代码
* @return 语言代码;
*/
public String getCode() {
return code;
}
/**
* 语言代码
* @param code
* ;
*/
public void setCode(String code) {
this.code = code;
}
/**
* 语言名称
* @return 语言名称;
*/
public String getName() {
return name;
}
/**
* 语言名称
* @param name
* ;
*/
public void setName(String name) {
this.name = name;
}
/** @return the imagePath */
public String getImagePath() {
return imagePath;
}
/**
* @param imagePath
* the imagePath to set
*/
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
/**
* 是否双向
* @return 是双向则返回 true,否则返回 false;
*/
public boolean isBidi() {
return bidi;
}
/**
* 是否双向
* @param bidi
* 是则为 true,否则为 false;
*/
public void setBidi(boolean bidi) {
this.bidi = bidi;
}
/**
* 返回此语言代码对应的 locale
* @return ;
*/
public Locale getLocale() {
if (locale == null) {
locale = new Locale(code);
}
return locale;
}
/**
* 这个方法的改动,会影响{@link TextUtil}的很多关于语言的方法,注意. robert
*/
@Override
public String toString() {
// return new StringBuffer(code).append(" ").append(name).toString();
// 修改BUG 2766 robert 2012-12-20
return new StringBuffer(name).append(" ").append(code).toString();
}
}
| 2,032 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MatchQuality.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/tm/MatchQuality.java | package net.heartsome.cat.common.tm;
/**
* 匹配率
* @author weachy
* @version
* @since JDK1.5
*/
public class MatchQuality {
static final int PENALTY = 2;
static String[] ignorables;
static boolean loaded; // default value for a boolean is "false"
static String LCS(String x, String y) {
String result = ""; //$NON-NLS-1$
int M = x.length();
int N = y.length();
int max = 0;
int mx = 0;
// opt[i][j] = length of LCS of x[i..M] and y[j..N]
int[][] opt = new int[M + 1][N + 1];
// fill the matrix
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++) {
if (x.charAt(i - 1) == y.charAt(j - 1)) {
opt[i][j] = opt[i - 1][j - 1] + 1;
if (opt[i][j] > max) {
// remember where the maximum length is
max = opt[i][j];
mx = i;
}
} else {
opt[i][j] = 0;
}
}
}
// recover the LCS
while (max > 0) {
result = x.charAt(mx - 1) + result;
max--;
mx--;
}
return result;
}
/**
* 比较相似性
* @param x
* @param y
* @return ;
*/
public static int similarity(String x, String y) {
if (!loaded) {
loadIgnorables();
}
int result = 0;
x = x.trim();
y = y.trim();
for (int i = 0; i < ignorables.length; i++) {
x = x.replaceAll(ignorables[i], ""); //$NON-NLS-1$
y = y.replaceAll(ignorables[i], ""); //$NON-NLS-1$
}
int longest = Math.max(x.length(), y.length());
if (longest == 0) {
return 0;
}
String a, b;
if (x.length() == longest) {
a = x;
b = y;
} else {
a = y;
b = x;
}
// a is the longest string
int count = -1;
int idx;
String lcs = LCS(a, b);
while (!lcs.trim().equals("") && lcs.length() > longest * PENALTY / 100) { //$NON-NLS-1$
count++;
idx = a.indexOf(lcs);
a = a.substring(0, idx) + a.substring(idx + lcs.length());
idx = b.indexOf(lcs);
b = b.substring(0, idx) + b.substring(idx + lcs.length());
lcs = LCS(a, b);
}
result = 100 * (longest - a.length()) / longest - count * PENALTY;
if (result < 0) {
result = 0;
}
return result;
}
public static void main(String[] args) {
String x = "Heimdal - 4 Channel Room Monitoring";
String y = "4 Channel Room Monitoring System — Heimdal";
System.out.println(similarity(x, y));
x = "string with tatw\u0640eel inside";
y = "string with tatweel inside<ph/>";
System.out.println(similarity(x, y));
}
private static void loadIgnorables() {
// IPreferenceStore store = Activator.getDefault().getPreferenceStore();
// String ignorableChars = store.getString(IPreferenceConstants.IGNORABLE_CHARS);
String ignorableChars = null;
if (ignorableChars == null || "".equals(ignorableChars)) {
ignorableChars = "\\u0640";
// store.setValue(IPreferenceConstants.IGNORABLE_CHARS, "\\u0640");
}
ignorables = ignorableChars.split(",");
loaded = true;
}
} | 2,964 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.