下面列出了org.eclipse.ui.actions.NewProjectAction#org.eclipse.jdt.internal.ui.JavaUIMessages 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void createViewMenu(Composite parent) {
fToolBar= new ToolBar(parent, SWT.FLAT);
fToolItem= new ToolItem(fToolBar, SWT.PUSH, 0);
GridData data= new GridData();
data.horizontalAlignment= GridData.END;
fToolBar.setLayoutData(data);
fToolItem.setImage(JavaPluginImages.get(JavaPluginImages.IMG_ELCL_VIEW_MENU));
fToolItem.setDisabledImage(JavaPluginImages.get(JavaPluginImages.IMG_DLCL_VIEW_MENU));
fToolItem.setToolTipText(JavaUIMessages.TypeSelectionComponent_menu);
fToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
showViewMenu();
}
});
fMenuManager= new MenuManager();
fillViewMenu(fMenuManager);
// ICommandService commandService= (ICommandService)PlatformUI.getWorkbench().getAdapter(ICommandService.class);
// IHandlerService handlerService= (IHandlerService)PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
}
public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
if (fFieldNameProposals.length == 0)
return null;
String input= contentAssistSubject.getDocument().get();
ArrayList<JavaCompletionProposal> proposals= new ArrayList<JavaCompletionProposal>();
String prefix= input.substring(0, documentOffset);
ImageDescriptor imageDescriptor= JavaElementImageProvider.getFieldImageDescriptor(false, fRefactoring.getVisibility());
Image image= fImageRegistry.get(imageDescriptor);
for (int i= 0; i < fFieldNameProposals.length; i++) {
String tempName= fFieldNameProposals[i];
if (tempName.length() == 0 || ! tempName.startsWith(prefix))
continue;
JavaCompletionProposal proposal= new JavaCompletionProposal(tempName, 0, input.length(), image, tempName, 0);
proposals.add(proposal);
}
fErrorMessage= proposals.size() > 0 ? null : JavaUIMessages.JavaEditor_codeassist_noCompletions;
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
if (fTempNameProposals.length == 0)
return null;
String input= contentAssistSubject.getDocument().get();
ArrayList<JavaCompletionProposal> proposals= new ArrayList<JavaCompletionProposal>();
String prefix= input.substring(0, documentOffset);
Image image= fImageRegistry.get(fProposalImageDescriptor);
for (int i= 0; i < fTempNameProposals.length; i++) {
String tempName= fTempNameProposals[i];
if (tempName.length() == 0 || ! tempName.startsWith(prefix))
continue;
JavaCompletionProposal proposal= new JavaCompletionProposal(tempName, 0, input.length(), image, tempName, 0);
proposals.add(proposal);
}
fErrorMessage= proposals.size() > 0 ? null : JavaUIMessages.JavaEditor_codeassist_noCompletions;
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
private void handleFinishedDropMove(DragSourceEvent event) {
MultiStatus status= new MultiStatus(
JavaPlugin.getPluginId(),
IJavaStatusConstants.INTERNAL_ERROR,
JavaUIMessages.ResourceTransferDragAdapter_cannot_delete_resource,
null);
List<IResource> resources= convertSelection();
for (Iterator<IResource> iter= resources.iterator(); iter.hasNext();) {
IResource resource= iter.next();
try {
resource.delete(true, null);
} catch (CoreException e) {
status.add(e.getStatus());
}
}
int childrenCount= status.getChildren().length;
if (childrenCount > 0) {
Shell parent= SWTUtil.getShell(event.widget);
ErrorDialog error= new ErrorDialog(parent,
JavaUIMessages.ResourceTransferDragAdapter_moving_resource,
childrenCount == 1 ? JavaUIMessages.ResourceTransferDragAdapter_cannot_delete_files_singular : Messages.format(
JavaUIMessages.ResourceTransferDragAdapter_cannot_delete_files_plural, String.valueOf(childrenCount)), status, IStatus.ERROR);
error.open();
}
}
@Override
protected Control createLinkControl(Composite composite) {
Link link= new Link(composite, SWT.WRAP);
link.setText(JavaUIMessages.OverrideMethodDialog_link_message);
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openCodeTempatePage(CodeTemplateContextType.OVERRIDECOMMENT_ID);
}
});
link.setToolTipText(JavaUIMessages.OverrideMethodDialog_link_tooltip);
GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
link.setLayoutData(gridData);
return link;
}
@Override
protected CheckboxTreeViewer createTreeViewer(Composite composite) {
initializeDialogUnits(composite);
ViewerPane pane= new ViewerPane(composite, SWT.BORDER | SWT.FLAT);
pane.setText(JavaUIMessages.OverrideMethodDialog_dialog_description);
CheckboxTreeViewer treeViewer= super.createTreeViewer(pane);
pane.setContent(treeViewer.getControl());
GridLayout paneLayout= new GridLayout();
paneLayout.marginHeight= 0;
paneLayout.marginWidth= 0;
paneLayout.numColumns= 1;
pane.setLayout(paneLayout);
GridData gd= new GridData(GridData.FILL_BOTH);
gd.widthHint= convertWidthInCharsToPixels(55);
gd.heightHint= convertHeightInCharsToPixels(15);
pane.setLayoutData(gd);
ToolBarManager manager= pane.getToolBarManager();
manager.add(new OverrideFlatTreeAction()); // create after tree is created
manager.update(true);
treeViewer.getTree().setFocus();
return treeViewer;
}
@Override
protected void setResult(List newResult) {
List<IType> resultToReturn= new ArrayList<IType>();
for (int i= 0; i < newResult.size(); i++) {
if (newResult.get(i) instanceof TypeNameMatch) {
IType type= ((TypeNameMatch) newResult.get(i)).getType();
if (type.exists()) {
// items are added to history in the
// org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#computeResult()
// method
resultToReturn.add(type);
} else {
TypeNameMatch typeInfo= (TypeNameMatch) newResult.get(i);
IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot();
String containerName= JavaElementLabels.getElementLabel(root, JavaElementLabels.ROOT_QUALIFIED);
String message= Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_dialogMessage, new String[] { TypeNameMatchLabelProvider.getText(typeInfo, TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED), containerName });
MessageDialog.openError(getShell(), fTitle, message);
getSelectionHistory().remove(typeInfo);
}
}
}
super.setResult(resultToReturn);
}
@Override
protected IStatus validateItem(Object item) {
if (item == null)
return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, "", null); //$NON-NLS-1$
if (fValidator != null) {
IType type= ((TypeNameMatch) item).getType();
if (!type.exists()) {
String qualifiedName= TypeNameMatchLabelProvider.getText((TypeNameMatch) item, TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED);
return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_error_type_doesnot_exist, qualifiedName), null);
}
Object[] elements= { type };
return fValidator.validate(elements);
} else
return Status.OK_STATUS;
}
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (fgFirstTime) {
// Join the initialize after load job.
IJobManager manager= Job.getJobManager();
manager.join(JavaUI.ID_PLUGIN, monitor);
}
OpenTypeHistory history= OpenTypeHistory.getInstance();
if (fgFirstTime || history.isEmpty()) {
if (history.needConsistencyCheck()) {
monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100);
refreshSearchIndices(new SubProgressMonitor(monitor, 90));
history.checkConsistency(new SubProgressMonitor(monitor, 10));
} else {
refreshSearchIndices(monitor);
}
monitor.done();
fgFirstTime= false;
} else {
history.checkConsistency(monitor);
}
}
public IStatus validate(Object[] selection) {
if (getGenerationSettings().toStringStyle == GenerateToStringOperation.CUSTOM_BUILDER) {
if (fValidator == null)
fValidator= new CustomBuilderValidator(getType().getJavaProject());
IStatus status= fValidator.revalidateAll(getGenerationSettings().getCustomBuilderSettings());
if (!status.isOK())
return new StatusInfo(IStatus.ERROR, JavaUIMessages.GenerateToStringDialog_selectioninfo_customBuilderConfigError);
}
int countFields= 0, countMethods= 0;
for (int index= 0; index < selection.length; index++) {
if (selection[index] instanceof IVariableBinding)
countFields++;
else if (selection[index] instanceof IMethodBinding)
countMethods++;
}
return new StatusInfo(IStatus.INFO, Messages.format(JavaUIMessages.GenerateToStringDialog_selectioninfo_more, new String[] { String.valueOf(countFields), String.valueOf(fNumFields),
String.valueOf(countMethods), String.valueOf(fNumMethods) }));
}
private void browseForBuilderClass() {
try {
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { getType().getJavaProject() });
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), PlatformUI.getWorkbench().getProgressService(), scope,
IJavaElementSearchConstants.CONSIDER_CLASSES, false, "*ToString", fExtension); //$NON-NLS-1$
dialog.setTitle(JavaUIMessages.GenerateToStringDialog_customBuilderConfig_classSelection_windowTitle);
dialog.setMessage(JavaUIMessages.GenerateToStringDialog_customBuilderConfig_classSelection_message);
dialog.open();
if (dialog.getReturnCode() == OK) {
IType type= (IType)dialog.getResult()[0];
fBuilderClassName.setText(type.getFullyQualifiedParameterizedName());
List<String> suggestions= fValidator.getAppendMethodSuggestions(type);
if (!suggestions.contains(fAppendMethodName.getText()))
fAppendMethodName.setText(suggestions.get(0));
suggestions= fValidator.getResultMethodSuggestions(type);
if (!suggestions.contains(fResultMethodName.getText()))
fResultMethodName.setText(suggestions.get(0));
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
public GenerateToStringDialog(Shell shell, CompilationUnitEditor editor, IType type, IVariableBinding[] fields, IVariableBinding[] inheritedFields, IVariableBinding[] selectedFields,
IMethodBinding[] methods, IMethodBinding[] inheritededMethods) throws JavaModelException {
super(shell, new BindingLabelProvider(), new GenerateToStringContentProvider(fields, inheritedFields, methods, inheritededMethods), editor, type, false);
setEmptyListMessage(JavaUIMessages.GenerateHashCodeEqualsDialog_no_entries);
List<Object> selected= new ArrayList<Object>(Arrays.asList(selectedFields));
if (selectedFields.length == fields.length && selectedFields.length > 0)
selected.add(getContentProvider().getParent(selectedFields[0]));
setInitialElementSelections(selected);
setTitle(JavaUIMessages.GenerateToStringDialog_dialog_title);
setMessage(JavaUIMessages.GenerateToStringDialog_select_fields_to_include);
setValidator(new GenerateToStringValidator(fields.length + inheritedFields.length, methods.length + inheritededMethods.length));
setSize(60, 18);
setInput(new Object());
fGenerationSettings= new ToStringGenerationSettings(getDialogSettings());
}
@Override
protected Composite createSelectionButtons(Composite composite) {
Composite buttonComposite= super.createSelectionButtons(composite);
GridLayout layout= new GridLayout();
buttonComposite.setLayout(layout);
createUpDownButtons(buttonComposite);
createButton(buttonComposite, SORT_BUTTON, JavaUIMessages.GenerateToStringDialog_sort_button, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 1;
return buttonComposite;
}
@Override
protected String getSimpleTypeName(IJavaElement enclosingElement, String typeSig) {
String typeName= super.getSimpleTypeName(enclosingElement, typeSig);
String title= ""; //$NON-NLS-1$
String qualifiedName= Signature.toString(Signature.getTypeErasure(typeSig));
int qualifierLength= qualifiedName.length() - typeName.length() - 1;
if (qualifierLength > 0) {
if (qualifiedName.endsWith(typeName)) {
title= qualifiedName.substring(0, qualifierLength);
title= Messages.format(JavaUIMessages.JavaElementLinks_title, title);
} else {
title= qualifiedName; // Not expected. Just show the whole qualifiedName.
}
}
try {
String uri= createURI(JAVADOC_SCHEME, enclosingElement, qualifiedName, null, null);
return createHeaderLink(uri, typeName, title);
} catch (URISyntaxException e) {
JavaPlugin.log(e);
return typeName;
}
}
private void createMaxEntriesField() {
fMaxEntriesField= new StringDialogField();
fMaxEntriesField.setLabelText(fHistory.getMaxEntriesMessage());
fMaxEntriesField.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
String maxString= fMaxEntriesField.getText();
boolean valid;
try {
fMaxEntries= Integer.parseInt(maxString);
valid= fMaxEntries > 0 && fMaxEntries < MAX_MAX_ENTRIES;
} catch (NumberFormatException e) {
valid= false;
}
if (valid)
updateStatus(StatusInfo.OK_STATUS);
else
updateStatus(new StatusInfo(IStatus.ERROR, Messages.format(JavaUIMessages.HistoryListAction_max_entries_constraint, Integer.toString(MAX_MAX_ENTRIES))));
}
});
fMaxEntriesField.setText(Integer.toString(fHistory.getMaxEntries()));
}
private void appendCategoryLabel(IMember member, long flags) throws JavaModelException {
String[] categories= member.getCategories();
if (categories.length > 0) {
int offset= fBuffer.length();
StringBuffer categoriesBuf= new StringBuffer();
for (int i= 0; i < categories.length; i++) {
if (i > 0)
categoriesBuf.append(JavaElementLabels.CATEGORY_SEPARATOR_STRING);
categoriesBuf.append(categories[i]);
}
fBuffer.append(JavaElementLabels.CONCAT_STRING);
fBuffer.append(Messages.format(JavaUIMessages.JavaElementLabels_category, categoriesBuf.toString()));
if (getFlag(flags, JavaElementLabels.COLORIZE)) {
fBuffer.setStyle(offset, fBuffer.length() - offset, COUNTER_STYLE);
}
}
}
/**
* Appends the label for a initializer. Considers the I_* flags.
*
* @param initializer the element to render
* @param flags the rendering flags. Flags with names starting with 'I_' are considered.
*/
public void appendInitializerLabel(IInitializer initializer, long flags) {
// qualification
if (getFlag(flags, JavaElementLabels.I_FULLY_QUALIFIED)) {
appendTypeLabel(initializer.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
fBuffer.append('.');
}
fBuffer.append(JavaUIMessages.JavaElementLabels_initializer);
// post qualification
if (getFlag(flags, JavaElementLabels.I_POST_QUALIFIED)) {
int offset= fBuffer.length();
fBuffer.append(JavaElementLabels.CONCAT_STRING);
appendTypeLabel(initializer.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
if (getFlag(flags, JavaElementLabels.COLORIZE)) {
fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
}
}
}
private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement[] input) {
IWorkbenchPage page= window.getActivePage();
try {
TypeHierarchyViewPart result= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
if (result != null) {
result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
}
result= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
result.setInputElements(input);
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.OpenTypeHierarchyUtil_error_open_view, e.getMessage());
}
return null;
}
public String getQualifiedText(TypeNameMatch type) {
StringBuffer result= new StringBuffer();
result.append(type.getSimpleTypeName());
String containerName= type.getTypeContainerName();
result.append(JavaElementLabels.CONCAT_STRING);
if (containerName.length() > 0) {
result.append(containerName);
} else {
result.append(JavaUIMessages.TypeInfoViewer_default_package);
}
return result.toString();
}
private String getMessage() {
if (fDone) {
return ""; //$NON-NLS-1$
} else if (fTotalWork == 0) {
return fName;
} else {
return Messages.format(
JavaUIMessages.TypeInfoViewer_progress_label,
new Object[] { fName, new Integer((int)((fWorked * 100) / fTotalWork)) });
}
}
protected AbstractSearchJob(int ticket, TypeInfoViewer viewer, TypeInfoFilter filter, OpenTypeHistory history, int numberOfVisibleItems, int mode) {
super(JavaUIMessages.TypeInfoViewer_job_label, viewer);
fMode= mode;
fTicket= ticket;
fViewer= viewer;
fLabelProvider= fViewer.getLabelProvider();
fFilter= filter;
fHistory= history;
}
@Override
protected TypeNameMatch[] getSearchResult(Set matchIdsInHistory, ProgressMonitor monitor) throws CoreException {
long start= System.currentTimeMillis();
fReqestor.setHistory(matchIdsInHistory);
// consider primary working copies during searching
SearchEngine engine= new SearchEngine((WorkingCopyOwner)null);
String packPattern= fFilter.getPackagePattern();
monitor.setTaskName(JavaUIMessages.TypeInfoViewer_searchJob_taskName);
engine.searchAllTypeNames(
packPattern == null ? null : packPattern.toCharArray(),
fFilter.getPackageFlags(),
fFilter.getNamePattern().toCharArray(),
fFilter.getSearchFlags(),
fElementKind,
fScope,
fReqestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
if (DEBUG)
System.out.println("Time needed until search has finished: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
TypeNameMatch[] result= fReqestor.getResult();
Arrays.sort(result, new TypeInfoComparator(fLabelProvider, fFilter));
if (DEBUG)
System.out.println("Time needed until sort has finished: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
fViewer.rememberResult(fTicket, result);
return result;
}
public void setText(String text) {
if (text == null || text.length() == 0) {
getShell().setText(fTitle);
} else {
getShell().setText(Messages.format(
JavaUIMessages.TypeSelectionDialog2_title_format,
new String[] { fTitle, text}));
}
}
@Override
protected void computeResult() {
TypeNameMatch[] selected= fContent.getSelection();
if (selected == null || selected.length == 0) {
setResult(null);
return;
}
// If the scope is null then it got computed by the type selection component.
if (fScope == null) {
fScope= fContent.getScope();
}
OpenTypeHistory history= OpenTypeHistory.getInstance();
List result= new ArrayList(selected.length);
for (int i= 0; i < selected.length; i++) {
TypeNameMatch typeInfo= selected[i];
IType type= typeInfo.getType();
if (!type.exists()) {
String title= JavaUIMessages.TypeSelectionDialog_errorTitle;
IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot();
String containerName= JavaElementLabels.getElementLabel(root, JavaElementLabels.ROOT_QUALIFIED);
String message= Messages.format(JavaUIMessages.TypeSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName });
MessageDialog.openError(getShell(), title, message);
history.remove(typeInfo);
setResult(null);
} else {
history.accessed(typeInfo);
result.add(type);
}
}
setResult(result);
}
public OpenTypeAction() {
super();
setText(JavaUIMessages.OpenTypeAction_label);
setDescription(JavaUIMessages.OpenTypeAction_description);
setToolTipText(JavaUIMessages.OpenTypeAction_tooltip);
setImageDescriptor(JavaPluginImages.DESC_TOOL_OPENTYPE);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_TYPE_ACTION);
}
/**
* Opens the new project dialog if the workspace is empty.
* @param parent the parent shell
* @return returns <code>true</code> when a project has been created, or <code>false</code> when the
* new project has been canceled.
*/
protected boolean doCreateProjectFirstOnEmptyWorkspace(Shell parent) {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
if (workspaceRoot.getProjects().length == 0) {
String title= JavaUIMessages.OpenTypeAction_dialogTitle;
String message= JavaUIMessages.OpenTypeAction_createProjectFirst;
if (MessageDialog.openQuestion(parent, title, message)) {
new NewProjectAction().run();
return workspaceRoot.getProjects().length != 0;
}
return false;
}
return true;
}
@Override
protected String formatMultipleMessages(List messages) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.addPageProlog(buffer);
HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(JavaUIMessages.JavaAnnotationHover_multipleMarkersAtThisLine));
HTMLPrinter.startBulletList(buffer);
Iterator<?> e= messages.iterator();
while (e.hasNext())
HTMLPrinter.addBullet(buffer, HTMLPrinter.convertToHTMLContent((String) e.next()));
HTMLPrinter.endBulletList(buffer);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
public String getErrorMessage() {
if (fErrorMessage != null)
return fErrorMessage;
if (fNumberOfComputedResults > 0)
return null;
return JavaUIMessages.JavaEditor_codeassist_noCompletions;
}
/**
* {@inheritDoc}
*/
@Override
protected String getStatusFieldText() {
KeySequence[] sequences= getInvokingCommandKeySequences();
if (sequences == null || sequences.length == 0)
return ""; //$NON-NLS-1$
String keySequence= sequences[0].format();
if (fOutlineContentProvider.isShowingInheritedMembers())
return Messages.format(JavaUIMessages.JavaOutlineControl_statusFieldText_hideInheritedMembers, keySequence);
else
return Messages.format(JavaUIMessages.JavaOutlineControl_statusFieldText_showInheritedMembers, keySequence);
}
/**
* Asks the user whether he wants to configure a user dictionary.
*
* @param shell the shell
* @return <code>true</code> if the user wants to configure the user dictionary
* @since 3.3
*/
private boolean askUserToConfigureUserDictionary(Shell shell) {
MessageDialogWithToggle toggleDialog= MessageDialogWithToggle.openYesNoQuestion(
shell,
JavaUIMessages.Spelling_add_askToConfigure_title,
JavaUIMessages.Spelling_add_askToConfigure_question,
JavaUIMessages.Spelling_add_askToConfigure_ignoreMessage,
false,
null,
null);
PreferenceConstants.getPreferenceStore().setValue(PREF_KEY_DO_NOT_ASK, toggleDialog.getToggleState());
return toggleDialog.getReturnCode() == IDialogConstants.YES_ID;
}