1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Patch for Hoda Amer.

First patch for a new class wizard for CDT.
This commit is contained in:
John Camelon 2003-05-27 21:33:04 +00:00
parent 8cbe8f914d
commit 1ce9ba9ea0
43 changed files with 5073 additions and 164 deletions

View file

@ -6,12 +6,18 @@ package org.eclipse.cdt.core.model;
*/
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.core.model.BatchOperation;
import org.eclipse.cdt.internal.core.model.CModelManager;
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.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public class CoreModel {
@ -199,4 +205,14 @@ public class CoreModel {
private CoreModel() {
}
public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
if (workspace.isTreeLocked()) {
new BatchOperation(action).run(monitor);
} else {
// use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
workspace.run(new BatchOperation(action), monitor);
}
}
}

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.core.model;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.cdt.core.model.ICModelStatus;
import org.eclipse.cdt.core.model.CModelException;
/**
* An operation created as a result of a call to JavaCore.run(IWorkspaceRunnable, IProgressMonitor)
* that encapsulates a user defined IWorkspaceRunnable.
*/
public class BatchOperation extends CModelOperation {
protected IWorkspaceRunnable runnable;
public BatchOperation(IWorkspaceRunnable runnable) {
this.runnable = runnable;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.core.JavaModelOperation#executeOperation()
*/
protected void executeOperation() throws CModelException {
try {
this.runnable.run(fMonitor);
} catch (CoreException ce) {
if (ce instanceof CModelException) {
throw (CModelException)ce;
} else {
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e= ce.getStatus().getException();
if (e instanceof CModelException) {
throw (CModelException) e;
}
}
throw new CModelException(ce);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.core.JavaModelOperation#verify()
*/
protected ICModelStatus verify() {
// cannot verify user defined operation
return CModelStatus.VERIFIED_OK;
}
}

View file

@ -269,7 +269,7 @@ public class CModelManager implements IResourceChangeListener {
}
public ICProject create(ICElement parent, IProject project) {
if (hasCNature(project)) {
if (hasCNature(project)){
return new CProject(parent, project);
}
return null;

View file

@ -89,6 +89,8 @@ public abstract class CModelOperation implements IWorkspaceRunnable, IProgressMo
*/
protected boolean hasModifiedResource = false;
protected CModelOperation() {
}
/**
* A common constructor for all C Model operations.
*/

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View file

@ -36,10 +36,14 @@ NewWizards.folder = Folder
NewWizards.folder.description = Create a new folder resource
NewWizards.file = File
NewWizards.file.description = Create a new file resource
NewWizards.class = Class
NewWizards.class.description = Create a new C++ class
OpenNewFileWizardAction.label=&File
OpenNewFileWizardAction.tooltip=Create a file
OpenNewFolderWizardAction.label=&Folder
OpenNewFolderWizardAction.tooltip=Create a folder
OpenClassWizardAction.label=&Class
OpenClassWizardAction.tooltip=Create a new C++ class
CEditor.name=C Editor
CPluginPreferencePage.name=C/C++

View file

@ -227,6 +227,17 @@
class="org.eclipse.core.resources.IResource">
</selection>
</wizard>
<wizard
name="%NewWizards.class"
icon="icons/full/ctool16/newclass_wiz.gif"
category="org.eclipse.cdt.ui.newCCWizards"
class="org.eclipse.cdt.ui.wizards.NewClassWizard"
finalPerspective="org.eclipse.cdt.ui.CPerspective"
id="org.eclipse.cdt.ui.wizards.NewClassWizard">
<description>
%NewWizards.class.description
</description>
</wizard>
</extension>
<extension
id="org.eclipse.cdt.ui.ceditor"
@ -405,6 +416,14 @@
toolbarPath="Normal/FolderWizards"
id="org.eclipse.cdt.ui.actions.OpenNewFolderWizardAction">
</action>
<action
label="%OpenClassWizardAction.label"
icon="icons/full/ctool16/newclass_wiz.gif"
tooltip="%OpenClassWizardAction.tooltip"
class="org.eclipse.cdt.ui.actions.OpenClassWizardAction"
toolbarPath="Normal/FolderWizards"
id="org.eclipse.cdt.ui.actions.OpenClassWizardAction">
</action>
</actionSet>
</extension>
<extension

View file

@ -57,6 +57,7 @@ public class CPerspectiveFactory implements IPerspectiveFactory {
layout.addShowViewShortcut(IPageLayout.ID_PROP_SHEET);
// new actions - C project creation wizard
layout.addNewWizardShortcut(CUIPlugin.CLASS_WIZARD_ID);
layout.addNewWizardShortcut(CUIPlugin.FILE_WIZARD_ID);
layout.addNewWizardShortcut(CUIPlugin.FOLDER_WIZARD_ID);
}

View file

@ -136,10 +136,13 @@ public class CPluginImages {
public static final ImageDescriptor DESC_OVR_ERROR= create(T_OVR, "error_co.gif");
public static final ImageDescriptor DESC_WIZABAN_NEW_PROJ= create(T_WIZBAN, "newcprj_wiz.gif");
public static final ImageDescriptor DESC_WIZBAN_NEWCLASS= create(T_WIZBAN, "newclass_wiz.gif");
public static final ImageDescriptor DESC_WIZABAN_C_APP= create(T_WIZBAN, "c_app_wiz.gif");
public static final String IMG_OBJS_PROJECT = NAME_PREFIX + "prj_obj.gif";
public static final ImageDescriptor DESC_PROJECT= createManaged(T_WIZBAN, IMG_OBJS_PROJECT);
public static final ImageDescriptor DESC_TOOL_NEWCLASS= create(T_TOOL, "newclass_wiz.gif"); //$NON-NLS-1$
// For the build image
public static final String IMG_OBJS_BUILD= NAME_PREFIX + "build_menu.gif";
public static final ImageDescriptor DESC_BUILD_MENU = createManaged(T_OBJ, IMG_OBJS_BUILD);

View file

@ -28,6 +28,7 @@ CBasePreferencePage.bracketColour.label=Bracket highlighting color
OpenProjectWizardAction.title=New Project
OpenNewFileWizardAction.title=New File
OpenNewFolderWizardAction.title=New Folder
OpenClassWizardAction.title=New Class
# ------- NewProjectCreationPluginPage-------
@ -79,6 +80,10 @@ StdCCWizard.description=Create a new Standard Make C++ Project.
StdCCWizardSettings.title=Standard Make C++ Settings
StdCCWizardSettings.description=Define the Standard Make C++ build settings.
NewClassWizard.title=New Class
NewClassWizard.description=Create a new C++ Class.
NewClassWizard.page.title=Class
CProjectWizard.op_error.title=Error Creating Project
CProjectWizard.op_error.message=Project cannot be created
CProjectWizard.op_description=C Project Wizard

View file

@ -0,0 +1,43 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class CUIMessages {
private static final String RESOURCE_BUNDLE= "org.eclipse.jdt.internal.ui.JavaUIMessages";//$NON-NLS-1$
private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
private CUIMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public static String getFormattedString(String key, String arg) {
return getFormattedString(key, new String[] { arg });
}
public static String getFormattedString(String key, String[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -21,6 +21,8 @@ public interface ICHelpContextIds {
// Wizard pages
public static final String NEW_CPROJECT_WIZARD_PAGE= PREFIX + "new_cproject_wizard_page_context";
public static final String NEW_LAUNCH_WIZARD_PAGE= PREFIX + "new_launch_wizard_page_context";
public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context";
public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action";
// Actions
public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action";

View file

@ -0,0 +1,52 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.cdt.core.model.CoreModel;
/**
* An <code>IRunnableWithProgress</code> that adapts and <code>IWorkspaceRunnable</code>
* so that is can be executed inside <code>IRunnableContext</code>. <code>OperationCanceledException</code>
* thrown by the apapted runnabled are cought and rethrown as a <code>InterruptedException</code>.
*/
public class WorkbenchRunnableAdapter implements IRunnableWithProgress {
private IWorkspaceRunnable fWorkspaceRunnable;
public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable) {
fWorkspaceRunnable= runnable;
}
/*
* @see IRunnableWithProgress#run(IProgressMonitor)
*/
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
CoreModel.run(fWorkspaceRunnable, monitor);
} catch (OperationCanceledException e) {
throw new InterruptedException(e.getMessage());
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
}

View file

@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.codemanipulation;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.core.runtime.CoreException;
public class StubUtility {
/**
* @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String)
*/
public static String getHeaderFileContent(ITranslationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
return "";
}
/**
* @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String)
*/
public static String getBodyFileContent(ITranslationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
return "";
}
/*
* @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String)
*/
public static String getClassComment(ITranslationUnit cu, String typeQualifiedName, String lineDelim) throws CoreException {
return "";
}
}

View file

@ -751,12 +751,15 @@ public class CView extends ViewPart implements IMenuListener, ISetSelectionTarge
}
void addNewMenu (IMenuManager menu, IStructuredSelection selection) {
MenuManager newMenu = new MenuManager("New");
IAdaptable element = (IAdaptable)selection.getFirstElement();
IResource resource = (IResource)element.getAdapter(IResource.class);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
newMenu.add(goIntoAction);
NewWizardMenu newWizMenu = new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
menu.add(newMenu);

View file

@ -0,0 +1,137 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.util;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.CStatusConstants;
import org.eclipse.cdt.internal.ui.CUIMessages;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
/**
* The default exception handler shows an error dialog when one of its handle methods
* is called. If the passed exception is a <code>CoreException</code> an error dialog
* pops up showing the exception's status information. For a <code>InvocationTargetException</code>
* a normal message dialog pops up showing the exception's message. Additionally the exception
* is written to the platform log.
*/
public class ExceptionHandler {
private static ExceptionHandler fgInstance= new ExceptionHandler();
/**
* Logs the given exception using the platform's logging mechanism. The exception is
* logged as an error with the error code <code>JavaStatusConstants.INTERNAL_ERROR</code>.
*/
public static void log(Throwable t, String message) {
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(),
CStatusConstants.INTERNAL_ERROR, message, t));
}
/**
* Handles the given <code>CoreException</code>. The workbench shell is used as a parent
* for the dialog window.
*
* @param e the <code>CoreException</code> to be handled
* @param title the dialog window's window title
* @param message message to be displayed by the dialog window
*/
public static void handle(CoreException e, String title, String message) {
handle(e, CUIPlugin.getDefault().getActiveWorkbenchShell(), title, message);
}
/**
* Handles the given <code>CoreException</code>.
*
* @param e the <code>CoreException</code> to be handled
* @param parent the dialog window's parent shell
* @param title the dialog window's window title
* @param message message to be displayed by the dialog window
*/
public static void handle(CoreException e, Shell parent, String title, String message) {
fgInstance.perform(e, parent, title, message);
}
/**
* Handles the given <code>InvocationTargetException</code>. The workbench shell is used
* as a parent for the dialog window.
*
* @param e the <code>InvocationTargetException</code> to be handled
* @param title the dialog window's window title
* @param message message to be displayed by the dialog window
*/
public static void handle(InvocationTargetException e, String title, String message) {
handle(e, CUIPlugin.getDefault().getActiveWorkbenchShell(), title, message);
}
/**
* Handles the given <code>InvocationTargetException</code>.
*
* @param e the <code>InvocationTargetException</code> to be handled
* @param parent the dialog window's parent shell
* @param title the dialog window's window title
* @param message message to be displayed by the dialog window
*/
public static void handle(InvocationTargetException e, Shell parent, String title, String message) {
fgInstance.perform(e, parent, title, message);
}
//---- Hooks for subclasses to control exception handling ------------------------------------
protected void perform(CoreException e, Shell shell, String title, String message) {
CUIPlugin.getDefault().log(e);
IStatus status= e.getStatus();
if (status != null) {
ErrorDialog.openError(shell, title, message, status);
} else {
displayMessageDialog(e, e.getMessage(), shell, title, message);
}
}
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
Throwable target= e.getTargetException();
if (target instanceof CoreException) {
perform((CoreException)target, shell, title, message);
} else {
CUIPlugin.getDefault().log(e);
if (e.getMessage() != null && e.getMessage().length() > 0) {
displayMessageDialog(e, e.getMessage(), shell, title, message);
} else {
displayMessageDialog(e, target.getMessage(), shell, title, message);
}
}
}
//---- Helper methods -----------------------------------------------------------------------
private void displayMessageDialog(Throwable t, String exceptionMessage, Shell shell, String title, String message) {
StringWriter msg= new StringWriter();
if (message != null) {
msg.write(message);
msg.write("\n\n"); //$NON-NLS-1$
}
if (exceptionMessage == null || exceptionMessage.length() == 0)
msg.write(CUIMessages.getString("ExceptionDialog.seeErrorLogMessage")); //$NON-NLS-1$
else
msg.write(exceptionMessage);
MessageDialog.openError(shell, title, msg.toString());
}
}

View file

@ -0,0 +1,58 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.util;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.dialogs.Dialog;
public class PixelConverter {
private FontMetrics fFontMetrics;
public PixelConverter(Control control) {
GC gc = new GC(control);
gc.setFont(control.getFont());
fFontMetrics= gc.getFontMetrics();
gc.dispose();
}
/**
* @see org.eclipse.jface.dialogs.DialogPage#convertHeightInCharsToPixels(int)
*/
public int convertHeightInCharsToPixels(int chars) {
return Dialog.convertHeightInCharsToPixels(fFontMetrics, chars);
}
/**
* @see org.eclipse.jface.dialogs.DialogPage#convertHorizontalDLUsToPixels(int)
*/
public int convertHorizontalDLUsToPixels(int dlus) {
return Dialog.convertHorizontalDLUsToPixels(fFontMetrics, dlus);
}
/**
* @see org.eclipse.jface.dialogs.DialogPage#convertVerticalDLUsToPixels(int)
*/
public int convertVerticalDLUsToPixels(int dlus) {
return Dialog.convertVerticalDLUsToPixels(fFontMetrics, dlus);
}
/**
* @see org.eclipse.jface.dialogs.DialogPage#convertWidthInCharsToPixels(int)
*/
public int convertWidthInCharsToPixels(int chars) {
return Dialog.convertWidthInCharsToPixels(fFontMetrics, chars);
}
}

View file

@ -17,7 +17,8 @@ import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.Assert;
/**
@ -66,19 +67,21 @@ public class SWTUtil {
* Returns a width hint for a button control.
*/
public static int getButtonWidthHint(Button button) {
//PixelConverter converter= new PixelConverter(button);
//int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
//return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
return 8*button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x;
if (button.getFont().equals(JFaceResources.getDefaultFont()))
button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
}
/**
* Returns a height hint for a button control.
*/
public static int getButtonHeigthHint(Button button) {
//PixelConverter converter= new PixelConverter(button);
//return converter.convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
return button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).y;
if (button.getFont().equals(JFaceResources.getDefaultFont()))
button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
return converter.convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
}

View file

@ -0,0 +1,375 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.util;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
/**
* Helper class to provide String manipulation functions not available in standard JDK.
*/
public class Strings {
/**
* Indent char is a space char but not a line delimiters.
* <code>== Character.isWhitespace(ch) && ch != '\n' && ch != '\r'</code>
*/
public static boolean isIndentChar(char ch) {
return Character.isWhitespace(ch) && !isLineDelimiterChar(ch);
}
/**
* tests if a char is lower case. Fix for 26529
*/
public static boolean isLowerCase(char ch) {
return Character.toLowerCase(ch) == ch;
}
/**
* Line delimiter chars are '\n' and '\r'.
*/
public static boolean isLineDelimiterChar(char ch) {
return ch == '\n' || ch == '\r';
}
public static String removeNewLine(String message) {
StringBuffer result= new StringBuffer();
int current= 0;
int index= message.indexOf('\n', 0);
while (index != -1) {
result.append(message.substring(current, index));
if (current < index && index != 0)
result.append(' ');
current= index + 1;
index= message.indexOf('\n', current);
}
result.append(message.substring(current));
return result.toString();
}
/**
* Converts the given string into an array of lines. The lines
* don't contain any line delimiter characters.
*
* @return the string converted into an array of strings. Returns <code>
* null</code> if the input string can't be converted in an array of lines.
*/
public static String[] convertIntoLines(String input) {
try {
ILineTracker tracker= new DefaultLineTracker();
tracker.set(input);
int size= tracker.getNumberOfLines();
String result[]= new String[size];
for (int i= 0; i < size; i++) {
IRegion region= tracker.getLineInformation(i);
int offset= region.getOffset();
result[i]= input.substring(offset, offset + region.getLength());
}
return result;
} catch (BadLocationException e) {
return null;
}
}
/**
* Returns <code>true</code> if the given string only consists of
* white spaces according to Java. If the string is empty, <code>true
* </code> is returned.
*
* @return <code>true</code> if the string only consists of white
* spaces; otherwise <code>false</code> is returned
*
* @see java.lang.Character#isWhitespace(char)
*/
public static boolean containsOnlyWhitespaces(String s) {
int size= s.length();
for (int i= 0; i < size; i++) {
if (!Character.isWhitespace(s.charAt(i)))
return false;
}
return true;
}
/**
* Removes leading tabs and spaces from the given string. If the string
* doesn't contain any leading tabs or spaces then the string itself is
* returned.
*/
public static String trimLeadingTabsAndSpaces(String line) {
int size= line.length();
int start= size;
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (!isIndentChar(c)) {
start= i;
break;
}
}
if (start == 0)
return line;
else if (start == size)
return ""; //$NON-NLS-1$
else
return line.substring(start);
}
public static String trimTrailingTabsAndSpaces(String line) {
int size= line.length();
int end= size;
for (int i= size - 1; i >= 0; i--) {
char c= line.charAt(i);
if (isIndentChar(c)) {
end= i;
} else {
break;
}
}
if (end == size)
return line;
else if (end == 0)
return ""; //$NON-NLS-1$
else
return line.substring(0, end);
}
/**
* Returns the indent of the given string.
*
* @param line the text line
* @param tabWidth the width of the '\t' character.
*/
public static int computeIndent(String line, int tabWidth) {
int result= 0;
int blanks= 0;
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c == '\t') {
result++;
blanks= 0;
} else if (isIndentChar(c)) {
blanks++;
if (blanks == tabWidth) {
result++;
blanks= 0;
}
} else {
return result;
}
}
return result;
}
/**
* Removes the given number of idents from the line. Asserts that the given line
* has the requested number of indents. If <code>indentsToRemove <= 0</code>
* the line is returned.
*/
public static String trimIndent(String line, int indentsToRemove, int tabWidth) {
if (line == null || indentsToRemove <= 0)
return line;
int start= 0;
int indents= 0;
int blanks= 0;
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c == '\t') {
indents++;
blanks= 0;
} else if (isIndentChar(c)) {
blanks++;
if (blanks == tabWidth) {
indents++;
blanks= 0;
}
} else {
// Assert.isTrue(false, "Line does not have requested number of indents"); //$NON-NLS-1$
start= i + 1;
break;
}
if (indents == indentsToRemove) {
start= i + 1;
break;
}
}
if (start == size)
return ""; //$NON-NLS-1$
else
return line.substring(start);
}
/**
* Removes all leading indents from the given line. If the line doesn't contain
* any indents the line itself is returned.
*/
public static String trimIndents(String s, int tabWidth) {
int indent= computeIndent(s, tabWidth);
if (indent == 0)
return s;
return trimIndent(s, indent, tabWidth);
}
/**
* Removes the common number of indents from all lines. If a line
* only consists out of white space it is ignored.
*/
public static void trimIndentation(String[] lines, int tabWidth) {
trimIndentation(lines, tabWidth, true);
}
/**
* Removes the common number of indents from all lines. If a line
* only consists out of white space it is ignored. If <code>
* considerFirstLine</code> is false the first line will be ignored.
*/
public static void trimIndentation(String[] lines, int tabWidth, boolean considerFirstLine) {
String[] toDo= new String[lines.length];
// find indentation common to all lines
int minIndent= Integer.MAX_VALUE; // very large
for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) {
String line= lines[i];
if (containsOnlyWhitespaces(line))
continue;
toDo[i]= line;
int indent= computeIndent(line, tabWidth);
if (indent < minIndent) {
minIndent= indent;
}
}
if (minIndent > 0) {
// remove this indent from all lines
for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) {
String s= toDo[i];
if (s != null)
lines[i]= trimIndent(s, minIndent, tabWidth);
else {
String line= lines[i];
int indent= computeIndent(line, tabWidth);
if (indent > minIndent)
lines[i]= trimIndent(line, minIndent, tabWidth);
else
lines[i]= trimLeadingTabsAndSpaces(line);
}
}
}
}
public static String getIndentString(String line, int tabWidth) {
int size= line.length();
int end= 0;
int blanks= 0;
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c == '\t') {
end= i + 1;
blanks= 0;
} else if (isIndentChar(c)) {
blanks++;
if (blanks == tabWidth) {
end= i + 1;
blanks= 0;
}
} else {
break;
}
}
if (end == 0)
return ""; //$NON-NLS-1$
else if (end == size)
return line;
else
return line.substring(0, end);
}
public static String[] removeTrailingEmptyLines(String[] sourceLines) {
int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines);
String[] result= new String[lastNonEmpty + 1];
for (int i= 0; i < result.length; i++) {
result[i]= sourceLines[i];
}
return result;
}
private static int findLastNonEmptyLineIndex(String[] sourceLines) {
for (int i= sourceLines.length - 1; i >= 0; i--) {
if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$
return i;
}
return -1;
}
/**
* Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added.
* The first line of the code will not be changed. (It is considered to have no indent as it might start in
* the middle of a line)
*/
public static String changeIndent(String code, int codeIndentLevel, int tabWidth, String newIndent, String lineDelim) {
try {
ILineTracker tracker= new DefaultLineTracker();
tracker.set(code);
int nLines= tracker.getNumberOfLines();
if (nLines == 1) {
return code;
}
StringBuffer buf= new StringBuffer();
for (int i= 0; i < nLines; i++) {
IRegion region= tracker.getLineInformation(i);
int start= region.getOffset();
int end= start + region.getLength();
String line= code.substring(start, end);
if (i == 0) { // no indent for first line (contained in the formatted string)
buf.append(line);
} else { // no new line after last line
buf.append(lineDelim);
buf.append(newIndent);
buf.append(trimIndent(line, codeIndentLevel, tabWidth));
}
}
return buf.toString();
} catch (BadLocationException e) {
// can not happen
return code;
}
}
/**
* Concatenate the given strings into one strings using the passed line delimiter as a
* delimiter. No delimiter is added to the last line.
*/
public static String concatenate(String[] lines, String delimiter) {
StringBuffer buffer= new StringBuffer();
for (int i= 0; i < lines.length; i++) {
if (i > 0)
buffer.append(delimiter);
buffer.append(lines[i]);
}
return buffer.toString();
}
public static boolean equals(String s, char[] c) {
if (s.length() != c.length)
return false;
for (int i = c.length; --i >= 0;)
if (s.charAt(i) != c[i])
return false;
return true;
}
}

View file

@ -0,0 +1,171 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.util;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
/**
* A special composite to layout columns inside a table. The composite is needed since we have
* to layout the columns "before" the actual table gets layouted. Hence we can't use a normal
* layout manager.
*/
public class TableLayoutComposite extends Composite {
private List columns= new ArrayList();
/**
* Creates a new <code>TableLayoutComposite</code>.
*/
public TableLayoutComposite(Composite parent, int style) {
super(parent, style);
addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle area= getClientArea();
Table table= (Table)getChildren()[0];
Point preferredSize= computeTableSize(table);
int width= area.width - 2 * table.getBorderWidth();
if (preferredSize.y > area.height) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
Point vBarSize = table.getVerticalBar().getSize();
width -= vBarSize.x;
}
layoutTable(table, width, area, table.getSize().x < area.width);
}
});
}
/**
* Adds a new column of data to this table layout.
*
* @param data the column layout data
*/
public void addColumnData(ColumnLayoutData data) {
columns.add(data);
}
//---- Helpers -------------------------------------------------------------------------------------
private Point computeTableSize(Table table) {
Point result= table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int width= 0;
int size= columns.size();
for (int i= 0; i < size; ++i) {
ColumnLayoutData layoutData= (ColumnLayoutData) columns.get(i);
if (layoutData instanceof ColumnPixelData) {
ColumnPixelData col= (ColumnPixelData) layoutData;
width += col.width;
} else if (layoutData instanceof ColumnWeightData) {
ColumnWeightData col= (ColumnWeightData) layoutData;
width += col.minimumWidth;
} else {
Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$
}
}
if (width > result.x)
result.x= width;
return result;
}
private void layoutTable(Table table, int width, Rectangle area, boolean increase) {
// XXX: Layout is being called with an invalid value the first time
// it is being called on Linux. This method resets the
// Layout to null so we make sure we run it only when
// the value is OK.
if (width <= 1)
return;
TableColumn[] tableColumns= table.getColumns();
int size= Math.min(columns.size(), tableColumns.length);
int[] widths= new int[size];
int fixedWidth= 0;
int numberOfWeightColumns= 0;
int totalWeight= 0;
// First calc space occupied by fixed columns
for (int i= 0; i < size; i++) {
ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
if (col instanceof ColumnPixelData) {
int pixels= ((ColumnPixelData) col).width;
widths[i]= pixels;
fixedWidth += pixels;
} else if (col instanceof ColumnWeightData) {
ColumnWeightData cw= (ColumnWeightData) col;
numberOfWeightColumns++;
// first time, use the weight specified by the column data, otherwise use the actual width as the weight
// int weight = firstTime ? cw.weight : tableColumns[i].getWidth();
int weight= cw.weight;
totalWeight += weight;
} else {
Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$
}
}
// Do we have columns that have a weight
if (numberOfWeightColumns > 0) {
// Now distribute the rest to the columns with weight.
int rest= width - fixedWidth;
int totalDistributed= 0;
for (int i= 0; i < size; ++i) {
ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
if (col instanceof ColumnWeightData) {
ColumnWeightData cw= (ColumnWeightData) col;
// calculate weight as above
// int weight = firstTime ? cw.weight : tableColumns[i].getWidth();
int weight= cw.weight;
int pixels= totalWeight == 0 ? 0 : weight * rest / totalWeight;
if (pixels < cw.minimumWidth)
pixels= cw.minimumWidth;
totalDistributed += pixels;
widths[i]= pixels;
}
}
// Distribute any remaining pixels to columns with weight.
int diff= rest - totalDistributed;
for (int i= 0; diff > 0; ++i) {
if (i == size)
i= 0;
ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
if (col instanceof ColumnWeightData) {
++widths[i];
--diff;
}
}
}
if (increase) {
table.setSize(area.width, area.height);
}
for (int i= 0; i < size; i++) {
tableColumns[i].setWidth(widths[i]);
}
if (!increase) {
table.setSize(area.width, area.height);
}
}
}

View file

@ -77,19 +77,4 @@ public class MemberFilter extends ViewerFilter{
}
return true;
}
/*
private boolean isMemberInInterface(IMember member) throws JavaModelException {
IType parent= member.getDeclaringType();
return parent != null && parent.isInterface();
}
private boolean isFieldInInterface(IMember member) throws JavaModelException {
return (member.getElementType() == IJavaElement.FIELD) && member.getDeclaringType().isInterface();
}
private boolean isTopLevelType(IMember member) throws JavaModelException {
IType parent= member.getDeclaringType();
return parent == null;
}
*/
}

View file

@ -0,0 +1,51 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class NewWizardMessages {
private static final String RESOURCE_BUNDLE= NewWizardMessages.class.getName();
private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
private NewWizardMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
/**
* Gets a string from the resource bundle and formats it with the argument
*
* @param key the string used to get the bundle value, must not be null
*/
public static String getFormattedString(String key, Object arg) {
return MessageFormat.format(getString(key), new Object[] { arg });
}
/**
* Gets a string from the resource bundle and formats it with arguments
*/
public static String getFormattedString(String key, Object[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -0,0 +1,591 @@
###############################################################################
# Copyright (c) 2000, 2003 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Common Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/cpl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# ------- AbstractOpenWizardAction -------
AbstractOpenWizardAction.noproject.title=New
AbstractOpenWizardAction.noproject.message=A project needs to be created first.\nOpen the 'New Project' wizard'?
AbstractOpenWizardAction.createerror.title=Open Wizard
AbstractOpenWizardAction.createerror.message=The wizard could not be opened. See log for details.
# ------- NewElementWizard -------
NewElementWizard.op_error.title=New
NewElementWizard.op_error.message=Creation of element failed.
NewElementWizard.typecomment.deprecated.title=Type Creation
NewElementWizard.typecomment.deprecated.message=You can configure the default layout of newly created files and types on the 'code generation' preference page. This was previously implemented on the template page in the templates 'filecomment' and 'typecomment'.
# ------- NewContainerWizardPage -------
NewContainerWizardPage.container.label=Source Fol&der:
NewContainerWizardPage.container.button=Br&owse...
NewContainerWizardPage.error.EnterContainerName=Folder name is empty.
NewContainerWizardPage.error.ContainerIsBinary=''{0}'' is a JAR archive.
NewContainerWizardPage.error.ContainerDoesNotExist=Folder ''{0}'' does not exist.
NewContainerWizardPage.error.NotAFolder=''{0}'' must be a project or folder.
NewContainerWizardPage.error.ProjectClosed=Project ''{0}'' must be accessible.
NewContainerWizardPage.warning.NotAJavaProject=Folder is not a Java project.
NewContainerWizardPage.warning.NotInAJavaProject=Folder is not in a Java project.
NewContainerWizardPage.warning.NotOnClassPath=Folder is not on the Java build class path.
NewContainerWizardPage.ChooseSourceContainerDialog.title=Folder Selection
NewContainerWizardPage.ChooseSourceContainerDialog.description=&Choose a folder:
# ------- NewPackageWizardPage -------
NewPackageCreationWizard.title=New Java Package
NewPackageWizardPage.package.label=&Name:
NewPackageWizardPage.error.InvalidPackageName=Invalid package name. {0}
NewPackageWizardPage.error.IsOutputFolder=Name conflict with output folder.
NewPackageWizardPage.error.PackageExists=Package already exists.
NewPackageWizardPage.error.EnterName=Enter a package name.
NewPackageWizardPage.warning.PackageNotShown=Package already exists. Note: Views might filter empty parent packages.
NewPackageWizardPage.warning.DiscouragedPackageName=Discouraged package name. {0}
NewPackageWizardPage.title=Java Package
NewPackageWizardPage.description=Create a Java package.
NewPackageWizardPage.info=Creates folders corresponding to packages.
# ------- NewTypeWizardPage -------
NewTypeWizardPage.package.label=Pac&kage:
NewTypeWizardPage.package.button=Bro&wse...
NewTypeWizardPage.enclosing.selection.label=Enclosing t&ype:
NewTypeWizardPage.enclosing.button=Bro&wse...
NewTypeWizardPage.error.InvalidPackageName=Package name is not valid. {0}
NewTypeWizardPage.error.ClashOutputLocation=Package clashes with project output folder.
NewTypeWizardPage.warning.DiscouragedPackageName=This package name is discouraged. {0}
NewTypeWizardPage.default=(default)
NewTypeWizardPage.ChoosePackageDialog.title=Package Selection
NewTypeWizardPage.ChoosePackageDialog.description=&Choose a folder:
NewTypeWizardPage.ChoosePackageDialog.empty=Cannot find packages to select.
NewTypeWizardPage.ChooseEnclosingTypeDialog.title=Enclosing Type Selection
NewTypeWizardPage.ChooseEnclosingTypeDialog.description=&Choose a type to which the new class will be added:
NewTypeWizardPage.error.EnclosingTypeEnterName=Name of enclosing type must be entered.
NewTypeWizardPage.error.EnclosingTypeNotExists=Enclosing type does not exist.
NewTypeWizardPage.error.EnclosingNotInCU=Enclosing type is binary.
NewTypeWizardPage.error.EnclosingNotEditable=Enclosing type is not editable.
NewTypeWizardPage.warning.EnclosingNotInSourceFolder=Enclosing type is not in specified source folder.
NewTypeWizardPage.typename.label=Na&me:
NewTypeWizardPage.superclass.label=&Superclass:
NewTypeWizardPage.superclass.button=Brows&e...
NewTypeWizardPage.interfaces.class.label=&Interfaces:
NewTypeWizardPage.interfaces.ifc.label=Extended &interfaces:
NewTypeWizardPage.interfaces.add=&Add...
NewTypeWizardPage.interfaces.remove=&Remove
NewTypeWizardPage.modifiers.acc.label=Modifiers:
NewTypeWizardPage.modifiers.public=&public
NewTypeWizardPage.modifiers.private=pri&vate
NewTypeWizardPage.modifiers.protected=pro&tected
NewTypeWizardPage.modifiers.default=defa&ult
NewTypeWizardPage.modifiers.abstract=abs&tract
NewTypeWizardPage.modifiers.final=fina&l
NewTypeWizardPage.modifiers.static=stati&c
NewTypeWizardPage.error.EnterTypeName=Type name is empty.
NewTypeWizardPage.error.TypeNameExists=Type already exists.
NewTypeWizardPage.error.InvalidTypeName=Type name is not valid. {0}
NewTypeWizardPage.error.QualifiedName=Type name must not be qualified.
NewTypeWizardPage.warning.TypeNameDiscouraged=Type name is discouraged. {0}
NewTypeWizardPage.error.InvalidSuperClassName=Superclass name is not valid.
NewTypeWizardPage.warning.SuperClassNotExists=Warning: Superclass does not exist in current project.
NewTypeWizardPage.warning.SuperClassIsFinal=Warning: Superclass ''{0}'' is final.
NewTypeWizardPage.warning.SuperClassIsNotVisible=Warning: Superclass ''{0}'' is not visible.
NewTypeWizardPage.warning.SuperClassIsNotClass=Warning: Superclass ''{0}'' is an interface.
NewTypeWizardPage.warning.InterfaceIsNotVisible=Extended interface ''{0}'' is not visible.
NewTypeWizardPage.warning.InterfaceNotExists=Extended interface ''{0}'' does not exist in current project.
NewTypeWizardPage.warning.InterfaceIsNotInterface=Extended interface ''{0}'' is not an interface.
NewTypeWizardPage.error.ModifiersFinalAndAbstract=Class cannot be both final and abstract
NewTypeWizardPage.SuperClassDialog.title=Superclass Selection
NewTypeWizardPage.SuperClassDialog.message=&Choose a type:
NewTypeWizardPage.InterfacesDialog.class.title= Implemented Interfaces Selection
NewTypeWizardPage.InterfacesDialog.interface.title= Extended Interfaces Selection
NewTypeWizardPage.InterfacesDialog.message=&Choose interfaces:
NewTypeWizardPage.operationdesc=Creating type....
# -----------NewClassWizardPage -------------
NewClassWizardPage.classname.label=&Name:
NewClassWizardPage.baseclass.label=&Base class:
NewClassWizardPage.baseclass.button=Brows&e...
NewClassWizardPage.baseclass.access.public=&public
NewClassWizardPage.baseclass.access.protected=pro&tected
NewClassWizardPage.baseclass.access.private=pri&vate
NewClassWizardPage.baseclass.access.access=&default
NewClassWizardPage.baseclass.access.label=Access:
NewClassWizardPage.constdest.virtualdestructor=&Virtual Destructor
NewClassWizardPage.constdest.inline=&Inline
NewClassWizardPage.files.header=Header File:
NewClassWizardPage.files.body=Body File:
NewClassWizardPage.files.linkFileButton=Link to file
NewClassWizardPage.error.EnterClassName=Class name is empty.
NewClassWizardPage.error.ClassNameExists=Class already exists.
NewClassWizardPage.error.InvalidClassName=Class name is not valid. {0}
NewClassWizardPage.error.QualifiedName=Class name must not be qualified.
NewClassWizardPage.warning.ClassNameDiscouraged=Class name is discouraged. {0}
NewClassWizardPage.error.InvalidBaseClassName=Base class name is not valid.
NewClassWizardPage.warning.BaseClassNotExists=Warning: Base class does not exist in current project.
# ------- BaseClassSelectionDialog -----
BaseClassSelectionDialog.title=Classes in this project
BaseClassSelectionDialog.message=Select a base class:
# ------- NewClassWizardPage -------
NewClassCreationWizard.title=New Java Class
NewClassWizardPage.title=Java Class
NewClassWizardPage.description=Create a new Java class.
NewClassWizardPage.methods.label=Which method stubs would you like to create?
NewClassWizardPage.methods.main=public static void main(Strin&g[] args)
NewClassWizardPage.methods.constructors=&Constructors from superclass
NewClassWizardPage.methods.inherited=In&herited abstract methods
# ------- NewInterfaceWizardPage -------
NewInterfaceCreationWizard.title=New Java Interface
NewInterfaceWizardPage.title=Java Interface
NewInterfaceWizardPage.description=Create a new Java interface.
# ------- JavaCapabilityWizard -------
JavaCapabilityWizard.title=Configure Java Capability
JavaCapabilityWizard.op_error.title=Error Configure Java Capability
JavaCapabilityWizard.op_error.message=An error occurred while configuring the Java project
# ------- JavaCapabilityConfigurationPage -------
JavaCapabilityConfigurationPage.title=Java Settings
JavaCapabilityConfigurationPage.description=Define the Java build settings.
JavaCapabilityConfigurationPage.op_desc_java=Configuring Java project...
# ------- NewProjectCreationWizard -------
NewProjectCreationWizard.title=New Java Project
NewProjectCreationWizard.op_error.title=Error Creating Java Project
NewProjectCreationWizard.op_error_create.message=An error occurred while creating the Java project
NewProjectCreationWizard.MainPage.title=Java Project
NewProjectCreationWizard.MainPage.description=Create a new Java project.
NewProjectCreationWizardPage.op_error.title=Error Creating Java Project
NewProjectCreationWizardPage.op_error_remove.message=An error occurred while removing a temporary project
NewProjectCreationWizardPage.EarlyCreationOperation.desc=Creating project and examining existing resources...
NewProjectCreationWizardPage.EarlyCreationOperation.error.title=New Java Project
NewProjectCreationWizardPage.EarlyCreationOperation.error.desc=An error occurred while creating project. Check log for details.
NewProjectCreationWizardPage.createproject.desc=Creating project...
NewProjectCreationWizardPage.removeproject.desc=Removing project...
# ------- NewJavaProjectWizardPage-------
NewJavaProjectWizardPage.title=Java Settings
NewJavaProjectWizardPage.description=Define the Java build settings.
NewJavaProjectWizardPage.op_desc=Creating Java project...
# ------- NewSourceFolderWizardPage-------
NewSourceFolderCreationWizard.title=New Source Folder
NewSourceFolderWizardPage.title=Source folder
NewSourceFolderWizardPage.description=Add a new source folder
NewSourceFolderWizardPage.root.label=Fol&der name:
NewSourceFolderWizardPage.root.button=Br&owse...
NewSourceFolderWizardPage.project.label=Project &name:
NewSourceFolderWizardPage.project.button=Bro&wse...
NewSourceFolderWizardPage.exclude.label=&Update exclusion filters in other source folders to solve nesting.
NewSourceFolderWizardPage.ChooseExistingRootDialog.title=Existing Folder Selection
NewSourceFolderWizardPage.ChooseExistingRootDialog.description=&Choose folder as source folder:
NewSourceFolderWizardPage.ChooseProjectDialog.title=Project Selection
NewSourceFolderWizardPage.ChooseProjectDialog.description=&Choose project for the new source folder:
NewSourceFolderWizardPage.error.EnterRootName=Root name must be entered.
NewSourceFolderWizardPage.error.InvalidRootName=Invalid folder name. {0}
NewSourceFolderWizardPage.error.NotAFolder=Not a folder.
NewSourceFolderWizardPage.error.AlreadyExisting=Already a source folder.
NewSourceFolderWizardPage.error.EnterProjectName=Project name must be entered.
NewSourceFolderWizardPage.error.InvalidProjectPath=Invalid project path.
NewSourceFolderWizardPage.error.NotAJavaProject=Project is not a Java project.
NewSourceFolderWizardPage.error.ProjectNotExists=Project does not exist.
NewSourceFolderWizardPage.warning.ReplaceSFandOL=To avoid overlapping, the existing project source folder entry will be replaced and the output folder set to ''{0}''.
NewSourceFolderWizardPage.warning.ReplaceOL=An exclusion pattern will be added to the project source folder entry and the output folder will be set to ''{0}''.
NewSourceFolderWizardPage.warning.ReplaceSF=To avoid overlapping, the existing project source folder entry will be replaced.
NewSourceFolderWizardPage.warning.AddedExclusions=Exclusion patterns of {0} source folder(s) updated to solve nesting.
# ------- NewSnippetFileWizardPage-------
NewSnippetFileCreationWizard.title=New Scrapbook Page
NewSnippetFileWizardPage.title=Create Java Scrapbook Page
NewSnippetFileWizardPage.error.AlreadyExists=A resource with the specified path already exists.
NewSnippetFileWizardPage.error.OnlyInJavaProject=The scrapbook page can only be created in a Java project.
NewSnippetFileWizardPage.open_error.message=Error in NewScrapbookPage
# ------- BuildPathsBlock -------
BuildPathsBlock.tab.source=&Source
BuildPathsBlock.tab.projects=&Projects
BuildPathsBlock.tab.libraries=&Libraries
BuildPathsBlock.tab.order=&Order and Export
BuildPathsBlock.classpath.label=Build &class path order and exported entries:\n(Exported entries are contributed to dependent projects)
BuildPathsBlock.classpath.up.button=&Up
BuildPathsBlock.classpath.down.button=&Down
BuildPathsBlock.classpath.checkall.button=Select &All
BuildPathsBlock.classpath.uncheckall.button=D&eselect All
BuildPathsBlock.buildpath.label=Defaul&t output folder:
BuildPathsBlock.buildpath.button=Bro&wse...
BuildPathsBlock.error.InvalidBuildPath=Invalid build output folder: ''{0}''
BuildPathsBlock.error.EnterBuildPath=Build output folder must be entered.
BuildPathsBlock.warning.EntryMissing=Build path entry is missing: {0}
BuildPathsBlock.warning.EntriesMissing={0} build path entries are missing.
BuildPathsBlock.operationdesc_project=Creating project...
BuildPathsBlock.operationdesc_java=Setting build paths...
BuildPathsBlock.ChooseOutputFolderDialog.title=Folder Selection
BuildPathsBlock.ChooseOutputFolderDialog.description=&Choose the folder for the build output:
BuildPathsBlock.RemoveBinariesDialog.title=Setting Build Paths
BuildPathsBlock.RemoveBinariesDialog.description=The output folder has changed. OK to remove all generated resources from the old location ''{0}''?
# ------- CPListLabelProvider -------
CPListLabelProvider.new=(new)
CPListLabelProvider.classcontainer=(class folder)
CPListLabelProvider.twopart={0} - {1}
CPListLabelProvider.willbecreated=(will be created)
# ------- SourceContainerWorkbookPage-------
SourceContainerWorkbookPage.folders.label=Source folders on build pat&h:
SourceContainerWorkbookPage.folders.remove.button=&Remove
SourceContainerWorkbookPage.folders.add.button=&Add Folder...
SourceContainerWorkbookPage.folders.edit.button=&Edit...
SourceContainerWorkbookPage.folders.check=Allow output folders for sour&ce folders.
SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title=Source Folder Selection
SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description=&Choose source folders to be added to the build path:
SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title=Source Folder Selection
SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description=&Select the source folder:
SourceContainerWorkbookPage.NewSourceFolderDialog.new.title=New Source Folder
SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title=Edit Source Folder
SourceContainerWorkbookPage.NewSourceFolderDialog.description=&Enter a path relative to ''{0}'':
SourceContainerWorkbookPage.ChangeOutputLocationDialog.title=Source Folder Added
SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message=Do you want to remove the project as source folder and update build output folder to ''{0}''?
SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message=Do you want to remove the project as source folder?
SourceContainerWorkbookPage.exclusion_added.title=Source Folder Added
SourceContainerWorkbookPage.exclusion_added.message=Exclusion filters have been added to nesting folders.
# ------- ProjectsWorkbookPage-------
ProjectsWorkbookPage.projects.label=&Required projects on the build path:
ProjectsWorkbookPage.projects.checkall.button=Select &All
ProjectsWorkbookPage.projects.uncheckall.button=&Deselect All
# ------- LibrariesWorkbookPage-------
LibrariesWorkbookPage.libraries.label=JARs &and class folders on the build path:
LibrariesWorkbookPage.libraries.remove.button=&Remove
LibrariesWorkbookPage.libraries.addjar.button=Add &JARs...
LibrariesWorkbookPage.libraries.addextjar.button=Add E&xternal JARs...
LibrariesWorkbookPage.libraries.addvariable.button=Add &Variable...
LibrariesWorkbookPage.libraries.addlibrary.button=Add Li&brary...
LibrariesWorkbookPage.libraries.addclassfolder.button=Add Class &Folder...
LibrariesWorkbookPage.libraries.edit.button=&Edit...
LibrariesWorkbookPage.ExistingClassFolderDialog.new.title=Class Folder Selection
LibrariesWorkbookPage.ExistingClassFolderDialog.new.description=&Choose class folders to be added to the build path:
LibrariesWorkbookPage.ExistingClassFolderDialog.edit.title=Edit Class Folder
LibrariesWorkbookPage.ExistingClassFolderDialog.edit.description=&Select the class folder:
LibrariesWorkbookPage.NewClassFolderDialog.new.title=New Class Folder
LibrariesWorkbookPage.NewClassFolderDialog.edit.title=Edit Class Folder
LibrariesWorkbookPage.NewClassFolderDialog.description=&Enter a path relative to ''{0}'':
LibrariesWorkbookPage.JARArchiveDialog.new.title=JAR Selection
LibrariesWorkbookPage.JARArchiveDialog.new.description=&Choose jar archives to be added to the build path:
LibrariesWorkbookPage.JARArchiveDialog.edit.title=Edit JAR
LibrariesWorkbookPage.JARArchiveDialog.edit.description=&Select the jar archive:
LibrariesWorkbookPage.ContainerDialog.new.title=Add Library
LibrariesWorkbookPage.ContainerDialog.edit.title=Edit Library
LibrariesWorkbookPage.VariableSelectionDialog.new.title=New Variable Classpath Entry
LibrariesWorkbookPage.VariableSelectionDialog.edit.title=Edit Variable Entry
LibrariesWorkbookPage.ExtJARArchiveDialog.new.title=JAR Selection
LibrariesWorkbookPage.ExtJARArchiveDialog.edit.title=Edit JAR
LibrariesWorkbookPage.SourceAttachmentDialog.title=Source For ''{0}''
LibrariesWorkbookPage.JavadocPropertyDialog.title=Javadoc For ''{0}''
LibrariesWorkbookPage.AdvancedDialog.title=Add Classpath Entry
LibrariesWorkbookPage.AdvancedDialog.description=Select the entry to add to the classpath:
LibrariesWorkbookPage.AdvancedDialog.createfolder=Create &New Class Folder
LibrariesWorkbookPage.AdvancedDialog.addfolder=Add &Existing Class Folder
LibrariesWorkbookPage.AdvancedDialog.addcontainer=Add &Container:
# ------- NewContainerDialog-------
NewContainerDialog.error.invalidpath=Invalid folder path: ''{0}''
NewContainerDialog.error.enterpath=Folder name must be entered
NewContainerDialog.error.pathexists=This folder is already in the list or it is an output folder.
# ------- NewSourceFolderDialog-------
NewSourceFolderDialog.error.invalidpath=Invalid folder path: ''{0}''
NewSourceFolderDialog.error.enterpath=Folder name must be entered.
NewSourceFolderDialog.error.pathexists=The folder is already in the list.
# ------- SourceAttachmentBlock-------
SourceAttachmentBlock.message=Select the location (folder, JAR or zip) containing the source for ''{0}'':
SourceAttachmentBlock.filename.description=Source attachments for variable entries are defined by variable paths. The first segment of such a path describes a variable name, the rest is an optional path extension.
SourceAttachmentBlock.filename.label=Lo&cation path:
SourceAttachmentBlock.filename.externalfile.button=External &File...
SourceAttachmentBlock.filename.externalfolder.button=External F&older...
SourceAttachmentBlock.filename.internal.button=&Workspace...
SourceAttachmentBlock.filename.varlabel=Lo&cation variable path:
SourceAttachmentBlock.filename.variable.button=&Variable...
SourceAttachmentBlock.filename.external.varbutton=&Extension....
SourceAttachmentBlock.filename.error.notvalid=The archive path is not a valid path.
SourceAttachmentBlock.filename.error.filenotexists=The path ''{0}'' does not exist.
SourceAttachmentBlock.filename.error.varnotexists=Variable in the location path does not exist.
SourceAttachmentBlock.filename.error.deviceinpath=Location must be described a variable path.
SourceAttachmentBlock.filename.warning.varempty=Location variable path is empty.
SourceAttachmentBlock.intjardialog.title=Source Location Selection
SourceAttachmentBlock.intjardialog.message=&Select folder or JAR/zip archive containing the source:
SourceAttachmentBlock.extvardialog.title=Variable Extension Selection
SourceAttachmentBlock.extvardialog.description=Select source location:
SourceAttachmentBlock.extjardialog.text=JAR/ZIP File Selection
SourceAttachmentBlock.extfolderdialog.text=Folder Selection
SourceAttachmentBlock.putoncpdialog.title=Setting Source Attachment
SourceAttachmentBlock.putoncpdialog.message=Source can only be attached to libraries on the build path.\nDo you want to add the library to the build path?
SourceAttachmentDialog.title=Source Attachment Configuration
SourceAttachmentDialog.error.title=Error Attaching Source
SourceAttachmentDialog.error.message=An error occurred while associating the source.
# ------- EditVariableEntryDialog -------
EditVariableEntryDialog.filename.varlabel=Edit classpath variable entry:
EditVariableEntryDialog.filename.variable.button=&Variable...
EditVariableEntryDialog.filename.external.varbutton=&Extension....
EditVariableEntryDialog.extvardialog.title=Variable Extension Selection
EditVariableEntryDialog.extvardialog.description=Select JAR archive:
EditVariableEntryDialog.filename.error.notvalid=The archive path is not a valid path.
EditVariableEntryDialog.filename.error.filenotexists=The path ''{0}'' does not point to an existing archive.
EditVariableEntryDialog.filename.error.varnotexists=Variable in the archive path does not exist.
EditVariableEntryDialog.filename.error.deviceinpath=The archive has to be described by a variable path.
EditVariableEntryDialog.filename.warning.varempty=Archive variable path is empty.
EditVariableEntryDialog.filename.error.alreadyexists=Classpath entry already exists.
# ------- VariableBlock-------
VariableBlock.vars.label=Defined &classpath variables:
VariableBlock.vars.add.button=Ne&w...
VariableBlock.vars.edit.button=&Edit...
VariableBlock.vars.remove.button=&Remove
VariableBlock.operation_desc=Setting classpath variables...
VariableBlock.operation_errror.title=Classpath Variables
VariableBlock.operation_errror.message=Problem while setting classpath variable. See log for details.
VariableBlock.needsbuild.title=Classpath Variables Changed
VariableBlock.needsbuild.message=The classpath variables have changed. A full rebuild is recommended to make changes effective. Do the full build now?
VariablePathDialogField.variabledialog.title=Variable Selection
CPVariableElementLabelProvider.reserved=(reserved)
CPVariableElementLabelProvider.empty=(empty)
# ------- VariableCreationDialog-------
VariableCreationDialog.titlenew=New Variable Entry
VariableCreationDialog.titleedit=Edit Variable Entry
VariableCreationDialog.name.label=&Name:
VariableCreationDialog.path.label=&Path:
VariableCreationDialog.path.file.button=&File...
VariableCreationDialog.path.dir.button=F&older...
VariableCreationDialog.error.entername=Variable name must be entered.
VariableCreationDialog.error.invalidname=Invalid name: ''{0}''.
VariableCreationDialog.error.nameexists=Variable name already exists.
VariableCreationDialog.error.invalidpath=The path is invalid.
VariableCreationDialog.warning.pathnotexists=Path does not exist.
VariableCreationDialog.extjardialog.text=JAR Selection
VariableCreationDialog.extdirdialog.text=Folder Selection
VariableCreationDialog.extdirdialog.message=&Specify folder to be represented by the variable:
# ------- NewVariableEntryDialog -------
NewVariableEntryDialog.vars.extend=E&xtend...
NewVariableEntryDialog.vars.config=&Edit...
NewVariableEntryDialog.vars.label=Select &variables to add to build path:
NewVariableEntryDialog.ExtensionDialog.title=Variable Extension
NewVariableEntryDialog.ExtensionDialog.description=Choose extensions to ''{0}''.
NewVariableEntryDialog.info.isfolder=Variable points to a folder: Click 'extend' to choose an archive inside the folder.
NewVariableEntryDialog.info.noselection=Select variable(s) to add to the classpath.
NewVariableEntryDialog.info.selected={0} variables selected.
# ------- OutputLocationDialog -------
OutputLocationDialog.title=Source Folder Output Location
OutputLocationDialog.usedefault.label=Project's default output folder.
OutputLocationDialog.usespecific.label=Specific output folder (path relative to ''{0}'').
OutputLocationDialog.location.button=Bro&wse...
OutputLocationDialog.error.existingisfile=Location is an existing file
OutputLocationDialog.error.invalidpath=Invalid path: {0}
OutputLocationDialog.ChooseOutputFolder.title=Folder Selection
OutputLocationDialog.ChooseOutputFolder.description=&Choose the folder for the build output:
# ------- ExclusionPatternDialog -------
ExclusionPatternDialog.title=Source Folder Exclusion Patterns
ExclusionPatternDialog.pattern.label=E&xclusion patterns for ''{0}'':
ExclusionPatternDialog.pattern.add=A&dd...
ExclusionPatternDialog.pattern.add.multiple=Add &Multiple...
ExclusionPatternDialog.pattern.remove=&Remove
ExclusionPatternDialog.pattern.edit=&Edit...
ExclusionPatternDialog.ChooseExclusionPattern.title=Exclusion Pattern Selection
ExclusionPatternDialog.ChooseExclusionPattern.description=&Choose folders or files to exclude:
# ------- ExclusionPatternEntryDialog -------
ExclusionPatternEntryDialog.add.title=Add Exclusion Pattern
ExclusionPatternEntryDialog.edit.title=Edit Exclusion Pattern
ExclusionPatternEntryDialog.description=Enter a pattern for excluding files from the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'java/util/A*.java', 'java/util/', '**/Test*'.
ExclusionPatternEntryDialog.pattern.label=E&xclusion pattern (Path relative to ''{0}''):
ExclusionPatternEntryDialog.pattern.button=Bro&wse...
ExclusionPatternEntryDialog.error.empty=Enter a pattern.
ExclusionPatternEntryDialog.error.notrelative=Pattern must be a relative path.
ExclusionPatternEntryDialog.error.exists=Pattern already exists.
ExclusionPatternEntryDialog.ChooseExclusionPattern.title=Exclusion Pattern Selection
ExclusionPatternEntryDialog.ChooseExclusionPattern.description=&Choose a folder or file to exclude:
# ------- ClasspathContainerDefaultPage-------
ClasspathContainerDefaultPage.title=Classpath Container
ClasspathContainerDefaultPage.description=Select classpath container path. First segment is the container type.
ClasspathContainerDefaultPage.path.label=&Classpath container path:
ClasspathContainerDefaultPage.path.error.enterpath=Enter path.
ClasspathContainerDefaultPage.path.error.invalidpath=Invalid path.
ClasspathContainerDefaultPage.path.error.needssegment=Path needs at least one segment.
ClasspathContainerDefaultPage.path.error.alreadyexists=Entry already exists.
# ------- ClasspathContainerSelectionPage-------
ClasspathContainerSelectionPage.title=Add Library
ClasspathContainerSelectionPage.description=Select the library type to add.
# ------- ClasspathContainerWizard-------
ClasspathContainerWizard.pagecreationerror.title= Library Wizard
ClasspathContainerWizard.pagecreationerror.message=Wizard page creation failed. Check log for details.
FolderSelectionDialog.button=Create New Folder...
CPListLabelProvider.none=(None)
CPListLabelProvider.source_attachment.label=Source attachment:
CPListLabelProvider.source_attachment_root.label=Source attachment root:
CPListLabelProvider.javadoc_location.label=Javadoc location:
CPListLabelProvider.output_folder.label=Output folder:
CPListLabelProvider.default_output_folder.label=(Default output folder)
CPListLabelProvider.exclusion_filter.label=Exclusion filter:
CPListLabelProvider.exclusion_filter_separator=;
CPListLabelProvider.unknown_element.label=unknown element
NewSourceFolderDialog.useproject.button=&Project as source folder
NewSourceFolderDialog.usefolder.button=&Folder as source folder
NewSourceFolderDialog.sourcefolder.label=&Source folder name:

View file

@ -5,16 +5,14 @@ package org.eclipse.cdt.internal.ui.wizards.dialogfields;
* All Rights Reserved.
*/
import org.eclipse.jface.util.Assert;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
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.jface.util.Assert;
import org.eclipse.cdt.internal.ui.wizards.swt.MGridData;
public class DialogField {
private Label fLabel;
@ -24,34 +22,72 @@ public class DialogField {
private boolean fEnabled;
protected final void assertCompositeNotNull(Composite comp) {
Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$
public DialogField() {
fEnabled= true;
fLabel= null;
fLabelText= ""; //$NON-NLS-1$
}
protected final void assertEnoughColumns(int nColumns) {
Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$
/**
* Sets the label of the dialog field.
*/
public void setLabelText(String labeltext) {
fLabelText= labeltext;
}
public static Control createEmptySpace(Composite parent, int span) {
Label label= new Label(parent, SWT.LEFT);
MGridData gd= new MGridData();
gd.horizontalAlignment= MGridData.BEGINNING;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
gd.horizontalIndent= 0;
gd.widthHint= 0;
gd.heightHint= 0;
label.setLayoutData(gd);
return label;
}
public static Control createEmptySpace(Composite parent) {
return createEmptySpace(parent, 1);
// ------ change listener
/**
* Defines the listener for this dialog field.
*/
public final void setDialogFieldListener(IDialogFieldListener listener) {
fDialogFieldListener= listener;
}
/**
* Programatical invocation of a dialog field change.
*/
public void dialogFieldChanged() {
if (fDialogFieldListener != null) {
fDialogFieldListener.dialogFieldChanged(this);
}
}
// ------- focus management
/**
* Tries to set the focus to the dialog field.
* Returns <code>true</code> if the dialog field can take focus.
* To be reimplemented by dialog field implementors.
*/
public boolean setFocus() {
return false;
}
/**
* Posts <code>setFocus</code> to the display event queue.
*/
public void postSetFocusOnDialogField(Display display) {
if (display != null) {
display.asyncExec(
new Runnable() {
public void run() {
setFocus();
}
}
);
}
}
// ------- layout helpers
/**
* Creates all controls of the dialog field and fills it to a composite.
* The composite is assumed to have <code>MGridLayout</code> as
* layout.
* The dialog field will adjust its controls' spans to the number of columns given.
* To be reimplemented by dialog field implementors.
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
@ -60,13 +96,33 @@ public class DialogField {
return new Control[] { label };
}
/**
* Returns the number of columns of the dialog field.
* To be reimplemented by dialog field implementors.
*/
public int getNumberOfControls() {
return 1;
}
protected static GridData gridDataForLabel(int span) {
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= span;
return gd;
}
// ------- ui creation
/**
* Creates or returns the created label widget.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Label getLabelControl(Composite parent) {
if (fLabel == null) {
assertCompositeNotNull(parent);
fLabel= new Label(parent, SWT.LEFT);
fLabel= new Label(parent, SWT.LEFT | SWT.WRAP);
fLabel.setFont(parent.getFont());
fLabel.setEnabled(fEnabled);
if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$
@ -79,60 +135,79 @@ public class DialogField {
}
return fLabel;
}
public int getNumberOfControls() {
return 1;
/**
* Creates a spacer control.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent) {
return createEmptySpace(parent, 1);
}
protected static MGridData gridDataForLabel(int span) {
MGridData gd= new MGridData();
/**
* Creates a spacer control with the given span.
* The composite is assumed to have <code>MGridLayout</code> as
* layout.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent, int span) {
Label label= new Label(parent, SWT.LEFT);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
return gd;
gd.horizontalIndent= 0;
gd.widthHint= 0;
gd.heightHint= 0;
label.setLayoutData(gd);
return label;
}
public boolean isEnabled() {
return fEnabled;
}
protected boolean isOkToUse(Control control) {
/**
* Tests is the control is not <code>null</code> and not disposed.
*/
protected final boolean isOkToUse(Control control) {
return (control != null) && !(control.isDisposed());
}
public void postSetFocusOnDialogField(Display display) {
if (display != null) {
display.asyncExec(
new Runnable() {
public void run() {
setFocus();
}
}
);
}
}
// ------ change listener
public void setDialogFieldListener(IDialogFieldListener listener) {
fDialogFieldListener= listener;
}
// --------- enable / disable management
public void setEnabled(boolean enabled) {
/**
* Sets the enable state of the dialog field.
*/
public final void setEnabled(boolean enabled) {
if (enabled != fEnabled) {
fEnabled= enabled;
updateEnableState();
}
}
// ------- focus management
public boolean setFocus() {
return false;
}
public void setLabelText(String labeltext) {
fLabelText= labeltext;
}
/**
* Called when the enable state changed.
* To be extended by dialog field implementors.
*/
protected void updateEnableState() {
if (fLabel != null) {
fLabel.setEnabled(fEnabled);
}
}
public DialogField() {
fEnabled= true;
fLabel= null;
fLabelText= ""; //$NON-NLS-1$
/**
* Gets the enable state of the dialog field.
*/
public final boolean isEnabled() {
return fEnabled;
}
protected final void assertCompositeNotNull(Composite comp) {
Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$
}
protected final void assertEnoughColumns(int nColumns) {
Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,33 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
/**
* Change listener used by <code>ListDialogField</code> and <code>CheckedListDialogField</code>
*/
public interface IListAdapter {
/**
* A button from the button bar has been pressed.
*/
void customButtonPressed(ListDialogField field, int index);
/**
* The selection of the list has changed.
*/
void selectionChanged(ListDialogField field);
/**
* En entry in the list has been double clicked
*/
void doubleClicked(ListDialogField field);
}

View file

@ -0,0 +1,140 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
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;
public class LayoutUtil {
/**
* Calculates the number of columns needed by field editors
*/
public static int getNumberOfColumns(DialogField[] editors) {
int nCulumns= 0;
for (int i= 0; i < editors.length; i++) {
nCulumns= Math.max(editors[i].getNumberOfControls(), nCulumns);
}
return nCulumns;
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop) {
doDefaultLayout(parent, editors, labelOnTop, 0, 0, 0, 0);
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
* @param minWidth The minimal width of the composite
* @param minHeight The minimal height of the composite
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight) {
doDefaultLayout(parent, editors, labelOnTop, minWidth, minHeight, 0, 0);
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
* @param minWidth The minimal width of the composite
* @param minHeight The minimal height of the composite
* @param marginWidth The margin width to be used by the composite
* @param marginHeight The margin height to be used by the composite
* @deprecated
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight, int marginWidth, int marginHeight) {
int nCulumns= getNumberOfColumns(editors);
Control[][] controls= new Control[editors.length][];
for (int i= 0; i < editors.length; i++) {
controls[i]= editors[i].doFillIntoGrid(parent, nCulumns);
}
if (labelOnTop) {
nCulumns--;
modifyLabelSpans(controls, nCulumns);
}
GridLayout layout= new GridLayout();
if (marginWidth != SWT.DEFAULT) {
layout.marginWidth= marginWidth;
}
if (marginHeight != SWT.DEFAULT) {
layout.marginHeight= marginHeight;
}
layout.numColumns= nCulumns;
parent.setLayout(layout);
}
private static void modifyLabelSpans(Control[][] controls, int nCulumns) {
for (int i= 0; i < controls.length; i++) {
setHorizontalSpan(controls[i][0], nCulumns);
}
}
/**
* Sets the span of a control. Assumes that GridData is used.
*/
public static void setHorizontalSpan(Control control, int span) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).horizontalSpan= span;
} else if (span != 1) {
GridData gd= new GridData();
gd.horizontalSpan= span;
control.setLayoutData(gd);
}
}
/**
* Sets the width hint of a control. Assumes that GridData is used.
*/
public static void setWidthHint(Control control, int widthHint) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).widthHint= widthHint;
}
}
/**
* Sets the heigthHint hint of a control. Assumes that GridData is used.
*/
public static void setHeigthHint(Control control, int heigthHint) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).heightHint= heigthHint;
}
}
/**
* Sets the horizontal indent of a control. Assumes that GridData is used.
*/
public static void setHorizontalIndent(Control control, int horizontalIndent) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).horizontalIndent= horizontalIndent;
}
}
/**
* Sets the horizontal indent of a control. Assumes that GridData is used.
*/
public static void setHorizontalGrabbing(Control control) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).grabExcessHorizontalSpace= true;
}
}
}

View file

@ -0,0 +1,392 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
import java.io.File;
import org.eclipse.cdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.dialogs.PathVariableSelectionDialog;
/**
*/
public class LinkToFileGroup extends StringButtonDialogField {
private String fText;
private Listener listener;
private String initialLinkTarget;
private int type;
private boolean createLink = false;
// used to compute layout sizes
//private FontMetrics fontMetrics;
// widgets
//private Composite groupComposite;
private Text linkTargetField;
private Button linkButton;
private Button browseButton;
private Button variablesButton;
private Label resolvedPathLabelText;
private Label resolvedPathLabelData;
public LinkToFileGroup(IStringButtonAdapter adapter, Listener listener) {
super(adapter);
this.listener = listener;
this.type = IResource.FILE;
}
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
//initializeDialogUnits(parent);
Label label= getLabelControl(parent);
label.setLayoutData(gridDataForLabel(1));
Button checkButton = getLinkCheckButtonControl(parent);
Text text= getTextControl(parent);
text.setLayoutData(gridDataForText(1));
Button browseButton = getBrowseButtonControl(parent);
browseButton.setLayoutData(gridDataForButton(browseButton, 1));
Button variablesButton = getVariablesButtonControl(parent);
variablesButton.setLayoutData(gridDataForButton(variablesButton, 1));
DialogField.createEmptySpace(parent);
resolvedPathLabelText = new Label(parent, SWT.SINGLE);
resolvedPathLabelText.setText(WorkbenchMessages.getString("CreateLinkedResourceGroup.resolvedPathLabel")); //$NON-NLS-1$
resolvedPathLabelText.setVisible(true);
resolvedPathLabelData = new Label(parent, SWT.SINGLE);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 3;
resolvedPathLabelData.setLayoutData(data);
resolvedPathLabelData.setVisible(true);
return null;
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 5;
}
public Button getLinkCheckButtonControl(Composite parent){
if(linkButton == null){
linkButton = new Button(parent, SWT.CHECK);
linkButton.setText(NewWizardMessages.getString("NewClassWizardPage.files.linkFileButton")); //$NON-NLS-1$
linkButton.setSelection(createLink);
linkButton.setFont(parent.getFont());
SelectionListener selectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
createLink = linkButton.getSelection();
browseButton.setEnabled(createLink);
variablesButton.setEnabled(createLink);
linkTargetField.setEnabled(createLink);
if (listener != null)
listener.handleEvent(new Event());
}
};
linkButton.addSelectionListener(selectionListener);
}
return linkButton;
}
public String getText() {
return linkTargetField.getText();
}
public void setText(String text) {
fText= text;
if (isOkToUse(linkTargetField)) {
linkTargetField.setText(text);
} else {
dialogFieldChanged();
}
}
public Text getTextControl(Composite parent){
if(linkTargetField == null){
assertCompositeNotNull(parent);
linkTargetField = new Text(parent, SWT.BORDER);
linkTargetField.setFont(parent.getFont());
linkTargetField.setEnabled(createLink);
linkTargetField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
resolveVariable();
if (listener != null)
listener.handleEvent(new Event());
}
});
if (initialLinkTarget != null)
linkTargetField.setText(initialLinkTarget);
}
return linkTargetField;
}
public static GridData gridDataForText(int span){
GridData data = new GridData();
data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH;
data.horizontalAlignment= GridData.FILL;
data.grabExcessHorizontalSpace= false;
data.horizontalSpan= span;
return data;
}
public Button getBrowseButtonControl(Composite parent){
// browse button
if(browseButton == null){
assertCompositeNotNull(parent);
browseButton = new Button(parent, SWT.PUSH);
//setButtonLayoutData(browseButton);
browseButton.setFont(parent.getFont());
browseButton.setText(WorkbenchMessages.getString("CreateLinkedResourceGroup.browseButton")); //$NON-NLS-1$
browseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
handleLinkTargetBrowseButtonPressed();
}
});
browseButton.setEnabled(createLink);
}
return browseButton;
}
public Button getVariablesButtonControl(Composite parent){
// variables button
if(variablesButton == null){
assertCompositeNotNull(parent);
variablesButton = new Button(parent, SWT.PUSH);
//setButtonLayoutData(variablesButton);
variablesButton.setFont(parent.getFont());
variablesButton.setText(WorkbenchMessages.getString("CreateLinkedResourceGroup.variablesButton")); //$NON-NLS-1$
variablesButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
handleVariablesButtonPressed();
}
});
variablesButton.setEnabled(createLink);
}
return variablesButton;
}
/**
* Returns a new status object with the given severity and message.
*
* @return a new status object with the given severity and message.
*/
private IStatus createStatus(int severity, String message) {
return new Status(
severity,
WorkbenchPlugin.getDefault().getDescriptor().getUniqueIdentifier(),
severity,
message,
null);
}
/**
* Returns the link target location entered by the user.
*
* @return the link target location entered by the user. null if the user
* chose not to create a link.
*/
public String getLinkTarget() {
if (createLink && linkTargetField != null && linkTargetField.isDisposed() == false)
return linkTargetField.getText();
return null;
}
public String getResolvedPath() {
if (createLink && resolvedPathLabelData != null && resolvedPathLabelData.isDisposed() == false)
return resolvedPathLabelData.getText();
return null;
}
/**
* Opens a file or directory browser depending on the link type.
*/
private void handleLinkTargetBrowseButtonPressed() {
String linkTargetName = linkTargetField.getText();
File file = null;
String selection = null;
if ("".equals(linkTargetName) == false) { //$NON-NLS-1$
file = new File(linkTargetName);
if (file.exists() == false)
file = null;
}
if (type == IResource.FILE) {
FileDialog dialog = new FileDialog(linkTargetField.getShell());
if (file != null) {
if (file.isFile())
dialog.setFileName(linkTargetName);
else
dialog.setFilterPath(linkTargetName);
}
selection = dialog.open();
}
else {
DirectoryDialog dialog = new DirectoryDialog(linkTargetField.getShell());
if (file != null) {
if (file.isFile())
linkTargetName = file.getParent();
if (linkTargetName != null)
dialog.setFilterPath(linkTargetName);
}
dialog.setMessage(WorkbenchMessages.getString("CreateLinkedResourceGroup.targetSelectionLabel")); //$NON-NLS-1$
selection = dialog.open();
}
if (selection != null)
linkTargetField.setText(selection);
}
/**
* Opens a path variable selection dialog
*/
private void handleVariablesButtonPressed() {
int variableTypes = IResource.FOLDER;
// allow selecting file and folder variables when creating a
// linked file
if (type == IResource.FILE)
variableTypes |= IResource.FILE;
PathVariableSelectionDialog dialog =
new PathVariableSelectionDialog(linkTargetField.getShell(), variableTypes);
if (dialog.open() == IDialogConstants.OK_ID) {
String[] variableNames = (String[]) dialog.getResult();
if (variableNames != null && variableNames.length == 1)
linkTargetField.setText(variableNames[0]);
}
}
/**
* Tries to resolve the value entered in the link target field as
* a variable, if the value is a relative path.
* Displays the resolved value if the entered value is a variable.
*/
private void resolveVariable() {
if(!linkTargetField.isEnabled())
return;
IPathVariableManager pathVariableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
IPath path = new Path(linkTargetField.getText());
IPath resolvedPath = pathVariableManager.resolvePath(path);
/* (path.equals(resolvedPath)) {
resolvedPathLabelText.setVisible(false);
resolvedPathLabelData.setVisible(false);
} else {
resolvedPathLabelText.setVisible(true);
resolvedPathLabelData.setVisible(true);
}
*/
resolvedPathLabelData.setText(resolvedPath.toOSString());
}
/**
* Sets the value of the link target field
*
* @param target the value of the link target field
*/
public void setLinkTarget(String target) {
initialLinkTarget = target;
if (linkTargetField != null && linkTargetField.isDisposed() == false)
linkTargetField.setText(target);
}
/**
* Validates the type of the given file against the link type specified
* in the constructor.
*
* @param linkTargetFile file to validate
* @return IStatus indicating the validation result. IStatus.OK if the
* given file is valid.
*/
private IStatus validateFileType(File linkTargetFile) {
if (type == IResource.FILE && linkTargetFile.isFile() == false) {
return createStatus(
IStatus.ERROR,
WorkbenchMessages.getString("CreateLinkedResourceGroup.linkTargetNotFile")); //$NON-NLS-1$
} else if (type == IResource.FOLDER && linkTargetFile.isDirectory() == false) {
return createStatus(
IStatus.ERROR,
WorkbenchMessages.getString("CreateLinkedResourceGroup.linkTargetNotFolder")); //$NON-NLS-1$
}
return createStatus(IStatus.OK, ""); //$NON-NLS-1$
}
/**
* Validates this page's controls.
*
* @return IStatus indicating the validation result. IStatus.OK if the
* specified link target is valid given the linkHandle.
*/
public IStatus validateLinkLocation(IResource linkHandle) {
if (linkTargetField == null || linkTargetField.isDisposed())
return createStatus(IStatus.OK, ""); //$NON-NLS-1$
IWorkspace workspace = WorkbenchPlugin.getPluginWorkspace();
String linkTargetName = linkTargetField.getText();
IPath path = new Path(linkTargetName);
if (createLink == false)
return createStatus(IStatus.OK, ""); //$NON-NLS-1$
IStatus locationStatus = workspace.validateLinkLocation(linkHandle, path);
if (locationStatus.getSeverity() == IStatus.ERROR)
return locationStatus;
// use the resolved link target name
linkTargetName = resolvedPathLabelData.getText();
path = new Path(linkTargetName);
File linkTargetFile = new Path(linkTargetName).toFile();
if (linkTargetFile.exists()) {
IStatus fileTypeStatus = validateFileType(linkTargetFile);
if (fileTypeStatus.isOK() == false)
return fileTypeStatus;
} else if (locationStatus.getSeverity() == IStatus.OK) {
// locationStatus takes precedence over missing location warning.
return createStatus(
IStatus.WARNING,
WorkbenchMessages.getString("CreateLinkedResourceGroup.linkTargetNonExistent")); //$NON-NLS-1$
}
return locationStatus;
}
public boolean linkCreated (){
return createLink;
}
}

View file

@ -0,0 +1,894 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
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.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
import org.eclipse.cdt.internal.ui.util.TableLayoutComposite;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class ListDialogField extends DialogField {
public static class ColumnsDescription {
private ColumnLayoutData[] columns;
private String[] headers;
private boolean drawLines;
public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) {
this.columns= columns;
this.headers= headers;
this.drawLines= drawLines;
}
public ColumnsDescription(String[] headers, boolean drawLines) {
this(createColumnWeightData(headers.length), headers, drawLines);
}
public ColumnsDescription(int nColumns, boolean drawLines) {
this(createColumnWeightData(nColumns), null, drawLines);
}
private static ColumnLayoutData[] createColumnWeightData(int nColumns) {
ColumnLayoutData[] data= new ColumnLayoutData[nColumns];
for (int i= 0; i < nColumns; i++) {
data[i]= new ColumnWeightData(1);
}
return data;
}
}
protected TableViewer fTable;
protected ILabelProvider fLabelProvider;
protected ListViewerAdapter fListViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Control fTableControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private IListAdapter fListAdapter;
private Object fParentElement;
private ColumnsDescription fTableColumns;
/**
* Creates the <code>ListDialogField</code>.
* @param adapter A listener for button invocation, selection changes. Can
* be <code>null</code>.
* @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and
* marks a separator.
* @param lprovider The label provider to render the table entries
*/
public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fListAdapter= adapter;
fLabelProvider= lprovider;
fListViewerAdapter= new ListViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTable= null;
fTableControl= null;
fButtonsControl= null;
fTableColumns= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
}
/**
* Sets the index of the 'remove' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'remove' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'up' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'down' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
public void setTableColumns(ColumnsDescription column) {
fTableColumns= column;
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index) && fListAdapter != null) {
fListAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getListControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the list control. When called the first time, the control will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getListControl(Composite parent) {
if (fTableControl == null) {
assertCompositeNotNull(parent);
if (fTableColumns == null) {
fTable= createTableViewer(parent);
Table tableControl= fTable.getTable();
fTableControl= tableControl;
tableControl.setLayout(new TableLayout());
} else {
TableLayoutComposite composite= new TableLayoutComposite(parent, SWT.NONE);
fTableControl= composite;
fTable= createTableViewer(composite);
Table tableControl= fTable.getTable();
tableControl.setHeaderVisible(fTableColumns.headers != null);
tableControl.setLinesVisible(fTableColumns.drawLines);
ColumnLayoutData[] columns= fTableColumns.columns;
for (int i= 0; i < columns.length; i++) {
composite.addColumnData(columns[i]);
TableColumn column= new TableColumn(tableControl, SWT.NONE);
//tableLayout.addColumnData(columns[i]);
if (fTableColumns.headers != null) {
column.setText(fTableColumns.headers[i]);
}
}
}
fTable.getTable().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
//fTableControl.setLayout(tableLayout);
fTable.setContentProvider(fListViewerAdapter);
fTable.setLabelProvider(fLabelProvider);
fTable.addSelectionChangedListener(fListViewerAdapter);
fTable.addDoubleClickListener(fListViewerAdapter);
fTable.setInput(fParentElement);
if (fViewerSorter != null) {
fTable.setSorter(fViewerSorter);
}
fTableControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTableControl;
}
/**
* Returns the internally used table viewer.
*/
public TableViewer getTableViewer() {
return fTable;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getListStyle(){
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ;
if (fTableColumns != null) {
style |= SWT.FULL_SELECTION;
}
return style;
}
protected TableViewer createTableViewer(Composite parent) {
Table table= new Table(parent, getListStyle());
return new TableViewer(table);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
}
}
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTable.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean getManagedButtonState(ISelection sel, int index) {
if (index == fRemoveButtonIndex) {
return !sel.isEmpty();
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && canMoveUp();
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && canMoveDown();
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTableControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTable.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTableControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the elements shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
fElements.set(idx, newElement);
if (fTable != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
fTable.refresh();
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTable != null) {
fTable.add(elementsToAdd.toArray());
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTable != null) {
fTable.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTable != null) {
fTable.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTable != null) {
fTable.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTable, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTableControl)) {
Display d= fTableControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTableControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the table.
*/
public void refresh() {
if (fTable != null) {
fTable.refresh();
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTable.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTable.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size()-1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp() {
if (isOkToUse(fTableControl)) {
int[] indc= fTable.getTable().getSelectionIndices();
for (int i= 0; i < indc.length; i++) {
if (indc[i] != i) {
return true;
}
}
}
return false;
}
private boolean canMoveDown() {
if (isOkToUse(fTableControl)) {
int[] indc= fTable.getTable().getSelectionIndices();
int k= fElements.size() - 1;
for (int i= indc.length - 1; i >= 0 ; i--, k--) {
if (indc[i] != k) {
return true;
}
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
List result= new ArrayList();
if (fTable != null) {
ISelection selection= fTable.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return result;
}
// ------- ListViewerAdapter
private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener {
// ------- ITableContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
doDoubleClick(event);
}
}
protected void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fListAdapter != null) {
fListAdapter.selectionChanged(this);
}
}
protected void doDoubleClick(DoubleClickEvent event) {
if (fListAdapter != null) {
fListAdapter.doubleClicked(this);
}
}
}

View file

@ -0,0 +1,256 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.util.Assert;
/**
* Dialog field describing a group with buttons (Checkboxes, radio buttons..)
*/
public class SelectionButtonDialogFieldGroup extends DialogField {
private Composite fButtonComposite;
private Button[] fButtons;
private String[] fButtonNames;
private boolean[] fButtonsSelected;
private boolean[] fButtonsEnabled;
private int fGroupBorderStyle;
private int fGroupNumberOfColumns;
private int fButtonsStyle;
/**
* Creates a group without border.
*/
public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns) {
this(buttonsStyle, buttonNames, nColumns, SWT.NONE);
}
/**
* Creates a group with border (label in border).
* Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE
* For border styles see <code>Group</code>
*/
public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) {
super();
Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE);
fButtonNames= buttonNames;
int nButtons= buttonNames.length;
fButtonsSelected= new boolean[nButtons];
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsSelected[i]= false;
fButtonsEnabled[i]= true;
}
if (fButtonsStyle == SWT.RADIO) {
fButtonsSelected[0]= true;
}
fGroupBorderStyle= borderStyle;
fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns;
fButtonsStyle= buttonsStyle;
}
// ------- layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
if (fGroupBorderStyle == SWT.NONE) {
Label label= getLabelControl(parent);
label.setLayoutData(gridDataForLabel(1));
Composite buttonsgroup= getSelectionButtonsGroup(parent);
GridData gd= new GridData();
gd.horizontalSpan= nColumns - 1;
buttonsgroup.setLayoutData(gd);
return new Control[] { label, buttonsgroup };
} else {
Composite buttonsgroup= getSelectionButtonsGroup(parent);
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
buttonsgroup.setLayoutData(gd);
return new Control[] { buttonsgroup };
}
}
/*
* @see DialogField#doFillIntoGrid
*/
public int getNumberOfControls() {
return (fGroupBorderStyle == SWT.NONE) ? 2 : 1;
}
// ------- ui creation
private Button createSelectionButton(int index, Composite group, SelectionListener listener) {
Button button= new Button(group, fButtonsStyle | SWT.LEFT);
button.setFont(group.getFont());
button.setText(fButtonNames[index]);
button.setEnabled(isEnabled() && fButtonsEnabled[index]);
button.setSelection(fButtonsSelected[index]);
button.addSelectionListener(listener);
button.setLayoutData(new GridData());
return button;
}
/**
* Returns the group widget. When called the first time, the widget will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getSelectionButtonsGroup(Composite parent) {
if (fButtonComposite == null) {
assertCompositeNotNull(parent);
GridLayout layout= new GridLayout();
layout.makeColumnsEqualWidth= true;
layout.numColumns= fGroupNumberOfColumns;
if (fGroupBorderStyle != SWT.NONE) {
Group group= new Group(parent, fGroupBorderStyle);
if (fLabelText != null && fLabelText.length() > 0) {
group.setText(fLabelText);
}
fButtonComposite= group;
} else {
fButtonComposite= new Composite(parent, SWT.NULL);
layout.marginHeight= 0;
layout.marginWidth= 0;
}
fButtonComposite.setLayout(layout);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doWidgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doWidgetSelected(e);
}
};
int nButtons= fButtonNames.length;
fButtons= new Button[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtons[i]= createSelectionButton(i, fButtonComposite, listener);
}
int nRows= nButtons / fGroupNumberOfColumns;
int nFillElements= nRows * fGroupNumberOfColumns - nButtons;
for (int i= 0; i < nFillElements; i++) {
createEmptySpace(fButtonComposite);
}
}
return fButtonComposite;
}
/**
* Returns a button from the group or <code>null</code> if not yet created.
*/
public Button getSelectionButton(int index) {
if (index >= 0 && index < fButtons.length) {
return fButtons[index];
}
return null;
}
private void doWidgetSelected(SelectionEvent e) {
Button button= (Button)e.widget;
for (int i= 0; i < fButtons.length; i++) {
if (fButtons[i] == button) {
fButtonsSelected[i]= button.getSelection();
dialogFieldChanged();
return;
}
}
}
// ------ model access
/**
* Returns the selection state of a button contained in the group.
* @param The index of the button
*/
public boolean isSelected(int index) {
if (index >= 0 && index < fButtonsSelected.length) {
return fButtonsSelected[index];
}
return false;
}
/**
* Sets the selection state of a button contained in the group.
*/
public void setSelection(int index, boolean selected) {
if (index >= 0 && index < fButtonsSelected.length) {
if (fButtonsSelected[index] != selected) {
fButtonsSelected[index]= selected;
if (fButtons != null) {
Button button= fButtons[index];
if (isOkToUse(button)) {
button.setSelection(selected);
}
}
}
}
}
// ------ enable / disable management
protected void updateEnableState() {
super.updateEnableState();
if (fButtons != null) {
boolean enabled= isEnabled();
for (int i= 0; i < fButtons.length; i++) {
Button button= fButtons[i];
if (isOkToUse(button)) {
button.setEnabled(enabled && fButtonsEnabled[i]);
}
}
}
}
/**
* Sets the enable state of a button contained in the group.
*/
public void enableSelectionButton(int index, boolean enable) {
if (index >= 0 && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
if (fButtons != null) {
Button button= fButtons[index];
if (isOkToUse(button)) {
button.setEnabled(isEnabled() && enable);
}
}
}
}
}

View file

@ -0,0 +1,95 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridData;
/**
* Dialog field describing a separator.
*/
public class Separator extends DialogField {
private Label fSeparator;
private int fStyle;
public Separator() {
this(SWT.NONE);
}
/**
* @param style of the separator. See <code>Label</code> for possible
* styles.
*/
public Separator(int style) {
super();
fStyle= style;
}
// ------- layout helpers
/**
* Creates the separator and fills it in a MGridLayout.
* @param height The heigth of the separator
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns, int height) {
assertEnoughColumns(nColumns);
Control separator= getSeparator(parent);
separator.setLayoutData(gridDataForSeperator(nColumns, height));
return new Control[] { separator };
}
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
return doFillIntoGrid(parent, nColumns, 4);
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 1;
}
protected static GridData gridDataForSeperator(int span, int height) {
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= height;
gd.horizontalSpan= span;
return gd;
}
// ------- ui creation
/**
* Creates or returns the created separator.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Control getSeparator(Composite parent) {
if (fSeparator == null) {
assertCompositeNotNull(parent);
fSeparator= new Label(parent, fStyle);
}
return fSeparator;
}
}

View file

@ -4,18 +4,22 @@ package org.eclipse.cdt.internal.ui.wizards.dialogfields;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.cdt.internal.ui.wizards.swt.MGridData;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
/**
* Dialog field containing a label, text control and a button control.
*/
public class StringButtonDialogField extends StringDialogField {
private Button fBrowseButton;
@ -24,13 +28,34 @@ public class StringButtonDialogField extends StringDialogField {
private boolean fButtonEnabled;
// ------ adapter communication
public StringButtonDialogField(IStringButtonAdapter adapter) {
super();
fStringButtonAdapter= adapter;
fBrowseButtonLabel= "!Browse...!"; //$NON-NLS-1$
fButtonEnabled= true;
}
/**
* Sets the label of the button.
*/
public void setButtonLabel(String label) {
fBrowseButtonLabel= label;
}
// ------ adapter communication
/**
* Programmatical pressing of the button
*/
public void changeControlPressed() {
fStringButtonAdapter.changeControlPressed(this);
}
// ------- layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
@ -38,22 +63,37 @@ public class StringButtonDialogField extends StringDialogField {
label.setLayoutData(gridDataForLabel(1));
Text text= getTextControl(parent);
text.setLayoutData(gridDataForText(nColumns - 2));
Control button= getChangeControl(parent);
button.setLayoutData(gridDataForControl(1));
Button button= getChangeControl(parent);
button.setLayoutData(gridDataForButton(button, 1));
return new Control[] { label, text, button };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
// ------ enable / disable management
public void enableButton(boolean enable) {
if (isOkToUse(fBrowseButton)) {
fBrowseButton.setEnabled(isEnabled() && enable);
}
fButtonEnabled= enable;
}
protected static GridData gridDataForButton(Button button, int span) {
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
return gd;
}
// ------- ui creation
public Control getChangeControl(Composite parent) {
/**
* Creates or returns the created buttom widget.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Button getChangeControl(Composite parent) {
if (fBrowseButton == null) {
assertCompositeNotNull(parent);
@ -72,29 +112,26 @@ public class StringButtonDialogField extends StringDialogField {
}
return fBrowseButton;
}
public int getNumberOfControls() {
return 3;
}
protected static MGridData gridDataForControl(int span) {
MGridData gd= new MGridData();
gd.horizontalAlignment= MGridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
return gd;
}
public StringButtonDialogField(IStringButtonAdapter adapter) {
super();
fStringButtonAdapter= adapter;
fBrowseButtonLabel= "!Browse...!"; //$NON-NLS-1$
fButtonEnabled= true;
}
public void setButtonLabel(String label) {
fBrowseButtonLabel= label;
// ------ enable / disable management
/**
* Sets the enable state of the button.
*/
public void enableButton(boolean enable) {
if (isOkToUse(fBrowseButton)) {
fBrowseButton.setEnabled(isEnabled() && enable);
}
fButtonEnabled= enable;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
if (isOkToUse(fBrowseButton)) {
fBrowseButton.setEnabled(isEnabled() && fButtonEnabled);
}
}
}
}

View file

@ -5,16 +5,16 @@ package org.eclipse.cdt.internal.ui.wizards.dialogfields;
* All Rights Reserved.
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.cdt.internal.ui.wizards.swt.MGridData;
public class StringDialogField extends DialogField {
@ -22,8 +22,16 @@ public class StringDialogField extends DialogField {
private Text fTextControl;
private ModifyListener fModifyListener;
public StringDialogField() {
super();
fText= ""; //$NON-NLS-1$
}
// ------- layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
@ -33,19 +41,43 @@ public class StringDialogField extends DialogField {
text.setLayoutData(gridDataForText(nColumns - 1));
return new Control[] { label, text };
}
}
protected void doModifyText(ModifyEvent e) {
if (isOkToUse(fTextControl)) {
fText= fTextControl.getText();
}
dialogFieldChanged();
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 2;
}
// ------- ui creation
protected static GridData gridDataForText(int span) {
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
return gd;
}
// ------- focus methods
/*
* @see DialogField#setFocus
*/
public boolean setFocus() {
if (isOkToUse(fTextControl)) {
fTextControl.setFocus();
fTextControl.setSelection(0, fTextControl.getText().length());
}
return true;
}
// ------- ui creation
/**
* Creates or returns the created text control.
* @param parent The parent composite or <code>null</code> when the widget has
* already been created.
*/
public Text getTextControl(Composite parent) {
if (fTextControl == null) {
assertCompositeNotNull(parent);
@ -61,38 +93,41 @@ public class StringDialogField extends DialogField {
fTextControl.setFont(parent.getFont());
fTextControl.addModifyListener(fModifyListener);
fTextControl.setEnabled(isEnabled());
}
return fTextControl;
}
private void doModifyText(ModifyEvent e) {
if (isOkToUse(fTextControl)) {
fText= fTextControl.getText();
}
dialogFieldChanged();
}
// ------ enable / disable management
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
if (isOkToUse(fTextControl)) {
fTextControl.setEnabled(isEnabled());
}
}
// ------ text access
/**
* Get the text
* Gets the text. Can not be <code>null</code>
*/
public String getText() {
return fText;
}
protected static MGridData gridDataForText(int span) {
MGridData gd= new MGridData();
gd.horizontalAlignment= MGridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.grabColumn= 0;
gd.horizontalSpan= span;
return gd;
}
// ------- focus methods
public boolean setFocus() {
if (isOkToUse(fTextControl)) {
fTextControl.setFocus();
fTextControl.setSelection(0, fTextControl.getText().length());
}
return true;
}
/**
* Set the text. Triggers an dialog-changed event
* Sets the text. Triggers a dialog-changed event.
*/
public void setText(String text) {
fText= text;
@ -102,8 +137,9 @@ public class StringDialogField extends DialogField {
dialogFieldChanged();
}
}
/**
* Set the text without triggering a dialog-changed event
* Sets the text without triggering a dialog-changed event.
*/
public void setTextWithoutUpdate(String text) {
fText= text;
@ -113,16 +149,5 @@ public class StringDialogField extends DialogField {
fTextControl.addModifyListener(fModifyListener);
}
}
// ------ enable / disable management
protected void updateEnableState() {
super.updateEnableState();
if (isOkToUse(fTextControl)) {
fTextControl.setEnabled(isEnabled());
}
}
public StringDialogField() {
super();
fText= ""; //$NON-NLS-1$
}
}

View file

@ -56,7 +56,7 @@ public class CUIPlugin extends AbstractUIPlugin {
public static final String FILE_WIZARD_ID = "org.eclipse.ui.wizards.new.file";
public static final String FOLDER_WIZARD_ID = "org.eclipse.ui.wizards.new.folder";
public static final String CLASS_WIZARD_ID = "org.eclipse.cdt.ui.wizards.NewClassWizard";
public static final String FOLDER_ACTION_SET_ID = PLUGIN_ID + ".CFolderActionSet";
public static final String BUILDER_ID = PLUGIN_CORE_ID + ".cbuilder";

View file

@ -0,0 +1,68 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.ui;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.ui.codemanipulation.StubUtility;
import org.eclipse.core.runtime.CoreException;
/**
* Class that offers access to the templates contained in the 'code generation' preference page.
*
* @since 2.1
*/
public class CodeGeneration {
private CodeGeneration() {
}
/**
* Returns the content for a new compilation unit using the 'new Java file' code template.
* @param cu The compilation to create the source for. The compilation unit does not need to exist.
* @param typeComment The comment for the type to created. Used when the code template contains a ${typecomment} variable. Can be <code>null</code> if
* no comment should be added.
* @param typeContent The code of the type, including type declaration and body.
* @param lineDelimiter The line delimiter to be used.
* @return Returns the new content or <code>null</code> if the template is undefined or empty.
* @throws CoreException
*/
public static String getHeaderFileContent(ITranslationUnit tu, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
return StubUtility.getHeaderFileContent(tu, typeComment, typeContent, lineDelimiter);
}
/**
* Returns the content for a new compilation unit using the 'new Java file' code template.
* @param cu The compilation to create the source for. The compilation unit does not need to exist.
* @param typeComment The comment for the type to created. Used when the code template contains a ${typecomment} variable. Can be <code>null</code> if
* no comment should be added.
* @param typeContent The code of the type, including type declaration and body.
* @param lineDelimiter The line delimiter to be used.
* @return Returns the new content or <code>null</code> if the template is undefined or empty.
* @throws CoreException
*/
public static String getBodyFileContent(ITranslationUnit tu, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
return StubUtility.getBodyFileContent(tu, typeComment, typeContent, lineDelimiter);
}
/**
* Returns the content for a new type comment using the 'typecomment' code template. The returned content is unformatted and is not indented.
* @param cu The compilation where the type is contained. The compilation unit does not need to exist.
* @param typeQualifiedName The name of the type to which the comment is added. For inner types the name must be qualified and include the outer
* types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)}.
* @param lineDelimiter The line delimiter to be used.
* @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented.
* @throws CoreException
*/
public static String getClassComment(ITranslationUnit tu, String typeQualifiedName, String lineDelimiter) throws CoreException {
return StubUtility.getClassComment(tu, typeQualifiedName, lineDelimiter);
}
}

View file

@ -4,6 +4,8 @@
*/
package org.eclipse.cdt.ui;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* Preference constants used in the JDT-UI preference store. Clients should only read the
* JDT-UI preference store using these values. Clients are not allowed to modify the
@ -16,6 +18,15 @@ public class PreferenceConstants {
private PreferenceConstants() {
}
/**
* A named preference that controls if comment stubs will be added
* automatically to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.cdt.ui.javadoc"; //$NON-NLS-1$
/**
* A named preference that controls whether the cview's selection is linked to the active editor.
@ -41,4 +52,12 @@ public class PreferenceConstants {
*/
public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.cdt.ui.editor.showSegments"; //$NON-NLS-1$
/**
* Returns the JDT-UI preference store.
*
* @return the JDT-UI preference store
*/
public static IPreferenceStore getPreferenceStore() {
return CUIPlugin.getDefault().getPreferenceStore();
}
}

View file

@ -0,0 +1,215 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.ui.actions;
import java.util.Iterator;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
import org.eclipse.cdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.actions.NewProjectAction;
public abstract class AbstractOpenWizardAction extends Action implements IWorkbenchWindowActionDelegate {
private Class[] fActivatedOnTypes;
private boolean fAcceptEmptySelection;
private boolean fNoChecking;
/**
* Creates a AbstractOpenWizardAction.
* @param label The label of the action
* @param acceptEmptySelection Specifies if the action allows an empty selection
*/
public AbstractOpenWizardAction(String label, boolean acceptEmptySelection) {
this(label, null, acceptEmptySelection);
}
/**
* Creates a AbstractOpenWizardAction.
* @param label The label of the action
* @param activatedOnTypes The action is only enabled when all objects in the selection
* are of the given types. <code>null</code> will allow all types.
* @param acceptEmptySelection Specifies if the action allows an empty selection
*/
public AbstractOpenWizardAction(String label, Class[] activatedOnTypes, boolean acceptEmptySelection) {
super(label);
fActivatedOnTypes= activatedOnTypes;
fAcceptEmptySelection= acceptEmptySelection;
fNoChecking= false;
}
/**
* Creates a AbstractOpenWizardAction with no restrictions on types, and does allow
* an empty selection.
*/
protected AbstractOpenWizardAction() {
fActivatedOnTypes= null;
fAcceptEmptySelection= true;
fNoChecking= true;
}
protected IWorkbench getWorkbench() {
return CUIPlugin.getDefault().getWorkbench();
}
private boolean isOfAcceptedType(Object obj) {
if (fActivatedOnTypes != null) {
for (int i= 0; i < fActivatedOnTypes.length; i++) {
if (fActivatedOnTypes[i].isInstance(obj)) {
return true;
}
}
return false;
}
return true;
}
private boolean isEnabled(IStructuredSelection selection) {
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object obj= iter.next();
if (!isOfAcceptedType(obj) || !shouldAcceptElement(obj)) {
return false;
}
}
return true;
}
/**
* Can be overridden to add more checks.
* obj is guaranteed to be instance of one of the accepted types
*/
protected boolean shouldAcceptElement(Object obj) {
return true;
}
/**
* Creates the specific wizard.
* (to be implemented by a subclass)
*/
abstract protected Wizard createWizard() throws CoreException;
protected IStructuredSelection getCurrentSelection() {
IWorkbenchWindow window= CUIPlugin.getDefault().getActiveWorkbenchWindow();
if (window != null) {
ISelection selection= window.getSelectionService().getSelection();
if (selection instanceof IStructuredSelection) {
return (IStructuredSelection) selection;
}
}
return null;
}
/**
* The user has invoked this action.
*/
public void run() {
/* if (!fNoChecking && !canActionBeAdded()) {
return;
}
if (!checkWorkspaceNotEmpty()) {
return;
}
*/ Shell shell= CUIPlugin.getDefault().getActiveWorkbenchShell();
try {
Wizard wizard= createWizard();
if (wizard instanceof IWorkbenchWizard) {
((IWorkbenchWizard)wizard).init(getWorkbench(), getCurrentSelection());
}
WizardDialog dialog= new WizardDialog(shell, wizard);
PixelConverter converter= new PixelConverter(CUIPlugin.getDefault().getActiveWorkbenchShell());
dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
dialog.create();
dialog.open();
} catch (CoreException e) {
String title= NewWizardMessages.getString("AbstractOpenWizardAction.createerror.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("AbstractOpenWizardAction.createerror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
}
}
/**
* Tests if the action can be run on the current selection.
*/
public boolean canActionBeAdded() {
IStructuredSelection selection= getCurrentSelection();
if (selection == null || selection.isEmpty()) {
return fAcceptEmptySelection;
}
return isEnabled(selection);
}
/*
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
run();
}
/*
* @see IWorkbenchWindowActionDelegate#dispose()
*/
public void dispose() {
}
/*
* @see IWorkbenchWindowActionDelegate#init(IWorkbenchWindow)
*/
public void init(IWorkbenchWindow window) {
}
/*
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
// selection taken from selectionprovider
}
protected boolean checkWorkspaceNotEmpty() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
if (workspace.getRoot().getProjects().length == 0) {
Shell shell= CUIPlugin.getDefault().getActiveWorkbenchShell();
String title= NewWizardMessages.getString("AbstractOpenWizardAction.noproject.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("AbstractOpenWizardAction.noproject.message"); //$NON-NLS-1$
if (MessageDialog.openQuestion(shell, title, message)) {
IWorkbenchWindow window= CUIPlugin.getDefault().getActiveWorkbenchWindow();
(new NewProjectAction(window)).run();
return workspace.getRoot().getProjects().length != 0;
}
return false;
}
return true;
}
}

View file

@ -0,0 +1,26 @@
package org.eclipse.cdt.ui.actions;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.ui.wizards.NewClassWizard;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* TODO: Provide description for "OpenClassWizardAction".
* @see IWorkbenchWindowActionDelegate
*/
public class OpenClassWizardAction extends AbstractOpenWizardAction implements IWorkbenchWindowActionDelegate {
public OpenClassWizardAction() {
WorkbenchHelp.setHelp(this, ICHelpContextIds.OPEN_CLASS_WIZARD_ACTION);
}
public OpenClassWizardAction(String label, Class[] acceptedTypes) {
super(label, acceptedTypes, false);
WorkbenchHelp.setHelp(this, ICHelpContextIds.OPEN_CLASS_WIZARD_ACTION);
}
protected Wizard createWizard() {
return new NewClassWizard();
}
}

View file

@ -0,0 +1,124 @@
package org.eclipse.cdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.cdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
/**
* description for "NewClassWizard".
* @see Wizard
*/
public class NewClassWizard extends BasicNewResourceWizard implements INewWizard {
private NewClassWizardPage fPage;
private String wz_title;
private static final String WZ_TITLE = "NewClassWizard.title";
private static final String WZ_DESC = "NewClassWizard.description";
private static final String PAGE_TITLE = "NewClassWizard.page.title";
/**
* "NewClassWizard" constructor.
*/
public NewClassWizard() {
this(CUIPlugin.getResourceString(WZ_TITLE));
}
public NewClassWizard(String title) {
super();
wz_title = title;
setDefaultPageImageDescriptor(CPluginImages.DESC_WIZBAN_NEWCLASS);
setWindowTitle(wz_title); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
fPage.createClass(monitor);
ITranslationUnit headerTU= fPage.getCreatedClassHeaderFile();
ITranslationUnit bodyTU= fPage.getCreatedClassBodyFile();
if (headerTU != null) {
IResource resource= headerTU.getResource();
selectAndReveal(resource);
openResource((IFile) resource);
}
if (bodyTU != null) {
IResource resource= bodyTU.getResource();
selectAndReveal(resource);
openResource((IFile) resource);
}
}
/**
* @see Wizard#performFinish
*/
public boolean performFinish() {
IWorkspaceRunnable op= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
try {
finishPage(monitor);
} catch (InterruptedException e) {
throw new OperationCanceledException(e.getMessage());
}
}
};
try {
getContainer().run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
handleFinishException(getShell(), e);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
public void addPages() {
super.addPages();
fPage= new NewClassWizardPage(getSelection());
addPage(fPage);
fPage.setTitle(CUIPlugin.getResourceString(PAGE_TITLE));
fPage.setDescription(CUIPlugin.getResourceString(WZ_DESC));
fPage.init();
}
protected void handleFinishException(Shell shell, InvocationTargetException e) {
String title= NewWizardMessages.getString("NewElementWizard.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewElementWizard.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
}
protected void openResource(final IFile resource) {
final IWorkbenchPage activePage= CUIPlugin.getActivePage();
if (activePage != null) {
final Display display= getShell().getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
try {
activePage.openEditor(resource);
} catch (PartInitException e) {
CUIPlugin.getDefault().log(e);
}
}
});
}
}
}
}

View file

@ -0,0 +1,869 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.ui.wizards;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IOpenable;
import org.eclipse.cdt.core.model.IParent;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.cdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.LinkToFileGroup;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.cdt.ui.CElementLabelProvider;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.CodeGeneration;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
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.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.ContainerGenerator;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.WorkbenchPlugin;
/**
* Wizard page to create a new class.
* <p>
* Note: This class is not intended to be subclassed. To implement a different kind of
* a new class wizard page, extend <code>NewTypeWizardPage</code>.
* </p>
*
*/
public class NewClassWizardPage extends WizardPage implements Listener {
// the page name
private final static String PAGE_NAME= "NewClassWizardPage";
// the current resource selection
private IStructuredSelection currentSelection;
// cache of C Model current selection
private ICElement eSelection = null;
// cache of newly-created files
private ITranslationUnit parentHeaderTU = null;
private ITranslationUnit parentBodyTU = null;
// Controls
private StringDialogField fClassNameDialogField;
private StringButtonDialogField fBaseClassDialogField;
private SelectionButtonDialogFieldGroup fAccessButtons;
private SelectionButtonDialogFieldGroup fConstDestButtons;
private LinkToFileGroup linkedResourceGroupForHeader;
private LinkToFileGroup linkedResourceGroupForBody;
private final int PUBLIC_INDEX= 0, PROTECTED_INDEX= 1, PRIVATE_INDEX= 2, DEFAULT_INDEX= 3;
private IStatus fCurrStatus;
protected IStatus fClassNameStatus;
protected IStatus fBaseClassStatus;
// -------------------- Initialization ------------------
public NewClassWizardPage(IStructuredSelection selection) {
super(PAGE_NAME);
currentSelection = selection;
eSelection = getSelectionCElement(currentSelection);
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fClassNameDialogField= new StringDialogField();
fClassNameDialogField.setDialogFieldListener(adapter);
fClassNameDialogField.setLabelText(NewWizardMessages.getString("NewClassWizardPage.classname.label"));
fBaseClassDialogField= new StringButtonDialogField(adapter);
fBaseClassDialogField.setDialogFieldListener(adapter);
fBaseClassDialogField.setLabelText(NewWizardMessages.getString("NewClassWizardPage.baseclass.label"));
fBaseClassDialogField.setButtonLabel(NewWizardMessages.getString("NewClassWizardPage.baseclass.button"));
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewClassWizardPage.baseclass.access.public"),
/* 1 == PROTECTED_INDEX */ NewWizardMessages.getString("NewClassWizardPage.baseclass.access.protected"),
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewClassWizardPage.baseclass.access.private"),
/* 3 == DEFAULT_INDEX */ NewWizardMessages.getString("NewClassWizardPage.baseclass.access.access")
};
fAccessButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccessButtons.setDialogFieldListener(adapter);
fAccessButtons.setLabelText(NewWizardMessages.getString("NewClassWizardPage.baseclass.access.label"));
fAccessButtons.setSelection(0, true);
String[] buttonNames2= new String[] {
/* 0 == INLINE_INDEX */ NewWizardMessages.getString("NewClassWizardPage.constdest.inline"),
/* 1 == VIRTUAL_DEST_INDEX */ NewWizardMessages.getString("NewClassWizardPage.constdest.virtualdestructor"),
};
fConstDestButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fConstDestButtons.setDialogFieldListener(adapter);
linkedResourceGroupForHeader = new LinkToFileGroup(adapter, this);
linkedResourceGroupForHeader.setLabelText(NewWizardMessages.getString("NewClassWizardPage.files.header"));
linkedResourceGroupForBody = new LinkToFileGroup(adapter, this);
linkedResourceGroupForBody.setLabelText(NewWizardMessages.getString("NewClassWizardPage.files.body"));
fClassNameStatus= new StatusInfo();
fBaseClassStatus= new StatusInfo();
}
public void init() {
fAccessButtons.setEnabled(false);
setPageComplete(false);
}
// ----------------- Creating Controls --------------------
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
int nColumns= 5;
initializeDialogUnits(parent);
// top level group
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout(nColumns, false));
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setFont(parent.getFont());
//WorkbenchHelp.setHelp(composite, IHelpContextIds.NEW_FILE_WIZARD_PAGE);
createClassNameControls(composite, nColumns);
createBaseClassControls(composite, nColumns);
createModifierControls(composite, nColumns);
createSeparator(composite, nColumns);
createFilesControls(composite, nColumns);
composite.layout();
setErrorMessage(null);
setMessage(null);
setControl(composite);
}
protected void createClassNameControls(Composite composite, int nColumns) {
fClassNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fClassNameDialogField.getTextControl(null), getMaxFieldWidth());
}
protected void createBaseClassControls(Composite composite, int nColumns) {
fBaseClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fBaseClassDialogField.getTextControl(null), getMaxFieldWidth());
createAccessControls(composite, nColumns);
}
protected void createAccessControls(Composite composite, int nColumns){
LayoutUtil.setHorizontalSpan(fAccessButtons.getLabelControl(composite), 1);
Control control= fAccessButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fConstDestButtons.getLabelControl(composite), 1);
Control control= fConstDestButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 1;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
protected void createFilesControls(Composite composite, int nColumns){
linkedResourceGroupForHeader.doFillIntoGrid(composite, nColumns);
linkedResourceGroupForBody.doFillIntoGrid(composite, nColumns);
}
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Returns the recommended maximum width for text fields (in pixels). This
* method requires that createContent has been called before this method is
* call. Subclasses may override to change the maximum width for text
* fields.
*
* @return the recommended maximum width for text fields.
*/
protected int getMaxFieldWidth() {
return convertWidthInCharsToPixels(40);
}
// --------------------- listeners --------------------------
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
}
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
classPageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
classPageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
classPageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void classPageChangeControlPressed(DialogField field) {
if (field == fBaseClassDialogField) {
ICElement element= chooseBaseClass();
if (element != null) {
fBaseClassDialogField.setText(element.getElementName());
}
}
}
private void classPageCustomButtonPressed(DialogField field, int index) {
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void classPageDialogFieldChanged(DialogField field) {
if(field == fClassNameDialogField){
String text = fClassNameDialogField.getText();
if(!linkedResourceGroupForHeader.linkCreated()){
if (text.length() > 0) {
linkedResourceGroupForHeader.setText(text + ".h");
} else {
linkedResourceGroupForHeader.setText(text);
}
}
if(!linkedResourceGroupForBody.linkCreated()){
if (text.length() > 0) {
linkedResourceGroupForBody.setText(text + ".cpp");
} else{
linkedResourceGroupForBody.setText(text);
}
}
fClassNameStatus = classNameChanged();
}
if(field == fBaseClassDialogField){
if(fBaseClassDialogField.getText().length() > 0)
{
fAccessButtons.setEnabled(true);
fBaseClassStatus = baseClassChanged();
}
else{
fAccessButtons.setEnabled(false);
}
}
doStatusUpdate();
}
// --------------- Helper methods for creating controls -----
private static ICElement getSelectionCElement(IStructuredSelection sel) {
if (!sel.isEmpty() && sel instanceof IStructuredSelection) {
List list= ((IStructuredSelection)sel).toList();
if (list.size() == 1) {
Object element= list.get(0);
if ( (element instanceof ICElement)
//&& ((ICElement)element).getElementType() == ICElement.C_CCONTAINER)
)
{
return (ICElement)element;
}
}
}
return null;
}
private void getChildrenOfTypeClass(IParent parent, ArrayList elementsFound, IProgressMonitor monitor, int worked){
ICElement[] elements = parent.getChildren();
monitor.worked( worked );
for (int i = 0; i< elements.length; i++){
ICElement element = (ICElement)elements[i];
if(element.getElementType() == ICElement.C_CLASS){
elementsFound.add(element);
}
if(element instanceof IParent){
getChildrenOfTypeClass((IParent)element, elementsFound, monitor, worked+1);
}
}
}
private ArrayList findClassElementsInProject(){
final ArrayList elementsOfTypeClassInProject = new ArrayList();
IRunnableWithProgress runnable= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask("", 5); //$NON-NLS-1$
try{
if(eSelection != null){
ICProject cProject = eSelection.getCProject();
getChildrenOfTypeClass((IParent)cProject, elementsOfTypeClassInProject, monitor, 1);
}
monitor.worked(5);
} finally{
monitor.done();
}
}
};
try {
getWizard().getContainer().run(false, true, runnable);
} catch (InvocationTargetException e) {
} catch (InterruptedException e) {
}
finally {
}
return elementsOfTypeClassInProject;
}
protected ICElement chooseBaseClass(){
// find the available classes in this project
ArrayList elementsFound = findClassElementsInProject();
ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new CElementLabelProvider());
dialog.setTitle(NewWizardMessages.getString("BaseClassSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("BaseClassSelectionDialog.message")); //$NON-NLS-1$
dialog.setElements(elementsFound.toArray());
dialog.setFilter("*");
if (dialog.open() == ElementListSelectionDialog.OK) {
ICElement element= (ICElement) dialog.getFirstResult();
return element;
}
return null;
}
// ------------- getter methods for dialog controls -------------
public String getHeaderFileName(){
return linkedResourceGroupForHeader.getText();
}
public String getBodyFileName(){
return linkedResourceGroupForBody.getText();
}
public String getNewClassName(){
return fClassNameDialogField.getText();
}
public String getBaseClassName(){
return fBaseClassDialogField.getText();
}
public boolean isVirtualDestructor(){
return fConstDestButtons.isSelected(1);
}
public boolean isInline(){
return fConstDestButtons.isSelected(0);
}
public String getAccess(){
if(fAccessButtons.isSelected(0))
return "public";
else if(fAccessButtons.isSelected(1))
return "protected";
else if(fAccessButtons.isSelected(2))
return "private";
else return "";
}
public ITranslationUnit getCreatedClassHeaderFile(){
return parentHeaderTU;
}
public ITranslationUnit getCreatedClassBodyFile(){
return parentBodyTU;
}
// -------------- Create a new Class ----------------------
public void createClass(IProgressMonitor monitor){
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
try{
String lineDelimiter= null;
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
parentHeaderTU = createTranslationUnit(linkedResourceGroupForHeader, getHeaderFileName());
parentBodyTU = createTranslationUnit(linkedResourceGroupForBody, getBodyFileName());
monitor.worked(1);
if(parentHeaderTU != null){
String header = constructHeaderFileContent(lineDelimiter);
IWorkingCopy headerWC = parentHeaderTU.getSharedWorkingCopy(null, CUIPlugin.getDefault().getDocumentProvider().getBufferFactory());
headerWC.getBuffer().append(header);
synchronized(headerWC) {
headerWC.reconcile();
headerWC.commit(true, monitor);
}
}
if(parentBodyTU != null){
String body = constructBodyFileContent(lineDelimiter);
IWorkingCopy bodyWC = parentBodyTU.getSharedWorkingCopy(null, CUIPlugin.getDefault().getDocumentProvider().getBufferFactory());
bodyWC.getBuffer().append(body);
synchronized(bodyWC){
bodyWC.reconcile();
bodyWC.commit(true, monitor);
}
}
}catch(CModelException e){
MessageDialog.openError(getContainer().getShell(), WorkbenchMessages.getString("WizardNewFileCreationPage.internalErrorTitle"), WorkbenchMessages.format("WizardNewFileCreationPage.internalErrorMessage", new Object[] {e.getMessage()})); //$NON-NLS-2$ //$NON-NLS-1$
}finally{
monitor.done();
}
}
protected ITranslationUnit createTranslationUnit(LinkToFileGroup linkedGroup, String fileName){
ITranslationUnit createdUnit = null;
IFile createdFile = null;
createdFile= createNewFile(linkedGroup);
// turn the file into a translation unit
if(createdFile != null){
Object element= CoreModel.getDefault().create(createdFile);
if (element instanceof ITranslationUnit)
createdUnit = (ITranslationUnit) element;
}
return createdUnit;
}
protected IFile createNewFile(LinkToFileGroup linkedGroup) {
final IPath newFilePath = getContainerFullPath(linkedGroup);
final IFile newFileHandle = createFileHandle(newFilePath);
if(newFileHandle.exists()){
return newFileHandle;
}
// create the new file and cache it if successful
final boolean linkedFile = linkedGroup.linkCreated();
final IPath containerPath = getContainerPath(linkedGroup);
final InputStream initialContents = getInitialContents();
WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(IProgressMonitor monitor) throws CoreException,
InterruptedException
{
try {
monitor.beginTask(WorkbenchMessages.getString("WizardNewFileCreationPage.progress"), 2000); //$NON-NLS-1$
if(!(containerExists(containerPath))){
ContainerGenerator generator = new ContainerGenerator(containerPath);
generator.generateContainer(new SubProgressMonitor(monitor, 1000));
}
createFile(newFileHandle,initialContents, newFilePath, linkedFile, new SubProgressMonitor(monitor, 1000));
} finally {
monitor.done();
}
}
};
try {
getContainer().run(false, true, op);
} catch (InterruptedException e) {
return null;
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof CoreException) {
ErrorDialog.openError(
getContainer().getShell(), // Was Utilities.getFocusShell()
WorkbenchMessages.getString("WizardNewFileCreationPage.errorTitle"), //$NON-NLS-1$
null, // no special message
((CoreException) e.getTargetException()).getStatus());
}
else {
// CoreExceptions are handled above, but unexpected runtime exceptions and errors may still occur.
WorkbenchPlugin.log(MessageFormat.format("Exception in {0}.getNewFile(): {1}", new Object[] {getClass().getName(), e.getTargetException()}));//$NON-NLS-1$
MessageDialog.openError(getContainer().getShell(), WorkbenchMessages.getString("WizardNewFileCreationPage.internalErrorTitle"), WorkbenchMessages.format("WizardNewFileCreationPage.internalErrorMessage", new Object[] {e.getTargetException().getMessage()})); //$NON-NLS-2$ //$NON-NLS-1$
}
return null;
}
return newFileHandle;
}
protected IFile createFileHandle(IPath filePath) {
IFile newFile = null;
IWorkspaceRoot root= CUIPlugin.getWorkspace().getRoot();
newFile = root.getFileForLocation(filePath);
if(newFile == null)
newFile = root.getFile(filePath);
return newFile;
}
protected void createFile(IFile fileHandle, InputStream contents, IPath targetPath, boolean linkedFile, IProgressMonitor monitor) throws CoreException {
if (contents == null)
contents = new ByteArrayInputStream(new byte[0]);
try {
fileHandle.create(contents, false, monitor);
}
catch (CoreException e) {
// If the file already existed locally, just refresh to get contents
int code = e.getStatus().getCode();
if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
fileHandle.refreshLocal(IResource.DEPTH_ZERO, null);
else
throw e;
}
if (monitor.isCanceled())
throw new OperationCanceledException();
}
// -------------Helper methods for creating the class -------
protected IPath getSelectionPath(){
// if it is a file, return the parent path
if(eSelection instanceof ITranslationUnit)
return (eSelection.getParent().getPath());
// if it is a root, project, or folder, return its path
if(eSelection instanceof IOpenable){
return (eSelection.getPath());
}else {
// if it is an element in a file, return its openable parent's path
ICElement current = eSelection.getParent();
while (current != null){
if ((current instanceof IOpenable) && !(current instanceof ITranslationUnit)){
return current.getPath();
}
current = current.getParent();
}
return null;
}
}
/*
* returns the path without the file name
*/
protected IPath getContainerPath(LinkToFileGroup linkedGroup) {
if(linkedGroup.linkCreated()){
String pathName = linkedGroup.getResolvedPath();
if((pathName == null) || (pathName.length() <1))
return null;
IPath containerPath = new Path (pathName);
return containerPath.removeLastSegments(1).removeTrailingSeparator().makeAbsolute();
}else {
return (getSelectionPath());
}
}
/*
* returns the path including the file name
*/
protected IPath getContainerFullPath(LinkToFileGroup linkedGroup) {
if(linkedGroup.linkCreated()){
String pathName = linkedGroup.getResolvedPath();
if (pathName == null || pathName.length() < 1)
return null;
else
//The user may not have made this absolute so do it for them
return (new Path(pathName)).makeAbsolute();
} else {
String pathName = linkedGroup.getText();
IPath containerPath = getSelectionPath();
containerPath.addTrailingSeparator();
return ((containerPath.append(pathName)).makeAbsolute());
}
}
protected boolean containerExists(IPath containerPath) {
IContainer container = null;
IWorkspaceRoot root= CUIPlugin.getWorkspace().getRoot();
container = root.getContainerForLocation(containerPath);
if(container == null)
return false;
return true;
}
protected InputStream getInitialContents() {
return null;
}
protected String getClassComment(ITranslationUnit parentTU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
try {
StringBuffer className= new StringBuffer();
className.append(getNewClassName());
String comment= CodeGeneration.getClassComment(parentTU, className.toString(), String.valueOf('\n'));
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
}
return null;
}
// ------------ Constructing File Contents -----------------
protected String constructHeaderFileContent(String lineDelimiter){
StringBuffer text = new StringBuffer();
boolean extendingBase = false;
String baseClassName = getBaseClassName();
if((baseClassName != null) && (baseClassName.length() > 0))
{
extendingBase = true;
}
if(extendingBase){
text.append("#include \"");
text.append(baseClassName);
text.append('\"');
text.append(lineDelimiter);
text.append(lineDelimiter);
}
text.append("class ");
text.append(getNewClassName());
if(extendingBase){
text.append(" : ");
text.append(getAccess());
text.append(" ");
text.append(baseClassName);
}
text.append("{");
text.append(lineDelimiter);
text.append("public:");
text.append(lineDelimiter);
text.append(lineDelimiter);
// constructor
text.append('\t');
text.append(getNewClassName());
text.append("()");
if(isInline()){
text.append(" {};");
text.append(lineDelimiter);
}else {
text.append(";");
text.append(lineDelimiter);
}
// destructor
text.append('\t');
if(isVirtualDestructor()){
text.append("virtual ");
}
text.append("~");
text.append(getNewClassName());
text.append("()");
if(isInline()){
text.append(" {};");
text.append(lineDelimiter);
}else {
text.append(";");
text.append(lineDelimiter);
}
text.append("};");
text.append(lineDelimiter);
return text.toString();
}
protected String constructBodyFileContent(String lineDelimiter){
StringBuffer text = new StringBuffer();
text.append("#include \"");
text.append(getNewClassName());
text.append("\"");
text.append(lineDelimiter);
text.append(lineDelimiter);
if(isInline())
return text.toString();
// constructor
text.append(getNewClassName());
text.append("::");
text.append(getNewClassName());
text.append("()");
text.append(lineDelimiter);
text.append("{};");
text.append(lineDelimiter);
// destructor
text.append(getNewClassName());
text.append("::~");
text.append(getNewClassName());
text.append("()");
text.append(lineDelimiter);
text.append("{};");
text.append(lineDelimiter);
return text.toString();
}
// ------ validation --------
protected void doStatusUpdate() {
// status of all used components
IStatus[] status= new IStatus[] {
fClassNameStatus,
fBaseClassStatus,
};
// the mode severe status will be displayed and the ok button enabled/disabled.
updateStatus(status);
}
protected void updateStatus(IStatus[] status) {
updateStatus(StatusUtil.getMostSevere(status));
}
protected void updateStatus(IStatus status) {
fCurrStatus= status;
setPageComplete(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
protected boolean isValidComment(String template) {
return true;
}
// status validation
/**
* Hook method that gets called when the class name has changed. The method validates the
* class name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus classNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getNewClassName();
// class name must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewClassWizardPage.error.EnterClassName")); //$NON-NLS-1$
return status;
}
// class name must not be qualified
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewClassWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
// class name must follow the C/CPP convensions
// class must NOT exist
// ArrayList elementsFound = findClassElementsInProject();
// if(foundInList(getNewClassName(), elementsFound)){
// status.setWarning(NewWizardMessages.getString("NewClassWizardPage.error.ClassNameExists")); //$NON-NLS-1$
// }
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus baseClassChanged() {
StatusInfo status= new StatusInfo();
// class name must follow the C/CPP convensions
// if class does not exist, give warning
// ArrayList elementsFound = findClassElementsInProject();
// if(!foundInList(getBaseClassName(), elementsFound)){
// status.setWarning(NewWizardMessages.getString("NewClassWizardPage.warning.BaseClassNotExists")); //$NON-NLS-1$
// }
return status;
}
private boolean foundInList(String name, ArrayList elements){
return false;
}
}

View file

@ -102,6 +102,31 @@ public class ControlFactory {
separator.setLayoutData(data);
return separator;
}
/**
* Creates a spacer control.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent) {
return createEmptySpace(parent, 1);
}
/**
* Creates a spacer control with the given span.
* The composite is assumed to have <code>MGridLayout</code> as
* layout.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent, int span) {
Label label= new Label(parent, SWT.LEFT);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
gd.horizontalIndent= 0;
gd.widthHint= 0;
gd.heightHint= 0;
label.setLayoutData(gd);
return label;
}
/**
* Creates an new label (basic method)