1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.ui.wizards;
13 import java.util.ArrayList;
14 import java.util.List;
16 import net.sourceforge.phpdt.core.Flags;
17 import net.sourceforge.phpdt.core.IBuffer;
18 import net.sourceforge.phpdt.core.ICompilationUnit;
19 import net.sourceforge.phpdt.core.IJavaElement;
20 import net.sourceforge.phpdt.core.IPackageFragment;
21 import net.sourceforge.phpdt.core.ISourceRange;
22 import net.sourceforge.phpdt.core.IType;
23 import net.sourceforge.phpdt.core.ToolFactory;
24 import net.sourceforge.phpdt.core.compiler.IScanner;
25 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
26 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
28 //import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo;
29 import net.sourceforge.phpeclipse.ui.StatusInfo;
30 import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility;
31 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
32 import net.sourceforge.phpdt.internal.corext.template.php.Templates;
33 import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil;
34 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
35 import net.sourceforge.phpdt.internal.ui.util.SWTUtil;
36 import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages;
37 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField;
38 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
39 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IListAdapter;
40 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
41 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil;
42 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField;
43 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
44 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
45 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.Separator;
46 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
47 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
48 import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringDialogField;
49 import net.sourceforge.phpdt.ui.CodeGeneration;
50 import net.sourceforge.phpdt.ui.PreferenceConstants;
51 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
53 import org.eclipse.core.runtime.CoreException;
54 import org.eclipse.core.runtime.IProgressMonitor;
55 import org.eclipse.core.runtime.IStatus;
56 import org.eclipse.core.runtime.NullProgressMonitor;
57 import org.eclipse.core.runtime.SubProgressMonitor;
58 import org.eclipse.jface.preference.IPreferenceStore;
59 import org.eclipse.jface.text.BadLocationException;
60 import org.eclipse.jface.text.templates.Template;
61 import org.eclipse.jface.text.templates.TemplateException;
62 import org.eclipse.jface.viewers.LabelProvider;
63 import org.eclipse.swt.SWT;
64 import org.eclipse.swt.graphics.Image;
65 import org.eclipse.swt.layout.GridData;
66 import org.eclipse.swt.layout.GridLayout;
67 import org.eclipse.swt.widgets.Button;
68 import org.eclipse.swt.widgets.Composite;
69 import org.eclipse.swt.widgets.Control;
72 * The class <code>NewTypeWizardPage</code> contains controls and validation
73 * routines for a 'New Type WizardPage'. Implementors decide which components to
74 * add and to enable. Implementors can also customize the validation code.
75 * <code>NewTypeWizardPage</code> is intended to serve as base class of all
76 * wizards that create types like applets, servlets, classes, interfaces, etc.
78 * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code>
79 * for an example usage of <code>NewTypeWizardPage</code>.
82 * @see net.sourceforge.phpdt.ui.wizards.NewClassWizardPage
83 * @see net.sourceforge.phpdt.ui.wizards.NewInterfaceWizardPage
87 public abstract class NewTypeWizardPage extends NewContainerWizardPage {
90 * Class used in stub creation routines to add needed imports to a
93 // public static class ImportsManager {
95 // private IImportsStructure fImportsStructure;
97 // /* package */ ImportsManager(IImportsStructure structure) {
98 // fImportsStructure= structure;
101 // /* package */ IImportsStructure getImportsStructure() {
102 // return fImportsStructure;
106 // * Adds a new import declaration that is sorted in the existing imports.
107 // * If an import already exists or the import would conflict with another
109 // * of an other type with the same simple name the import is not added.
111 // * @param qualifiedTypeName The fully qualified name of the type to import
113 // * @return Returns the simple type name that can be used in the code or
115 // * fully qualified type name if an import conflict prevented the import
117 // public String addImport(String qualifiedTypeName) {
118 // return fImportsStructure.addImport(qualifiedTypeName);
122 * Public access flag. See The Java Virtual Machine Specification for more
125 public int F_PUBLIC = Flags.AccPublic;
128 * Private access flag. See The Java Virtual Machine Specification for more
131 public int F_PRIVATE = Flags.AccPrivate;
134 * Protected access flag. See The Java Virtual Machine Specification for
137 public int F_PROTECTED = Flags.AccProtected;
140 * Static access flag. See The Java Virtual Machine Specification for more
143 public int F_STATIC = Flags.AccStatic;
146 * Final access flag. See The Java Virtual Machine Specification for more
149 public int F_FINAL = Flags.AccFinal;
152 * Abstract property flag. See The Java Virtual Machine Specification for
155 // public int F_ABSTRACT = Flags.AccAbstract;
156 private final static String PAGE_NAME = "NewTypeWizardPage"; //$NON-NLS-1$
158 /** Field ID of the package input field */
159 protected final static String PACKAGE = PAGE_NAME + ".package"; //$NON-NLS-1$
161 /** Field ID of the eclosing type input field */
162 protected final static String ENCLOSING = PAGE_NAME + ".enclosing"; //$NON-NLS-1$
164 /** Field ID of the enclosing type checkbox */
165 protected final static String ENCLOSINGSELECTION = ENCLOSING + ".selection"; //$NON-NLS-1$
167 /** Field ID of the type name input field */
168 protected final static String TYPENAME = PAGE_NAME + ".typename"; //$NON-NLS-1$
170 /** Field ID of the super type input field */
171 protected final static String SUPER = PAGE_NAME + ".superclass"; //$NON-NLS-1$
173 /** Field ID of the super interfaces input field */
174 protected final static String INTERFACES = PAGE_NAME + ".interfaces"; //$NON-NLS-1$
176 /** Field ID of the modifier checkboxes */
177 protected final static String MODIFIERS = PAGE_NAME + ".modifiers"; //$NON-NLS-1$
179 /** Field ID of the method stubs checkboxes */
180 protected final static String METHODS = PAGE_NAME + ".methods"; //$NON-NLS-1$
182 private class InterfacesListLabelProvider extends LabelProvider {
184 private Image fInterfaceImage;
186 public InterfacesListLabelProvider() {
188 fInterfaceImage = PHPUiImages.get(PHPUiImages.IMG_OBJS_INTERFACE);
191 public Image getImage(Object element) {
192 return fInterfaceImage;
196 private StringButtonStatusDialogField fPackageDialogField;
198 private SelectionButtonDialogField fEnclosingTypeSelection;
200 private StringButtonDialogField fEnclosingTypeDialogField;
202 private boolean fCanModifyPackage;
204 private boolean fCanModifyEnclosingType;
206 private IPackageFragment fCurrPackage;
208 // private IType fCurrEnclosingType;
209 private StringDialogField fTypeNameDialogField;
211 private StringButtonDialogField fSuperClassDialogField;
213 private ListDialogField fSuperInterfacesDialogField;
215 // private IType fSuperClass;
217 private SelectionButtonDialogFieldGroup fAccMdfButtons;
219 private SelectionButtonDialogFieldGroup fOtherMdfButtons;
221 private IType fCreatedType;
223 protected IStatus fEnclosingTypeStatus;
225 protected IStatus fPackageStatus;
227 protected IStatus fTypeNameStatus;
229 // protected IStatus fSuperClassStatus;
230 protected IStatus fModifierStatus;
232 // protected IStatus fSuperInterfacesStatus;
234 private boolean fIsClass;
236 private int fStaticMdfIndex;
238 private final int PUBLIC_INDEX = 0, DEFAULT_INDEX = 1, PRIVATE_INDEX = 2,
241 private final int ABSTRACT_INDEX = 0, FINAL_INDEX = 1;
244 * Creates a new <code>NewTypeWizardPage</code>
247 * <code>true</code> if a new class is to be created; otherwise
248 * an interface is to be created
250 * the wizard page's name
252 public NewTypeWizardPage(boolean isClass, String pageName) {
258 TypeFieldsAdapter adapter = new TypeFieldsAdapter();
260 fPackageDialogField = new StringButtonStatusDialogField(adapter);
261 fPackageDialogField.setDialogFieldListener(adapter);
262 fPackageDialogField.setLabelText(NewWizardMessages
263 .getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
264 fPackageDialogField.setButtonLabel(NewWizardMessages
265 .getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
266 fPackageDialogField.setStatusWidthHint(NewWizardMessages
267 .getString("NewTypeWizardPage.default")); //$NON-NLS-1$
269 fEnclosingTypeSelection = new SelectionButtonDialogField(SWT.CHECK);
270 fEnclosingTypeSelection.setDialogFieldListener(adapter);
271 fEnclosingTypeSelection.setLabelText(NewWizardMessages
272 .getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
274 fEnclosingTypeDialogField = new StringButtonDialogField(adapter);
275 fEnclosingTypeDialogField.setDialogFieldListener(adapter);
276 fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages
277 .getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
279 fTypeNameDialogField = new StringDialogField();
280 fTypeNameDialogField.setDialogFieldListener(adapter);
281 fTypeNameDialogField.setLabelText(NewWizardMessages
282 .getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
284 fSuperClassDialogField = new StringButtonDialogField(adapter);
285 fSuperClassDialogField.setDialogFieldListener(adapter);
286 fSuperClassDialogField.setLabelText(NewWizardMessages
287 .getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
288 fSuperClassDialogField.setButtonLabel(NewWizardMessages
289 .getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
291 String[] addButtons = new String[] {
293 NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
298 .getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
300 fSuperInterfacesDialogField = new ListDialogField(adapter, addButtons,
301 new InterfacesListLabelProvider());
302 fSuperInterfacesDialogField.setDialogFieldListener(adapter);
303 String interfaceLabel = fIsClass ? NewWizardMessages
304 .getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
305 fSuperInterfacesDialogField.setLabelText(interfaceLabel);
306 fSuperInterfacesDialogField.setRemoveButtonIndex(2);
308 String[] buttonNames1 = new String[] {
309 /* 0 == PUBLIC_INDEX */
311 .getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
312 /* 1 == DEFAULT_INDEX */
314 .getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
315 /* 2 == PRIVATE_INDEX */
317 .getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
318 /* 3 == PROTECTED_INDEX */
320 .getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
322 fAccMdfButtons = new SelectionButtonDialogFieldGroup(SWT.RADIO,
324 fAccMdfButtons.setDialogFieldListener(adapter);
325 fAccMdfButtons.setLabelText(NewWizardMessages
326 .getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
327 fAccMdfButtons.setSelection(0, true);
329 String[] buttonNames2;
331 buttonNames2 = new String[] {
332 /* 0 == ABSTRACT_INDEX */
334 .getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
335 /* 1 == FINAL_INDEX */
337 .getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
340 .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
342 fStaticMdfIndex = 2; // index of the static checkbox is 2
344 buttonNames2 = new String[] { NewWizardMessages
345 .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
347 fStaticMdfIndex = 0; // index of the static checkbox is 0
350 fOtherMdfButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK,
352 fOtherMdfButtons.setDialogFieldListener(adapter);
354 fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
355 fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
356 fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
358 fPackageStatus = new StatusInfo();
359 fEnclosingTypeStatus = new StatusInfo();
361 fCanModifyPackage = true;
362 fCanModifyEnclosingType = true;
365 fTypeNameStatus = new StatusInfo();
366 // fSuperClassStatus= new StatusInfo();
367 // fSuperInterfacesStatus= new StatusInfo();
368 fModifierStatus = new StatusInfo();
372 * Initializes all fields provided by the page with a given selection.
375 * the selection used to intialize this page or <code>
377 * if no selection was available
379 protected void initTypePage(IJavaElement elem) {
380 String initSuperclass = "java.lang.Object"; //$NON-NLS-1$
381 ArrayList initSuperinterfaces = new ArrayList(5);
383 IPackageFragment pack = null;
384 IType enclosingType = null;
387 // evaluate the enclosing type
388 pack = (IPackageFragment) elem
389 .getAncestor(IJavaElement.PACKAGE_FRAGMENT);
390 IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE);
391 if (typeInCU != null) {
392 if (typeInCU.getCompilationUnit() != null) {
393 enclosingType = typeInCU;
396 ICompilationUnit cu = (ICompilationUnit) elem
397 .getAncestor(IJavaElement.COMPILATION_UNIT);
399 // enclosingType= cu.findPrimaryType();
405 // if (elem.getElementType() == IJavaElement.TYPE) {
406 // type= (IType)elem;
407 // if (type.exists()) {
408 // String superName= JavaModelUtil.getFullyQualifiedName(type);
409 // if (type.isInterface()) {
410 // initSuperinterfaces.add(superName);
412 // initSuperclass= superName;
416 // } catch (JavaModelException e) {
417 // PHPeclipsePlugin.log(e);
418 // // ignore this exception now
422 setPackageFragment(pack, true);
423 // setEnclosingType(enclosingType, true);
424 setEnclosingTypeSelection(false, true);
426 setTypeName("", true); //$NON-NLS-1$
427 setSuperClass(initSuperclass, true);
428 setSuperInterfaces(initSuperinterfaces, true);
431 // -------- UI Creation ---------
434 * Creates a separator line. Expects a <code>GridLayout</code> with at
438 * the parent composite
440 * number of columns to span
442 protected void createSeparator(Composite composite, int nColumns) {
443 (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(
444 composite, nColumns, convertHeightInCharsToPixels(1));
448 * Creates the controls for the package name field. Expects a
449 * <code>GridLayout</code> with at least 4 columns.
452 * the parent composite
454 * number of columns to span
456 protected void createPackageControls(Composite composite, int nColumns) {
457 fPackageDialogField.doFillIntoGrid(composite, nColumns);
458 LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null),
460 LayoutUtil.setHorizontalGrabbing(fPackageDialogField
461 .getTextControl(null));
465 * Creates the controls for the enclosing type name field. Expects a
466 * <code>GridLayout</code> with at least 4 columns.
469 * the parent composite
471 * number of columns to span
473 protected void createEnclosingTypeControls(Composite composite, int nColumns) {
475 Composite tabGroup = new Composite(composite, SWT.NONE);
476 GridLayout layout = new GridLayout();
477 layout.marginWidth = 0;
478 layout.marginHeight = 0;
479 tabGroup.setLayout(layout);
481 fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
483 Control c = fEnclosingTypeDialogField.getTextControl(composite);
484 GridData gd = new GridData(GridData.FILL_HORIZONTAL);
485 gd.widthHint = getMaxFieldWidth();
486 gd.horizontalSpan = 2;
489 Button button = fEnclosingTypeDialogField.getChangeControl(composite);
490 gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
491 gd.heightHint = SWTUtil.getButtonHeightHint(button);
492 gd.widthHint = SWTUtil.getButtonWidthHint(button);
493 button.setLayoutData(gd);
497 * Creates the controls for the type name field. Expects a
498 * <code>GridLayout</code> with at least 2 columns.
501 * the parent composite
503 * number of columns to span
505 protected void createTypeNameControls(Composite composite, int nColumns) {
506 fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
507 DialogField.createEmptySpace(composite);
509 LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null),
514 * Creates the controls for the modifiers radio/ceckbox buttons. Expects a
515 * <code>GridLayout</code> with at least 3 columns.
518 * the parent composite
520 * number of columns to span
522 protected void createModifierControls(Composite composite, int nColumns) {
523 LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite),
526 Control control = fAccMdfButtons.getSelectionButtonsGroup(composite);
527 GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
528 gd.horizontalSpan = nColumns - 2;
529 control.setLayoutData(gd);
531 DialogField.createEmptySpace(composite);
533 DialogField.createEmptySpace(composite);
535 control = fOtherMdfButtons.getSelectionButtonsGroup(composite);
536 gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
537 gd.horizontalSpan = nColumns - 2;
538 control.setLayoutData(gd);
540 DialogField.createEmptySpace(composite);
544 * Creates the controls for the superclass name field. Expects a
545 * <code>GridLayout</code> with at least 3 columns.
548 * the parent composite
550 * number of columns to span
552 protected void createSuperClassControls(Composite composite, int nColumns) {
553 fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
554 LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null),
559 * Creates the controls for the superclass name field. Expects a
560 * <code>GridLayout</code> with at least 3 columns.
563 * the parent composite
565 * number of columns to span
567 protected void createSuperInterfacesControls(Composite composite,
569 fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
570 GridData gd = (GridData) fSuperInterfacesDialogField.getListControl(
571 null).getLayoutData();
573 gd.heightHint = convertHeightInCharsToPixels(3);
575 gd.heightHint = convertHeightInCharsToPixels(6);
577 gd.grabExcessVerticalSpace = false;
578 gd.widthHint = getMaxFieldWidth();
582 * Sets the focus on the type name input field.
584 protected void setFocus() {
585 fTypeNameDialogField.setFocus();
588 // -------- TypeFieldsAdapter --------
590 private class TypeFieldsAdapter implements IStringButtonAdapter,
591 IDialogFieldListener, IListAdapter {
593 // -------- IStringButtonAdapter
594 public void changeControlPressed(DialogField field) {
595 // typePageChangeControlPressed(field);
598 // -------- IListAdapter
599 public void customButtonPressed(ListDialogField field, int index) {
600 // typePageCustomButtonPressed(field, index);
603 public void selectionChanged(ListDialogField field) {
606 // -------- IDialogFieldListener
607 public void dialogFieldChanged(DialogField field) {
608 typePageDialogFieldChanged(field);
611 public void doubleClicked(ListDialogField field) {
615 // private void typePageChangeControlPressed(DialogField field) {
616 // if (field == fPackageDialogField) {
617 // IPackageFragment pack= choosePackage();
618 // if (pack != null) {
619 // fPackageDialogField.setText(pack.getElementName());
621 // } else if (field == fEnclosingTypeDialogField) {
622 // IType type= chooseEnclosingType();
623 // if (type != null) {
624 // fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
626 // } else if (field == fSuperClassDialogField) {
627 // IType type= chooseSuperType();
628 // if (type != null) {
629 // fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
634 // private void typePageCustomButtonPressed(DialogField field, int index) {
635 // if (field == fSuperInterfacesDialogField) {
636 // chooseSuperInterfaces();
641 * A field on the type has changed. The fields' status and all dependend
642 * status are updated.
644 private void typePageDialogFieldChanged(DialogField field) {
645 String fieldName = null;
646 if (field == fPackageDialogField) {
647 fPackageStatus = packageChanged();
648 updatePackageStatusLabel();
649 fTypeNameStatus = typeNameChanged();
650 // fSuperClassStatus= superClassChanged();
652 } else if (field == fEnclosingTypeDialogField) {
653 // fEnclosingTypeStatus= enclosingTypeChanged();
654 fTypeNameStatus = typeNameChanged();
655 // fSuperClassStatus= superClassChanged();
656 fieldName = ENCLOSING;
657 } else if (field == fEnclosingTypeSelection) {
659 boolean isEnclosedType = isEnclosingTypeSelected();
660 if (!isEnclosedType) {
661 if (fAccMdfButtons.isSelected(PRIVATE_INDEX)
662 || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
663 fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
664 fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
665 fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
667 if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
668 fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
671 fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType
673 fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX,
674 isEnclosedType && fIsClass);
675 fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex,
677 fTypeNameStatus = typeNameChanged();
678 // fSuperClassStatus= superClassChanged();
679 fieldName = ENCLOSINGSELECTION;
680 } else if (field == fTypeNameDialogField) {
681 fTypeNameStatus = typeNameChanged();
682 fieldName = TYPENAME;
683 } else if (field == fSuperClassDialogField) {
684 // fSuperClassStatus= superClassChanged();
686 } else if (field == fSuperInterfacesDialogField) {
687 // fSuperInterfacesStatus= superInterfacesChanged();
688 fieldName = INTERFACES;
689 } else if (field == fOtherMdfButtons) {
690 fModifierStatus = modifiersChanged();
691 fieldName = MODIFIERS;
696 handleFieldChanged(fieldName);
699 // -------- update message ----------------
702 * @see net.sourceforge.phpdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
704 protected void handleFieldChanged(String fieldName) {
705 super.handleFieldChanged(fieldName);
706 if (fieldName == CONTAINER) {
707 fPackageStatus = packageChanged();
708 // fEnclosingTypeStatus= enclosingTypeChanged();
709 fTypeNameStatus = typeNameChanged();
710 // fSuperClassStatus= superClassChanged();
711 // fSuperInterfacesStatus= superInterfacesChanged();
715 // ---- set / get ----------------
718 * Returns the text of the package input field.
720 * @return the text of the package input field
722 public String getPackageText() {
723 return fPackageDialogField.getText();
727 * Returns the text of the enclosing type input field.
729 * @return the text of the enclosing type input field
731 public String getEnclosingTypeText() {
732 return fEnclosingTypeDialogField.getText();
736 * Returns the package fragment corresponding to the current input.
738 * @return a package fragement or <code>null</code> if the input could not
741 public IPackageFragment getPackageFragment() {
742 if (!isEnclosingTypeSelected()) {
745 // if (fCurrEnclosingType != null) {
746 // return fCurrEnclosingType.getPackageFragment();
753 * Sets the package fragment to the given value. The method updates the
754 * model and the text of the control.
757 * the package fragement to be set
758 * @param canBeModified
759 * if <code>true</code> the package fragment is editable;
760 * otherwise it is read-only.
762 public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
764 fCanModifyPackage = canBeModified;
765 String str = (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
766 fPackageDialogField.setText(str);
771 * Returns the enclosing type corresponding to the current input.
773 * @return the enclosing type or <code>null</code> if the enclosing type
774 * is not selected or the input could not be resolved
776 public IType getEnclosingType() {
777 // if (isEnclosingTypeSelected()) {
778 // return fCurrEnclosingType;
784 * Sets the enclosing type. The method updates the underlying model and the
785 * text of the control.
789 * @param canBeModified
790 * if <code>true</code> the enclosing type field is editable;
791 * otherwise it is read-only.
793 // public void setEnclosingType(IType type, boolean canBeModified) {
794 // fCurrEnclosingType= type;
795 // fCanModifyEnclosingType= canBeModified;
796 // String str= (type == null) ? "" :
797 // JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
798 // fEnclosingTypeDialogField.setText(str);
799 // updateEnableState();
802 * Returns the selection state of the enclosing type checkbox.
804 * @return the seleciton state of the enclosing type checkbox
806 public boolean isEnclosingTypeSelected() {
807 return fEnclosingTypeSelection.isSelected();
811 * Sets the enclosing type checkbox's selection state.
814 * the checkbox's selection state
815 * @param canBeModified
816 * if <code>true</code> the enclosing type checkbox is
817 * modifiable; otherwise it is read-only.
819 public void setEnclosingTypeSelection(boolean isSelected,
820 boolean canBeModified) {
821 fEnclosingTypeSelection.setSelection(isSelected);
822 fEnclosingTypeSelection.setEnabled(canBeModified);
827 * Returns the type name entered into the type input field.
829 * @return the type name
831 public String getTypeName() {
832 return fTypeNameDialogField.getText();
836 * Sets the type name input field's text to the given value. Method doesn't
841 * @param canBeModified
842 * if <code>true</code> the enclosing type name field is
843 * editable; otherwise it is read-only.
845 public void setTypeName(String name, boolean canBeModified) {
846 fTypeNameDialogField.setText(name);
847 fTypeNameDialogField.setEnabled(canBeModified);
851 * Returns the selected modifiers.
853 * @return the selected modifiers
856 public int getModifiers() {
858 if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
860 } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
862 } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
865 // if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex
869 if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
872 if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
879 * Sets the modifiers.
882 * <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
883 * <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
884 * or <code>F_STATIC</code> or, a valid combination.
885 * @param canBeModified
886 * if <code>true</code> the modifier fields are editable;
887 * otherwise they are read-only
890 public void setModifiers(int modifiers, boolean canBeModified) {
891 if (Flags.isPublic(modifiers)) {
892 fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
893 } else if (Flags.isPrivate(modifiers)) {
894 fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
895 } else if (Flags.isProtected(modifiers)) {
896 fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
898 fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
900 // if (Flags.isAbstract(modifiers)) {
901 // fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
903 if (Flags.isFinal(modifiers)) {
904 fOtherMdfButtons.setSelection(FINAL_INDEX, true);
906 if (Flags.isStatic(modifiers)) {
907 fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
910 fAccMdfButtons.setEnabled(canBeModified);
911 fOtherMdfButtons.setEnabled(canBeModified);
915 * Returns the content of the superclass input field.
917 * @return the superclass name
919 public String getSuperClass() {
920 return fSuperClassDialogField.getText();
924 * Sets the super class name.
927 * the new superclass name
928 * @param canBeModified
929 * if <code>true</code> the superclass name field is editable;
930 * otherwise it is read-only.
932 public void setSuperClass(String name, boolean canBeModified) {
933 fSuperClassDialogField.setText(name);
934 fSuperClassDialogField.setEnabled(canBeModified);
938 * Returns the chosen super interfaces.
940 * @return a list of chosen super interfaces. The list's elements are of
941 * type <code>String</code>
943 public List getSuperInterfaces() {
944 return fSuperInterfacesDialogField.getElements();
948 * Sets the super interfaces.
950 * @param interfacesNames
951 * a list of super interface. The method requires that the list's
952 * elements are of type <code>String</code>
953 * @param canBeModified
954 * if <code>true</code> the super interface field is editable;
955 * otherwise it is read-only.
957 public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
958 fSuperInterfacesDialogField.setElements(interfacesNames);
959 fSuperInterfacesDialogField.setEnabled(canBeModified);
962 // ----------- validation ----------
965 * A hook method that gets called when the package field has changed. The
966 * method validates the package name and returns the status of the
967 * validation. The validation also updates the package fragment model.
969 * Subclasses may extend this method to perform their own validation.
972 * @return the status of the validation
974 protected IStatus packageChanged() {
975 StatusInfo status = new StatusInfo();
976 fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
978 // String packName= getPackageText();
979 // if (packName.length() > 0) {
980 // IStatus val= JavaConventions.validatePackageName(packName);
981 // if (val.getSeverity() == IStatus.ERROR) {
982 // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName",
983 // val.getMessage())); //$NON-NLS-1$
985 // } else if (val.getSeverity() == IStatus.WARNING) {
986 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName",
987 // val.getMessage())); //$NON-NLS-1$
992 // IPackageFragmentRoot root= getPackageFragmentRoot();
993 // if (root != null) {
994 // if (root.getJavaProject().exists() && packName.length() > 0) {
996 // IPath rootPath= root.getPath();
997 // IPath outputPath= root.getJavaProject().getOutputLocation();
998 // if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath))
1000 // // if the bin folder is inside of our root, dont allow to name a
1002 // // like the bin folder
1003 // IPath packagePath= rootPath.append(packName.replace('.', '/'));
1004 // if (outputPath.isPrefixOf(packagePath)) {
1005 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation"));
1010 // } catch (JavaModelException e) {
1011 // PHPeclipsePlugin.log(e);
1016 // fCurrPackage= root.getPackageFragment(packName);
1018 // status.setError(""); //$NON-NLS-1$
1024 * Updates the 'default' label next to the package field.
1026 private void updatePackageStatusLabel() {
1027 String packName = getPackageText();
1029 if (packName.length() == 0) {
1030 fPackageDialogField.setStatus(NewWizardMessages
1031 .getString("NewTypeWizardPage.default")); //$NON-NLS-1$
1033 fPackageDialogField.setStatus(""); //$NON-NLS-1$
1038 * Updates the enable state of buttons related to the enclosing type
1039 * selection checkbox.
1041 private void updateEnableState() {
1042 boolean enclosing = isEnclosingTypeSelected();
1043 fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
1044 fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType
1049 * Hook method that gets called when the enclosing type name has changed.
1050 * The method validates the enclosing type and returns the status of the
1051 * validation. It also updates the enclosing type model.
1053 * Subclasses may extend this method to perform their own validation.
1056 * @return the status of the validation
1058 // protected IStatus enclosingTypeChanged() {
1059 // StatusInfo status= new StatusInfo();
1060 // fCurrEnclosingType= null;
1062 // IPackageFragmentRoot root= getPackageFragmentRoot();
1064 // fEnclosingTypeDialogField.enableButton(root != null);
1065 // if (root == null) {
1066 // status.setError(""); //$NON-NLS-1$
1070 // String enclName= getEnclosingTypeText();
1071 // if (enclName.length() == 0) {
1072 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName"));
1077 // IType type= findType(root.getJavaProject(), enclName);
1078 // if (type == null) {
1079 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists"));
1084 // if (type.getCompilationUnit() == null) {
1085 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU"));
1089 // if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
1090 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable"));
1095 // fCurrEnclosingType= type;
1096 // IPackageFragmentRoot enclosingRoot=
1097 // JavaModelUtil.getPackageFragmentRoot(type);
1098 // if (!enclosingRoot.equals(root)) {
1099 // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder"));
1103 // } catch (JavaModelException e) {
1104 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists"));
1106 // PHPeclipsePlugin.log(e);
1111 * Hook method that gets called when the type name has changed. The method
1112 * validates the type name and returns the status of the validation.
1114 * Subclasses may extend this method to perform their own validation.
1117 * @return the status of the validation
1119 protected IStatus typeNameChanged() {
1120 StatusInfo status = new StatusInfo();
1121 String typeName = getTypeName();
1122 // must not be empty
1123 if (typeName.length() == 0) {
1124 status.setError(NewWizardMessages
1125 .getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
1128 if (typeName.indexOf('.') != -1) {
1129 status.setError(NewWizardMessages
1130 .getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
1133 // IStatus val= JavaConventions.validateJavaTypeName(typeName);
1134 // if (val.getSeverity() == IStatus.ERROR) {
1135 // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName",
1136 // val.getMessage())); //$NON-NLS-1$
1138 // } else if (val.getSeverity() == IStatus.WARNING) {
1139 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged",
1140 // val.getMessage())); //$NON-NLS-1$
1141 // // continue checking
1145 if (!isEnclosingTypeSelected()) {
1146 IPackageFragment pack = getPackageFragment();
1148 ICompilationUnit cu = pack.getCompilationUnit(typeName
1149 + ".java"); //$NON-NLS-1$
1150 if (cu.getResource().exists()) {
1152 .setError(NewWizardMessages
1153 .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
1158 IType type = getEnclosingType();
1160 IType member = type.getType(typeName);
1161 if (member.exists()) {
1163 .setError(NewWizardMessages
1164 .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
1173 * Hook method that gets called when the superclass name has changed. The
1174 * method validates the superclass name and returns the status of the
1177 * Subclasses may extend this method to perform their own validation.
1180 * @return the status of the validation
1182 // protected IStatus superClassChanged() {
1183 // StatusInfo status= new StatusInfo();
1184 // IPackageFragmentRoot root= getPackageFragmentRoot();
1185 // fSuperClassDialogField.enableButton(root != null);
1187 // fSuperClass= null;
1189 // String sclassName= getSuperClass();
1190 // if (sclassName.length() == 0) {
1191 // // accept the empty field (stands for java.lang.Object)
1194 // IStatus val= JavaConventions.validateJavaTypeName(sclassName);
1195 // if (val.getSeverity() == IStatus.ERROR) {
1196 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName"));
1200 // if (root != null) {
1202 // IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
1203 // if (type == null) {
1204 // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists"));
1208 // if (type.isInterface()) {
1209 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass",
1210 // sclassName)); //$NON-NLS-1$
1213 // int flags= type.getFlags();
1214 // if (Flags.isFinal(flags)) {
1215 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal",
1216 // sclassName)); //$NON-NLS-1$
1218 // } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
1219 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible",
1220 // sclassName)); //$NON-NLS-1$
1224 // fSuperClass= type;
1225 // } catch (JavaModelException e) {
1226 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName"));
1228 // PHPeclipsePlugin.log(e);
1231 // status.setError(""); //$NON-NLS-1$
1236 // private IType resolveSuperTypeName(IJavaProject jproject, String
1237 // sclassName) throws JavaModelException {
1238 // if (!jproject.exists()) {
1241 // IType type= null;
1242 // if (isEnclosingTypeSelected()) {
1243 // // search in the context of the enclosing type
1244 // IType enclosingType= getEnclosingType();
1245 // if (enclosingType != null) {
1246 // String[][] res= enclosingType.resolveType(sclassName);
1247 // if (res != null && res.length > 0) {
1248 // type= jproject.findType(res[0][0], res[0][1]);
1252 // IPackageFragment currPack= getPackageFragment();
1253 // if (type == null && currPack != null) {
1254 // String packName= currPack.getElementName();
1255 // // search in own package
1256 // if (!currPack.isDefaultPackage()) {
1257 // type= jproject.findType(packName, sclassName);
1259 // // search in java.lang
1260 // if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
1261 // type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
1264 // // search fully qualified
1265 // if (type == null) {
1266 // type= jproject.findType(sclassName);
1271 // private IType findType(IJavaProject project, String typeName) throws
1272 // JavaModelException {
1273 // if (project.exists()) {
1274 // return project.findType(typeName);
1279 * Hook method that gets called when the list of super interface has
1280 * changed. The method validates the superinterfaces and returns the status
1281 * of the validation.
1283 * Subclasses may extend this method to perform their own validation.
1286 * @return the status of the validation
1288 // protected IStatus superInterfacesChanged() {
1289 // StatusInfo status= new StatusInfo();
1291 // IPackageFragmentRoot root= getPackageFragmentRoot();
1292 // fSuperInterfacesDialogField.enableButton(0, root != null);
1294 // if (root != null) {
1295 // List elements= fSuperInterfacesDialogField.getElements();
1296 // int nElements= elements.size();
1297 // for (int i= 0; i < nElements; i++) {
1298 // String intfname= (String)elements.get(i);
1300 // IType type= findType(root.getJavaProject(), intfname);
1301 // if (type == null) {
1302 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists",
1303 // intfname)); //$NON-NLS-1$
1306 // if (type.isClass()) {
1307 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface",
1308 // intfname)); //$NON-NLS-1$
1311 // if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
1312 // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible",
1313 // intfname)); //$NON-NLS-1$
1317 // } catch (JavaModelException e) {
1318 // PHPeclipsePlugin.log(e);
1319 // // let pass, checking is an extra
1326 * Hook method that gets called when the modifiers have changed. The method
1327 * validates the modifiers and returns the status of the validation.
1329 * Subclasses may extend this method to perform their own validation.
1332 * @return the status of the validation
1334 protected IStatus modifiersChanged() {
1335 StatusInfo status = new StatusInfo();
1336 int modifiers = getModifiers();
1337 // if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
1338 // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract"));
1344 // selection dialogs
1346 // private IPackageFragment choosePackage() {
1347 // IPackageFragmentRoot froot= getPackageFragmentRoot();
1348 // IJavaElement[] packages= null;
1350 // if (froot != null && froot.exists()) {
1351 // packages= froot.getChildren();
1353 // } catch (JavaModelException e) {
1354 // PHPeclipsePlugin.log(e);
1356 // if (packages == null) {
1357 // packages= new IJavaElement[0];
1360 // ElementListSelectionDialog dialog= new
1361 // ElementListSelectionDialog(getShell(), new
1362 // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
1363 // dialog.setIgnoreCase(false);
1364 // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title"));
1366 // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description"));
1368 // dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty"));
1370 // dialog.setElements(packages);
1371 // IPackageFragment pack= getPackageFragment();
1372 // if (pack != null) {
1373 // dialog.setInitialSelections(new Object[] { pack });
1376 // if (dialog.open() == ElementListSelectionDialog.OK) {
1377 // return (IPackageFragment) dialog.getFirstResult();
1382 // private IType chooseEnclosingType() {
1383 // IPackageFragmentRoot root= getPackageFragmentRoot();
1384 // if (root == null) {
1388 // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new
1389 // IJavaElement[] { root });
1391 // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(),
1392 // getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
1393 // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title"));
1395 // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description"));
1397 // dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
1399 // if (dialog.open() == TypeSelectionDialog.OK) {
1400 // return (IType) dialog.getFirstResult();
1405 // private IType chooseSuperType() {
1406 // IPackageFragmentRoot root= getPackageFragmentRoot();
1407 // if (root == null) {
1411 // IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
1412 // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
1414 // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(),
1415 // getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
1416 // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title"));
1418 // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message"));
1420 // dialog.setFilter(getSuperClass());
1422 // if (dialog.open() == TypeSelectionDialog.OK) {
1423 // return (IType) dialog.getFirstResult();
1428 // private void chooseSuperInterfaces() {
1429 // IPackageFragmentRoot root= getPackageFragmentRoot();
1430 // if (root == null) {
1434 // IJavaProject project= root.getJavaProject();
1435 // SuperInterfaceSelectionDialog dialog= new
1436 // SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(),
1437 // fSuperInterfacesDialogField, project);
1438 // dialog.setTitle(fIsClass ?
1439 // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title")
1441 // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title"));
1442 // //$NON-NLS-1$ //$NON-NLS-2$
1443 // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message"));
1449 // ---- creation ----------------
1452 * Creates the new type using the entered field values.
1455 * a progress monitor to report progress.
1457 public void createType(IProgressMonitor monitor) throws CoreException,
1458 InterruptedException {
1459 if (monitor == null) {
1460 monitor = new NullProgressMonitor();
1463 monitor.beginTask(NewWizardMessages
1464 .getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
1465 ICompilationUnit createdWorkingCopy = null;
1467 // IPackageFragmentRoot root = getPackageFragmentRoot();
1468 // IPackageFragment pack = getPackageFragment();
1469 // if (pack == null) {
1470 // pack = root.getPackageFragment(""); //$NON-NLS-1$
1473 // if (!pack.exists()) {
1474 // String packName = pack.getElementName();
1475 // pack = root.createPackageFragment(packName, true, null);
1480 String clName = getTypeName();
1482 boolean isInnerClass = isEnclosingTypeSelected();
1485 // ImportsStructure imports;
1488 IPreferenceStore store = PreferenceConstants.getPreferenceStore();
1489 // String[] prefOrder =
1490 // JavaPreferencesSettings.getImportOrderPreference(store);
1492 // JavaPreferencesSettings.getImportNumberThreshold(store);
1494 String lineDelimiter = null;
1495 // if (!isInnerClass) {
1496 lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
1498 // ICompilationUnit parentCU = pack.createCompilationUnit(clName +
1499 // ".php", "", false, new SubProgressMonitor(monitor, 2));
1500 // //$NON-NLS-1$ //$NON-NLS-2$
1501 // createdWorkingCopy = (ICompilationUnit)
1502 // parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(),
1505 // imports = new ImportsStructure(createdWorkingCopy, prefOrder,
1506 // threshold, false);
1507 // // add an import that will be removed again. Having this import
1509 // imports.addImport(pack.getElementName(), getTypeName());
1511 String typeContent = constructTypeStub(lineDelimiter);// new
1512 // ImportsManager(imports),
1515 // String cuContent = constructCUContent(parentCU, typeContent,
1518 // createdWorkingCopy.getBuffer().setContents(cuContent);
1520 createdType = createdWorkingCopy.getType(clName);
1522 // IType enclosingType = getEnclosingType();
1524 // // if we are working on a enclosed type that is open in an
1526 // // then replace the enclosing type with its working copy
1527 // IType workingCopy = (IType)
1528 // EditorUtility.getWorkingCopy(enclosingType);
1529 // if (workingCopy != null) {
1530 // enclosingType = workingCopy;
1533 // ICompilationUnit parentCU = enclosingType.getCompilationUnit();
1534 // imports = new ImportsStructure(parentCU, prefOrder, threshold,
1537 // // add imports that will be removed again. Having the imports
1539 // IType[] topLevelTypes = parentCU.getTypes();
1540 // for (int i = 0; i < topLevelTypes.length; i++) {
1541 // imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
1544 // lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
1545 // StringBuffer content = new StringBuffer();
1546 // String comment = getTypeComment(parentCU);
1547 // if (comment != null) {
1548 // content.append(comment);
1549 // content.append(lineDelimiter);
1551 // content.append(constructTypeStub(new ImportsManager(imports),
1553 // IJavaElement[] elems = enclosingType.getChildren();
1554 // IJavaElement sibling = elems.length > 0 ? elems[0] : null;
1556 // createdType = enclosingType.createType(content.toString(),
1557 // sibling, false, new SubProgressMonitor(monitor, 1));
1559 // indent = StubUtility.getIndentUsed(enclosingType) + 1;
1562 // // add imports for superclass/interfaces, so types can be
1563 // resolved correctly
1564 // imports.create(false, new SubProgressMonitor(monitor, 1));
1566 ICompilationUnit cu = createdType.getCompilationUnit();
1570 // createTypeMembers(createdType, new ImportsManager(imports), new
1571 // SubProgressMonitor(monitor, 1));
1574 // imports.create(false, new SubProgressMonitor(monitor, 1));
1579 ISourceRange range = createdType.getSourceRange();
1581 IBuffer buf = cu.getBuffer();
1582 String originalContent = buf.getText(range.getOffset(), range
1584 String formattedContent = StubUtility.codeFormat(originalContent,
1585 indent, lineDelimiter);
1586 buf.replace(range.getOffset(), range.getLength(), formattedContent);
1587 if (!isInnerClass) {
1588 String fileComment = getFileComment(cu);
1589 if (fileComment != null && fileComment.length() > 0) {
1590 buf.replace(0, 0, fileComment + lineDelimiter);
1592 cu.commit(false, new SubProgressMonitor(monitor, 1));
1596 fCreatedType = createdType;
1598 if (createdWorkingCopy != null) {
1599 createdWorkingCopy.destroy();
1606 * Uses the New Java file template from the code template page to generate a
1607 * compilation unit with the given type content.
1610 * The new created compilation unit
1611 * @param typeContent
1612 * The content of the type, including signature and type body.
1613 * @param lineDelimiter
1614 * The line delimiter to be used.
1615 * @return String Returns the result of evaluating the new file template
1616 * with the given type content.
1617 * @throws CoreException
1620 // protected String constructCUContent(ICompilationUnit cu, String
1621 // typeContent, String lineDelimiter) throws CoreException {
1622 // StringBuffer typeQualifiedName= new StringBuffer();
1623 // if (isEnclosingTypeSelected()) {
1624 // typeQualifiedName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
1626 // typeQualifiedName.append(getTypeName());
1627 // String typeComment= CodeGeneration.getTypeComment(cu,
1628 // typeQualifiedName.toString(), lineDelimiter);
1629 // IPackageFragment pack= (IPackageFragment) cu.getParent();
1630 // String content= CodeGeneration.getCompilationUnitContent(cu, typeComment,
1631 // typeContent, lineDelimiter);
1632 // if (content != null) {
1633 // CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray());
1634 // if ((pack.isDefaultPackage() || unit.getPackage() != null) &&
1635 // !unit.types().isEmpty()) {
1639 // StringBuffer buf= new StringBuffer();
1640 // if (!pack.isDefaultPackage()) {
1641 // buf.append("package ").append(pack.getElementName()).append(';');
1644 // buf.append(lineDelimiter).append(lineDelimiter);
1645 // if (typeComment != null) {
1646 // buf.append(typeComment).append(lineDelimiter);
1648 // buf.append(typeContent);
1649 // return buf.toString();
1652 * Returns the created type. The method only returns a valid type after
1653 * <code>createType</code> has been called.
1655 * @return the created type
1656 * @see #createType(IProgressMonitor)
1658 public IType getCreatedType() {
1659 return fCreatedType;
1662 // ---- construct cu body----------------
1664 // private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
1665 // String typename= getSuperClass();
1666 // if (fIsClass && typename.length() > 0 &&
1667 // !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
1668 // buf.append(" extends "); //$NON-NLS-1$
1670 // String qualifiedName= fSuperClass != null ?
1671 // JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
1672 // buf.append(imports.addImport(qualifiedName));
1676 // private void writeSuperInterfaces(StringBuffer buf, ImportsManager
1678 // List interfaces= getSuperInterfaces();
1679 // int last= interfaces.size() - 1;
1682 // buf.append(" implements "); //$NON-NLS-1$
1684 // buf.append(" extends "); //$NON-NLS-1$
1686 // for (int i= 0; i <= last; i++) {
1687 // String typename= (String) interfaces.get(i);
1688 // buf.append(imports.addImport(typename));
1697 * Called from createType to construct the source for this type
1699 private String constructTypeStub(String lineDelimiter) { // ImportsManager
1704 StringBuffer buf = new StringBuffer();
1706 int modifiers = getModifiers();
1707 buf.append(Flags.toString(modifiers));
1708 if (modifiers != 0) {
1711 buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
1712 buf.append(getTypeName());
1713 // writeSuperClass(buf, imports);
1714 // writeSuperInterfaces(buf, imports);
1716 buf.append(lineDelimiter);
1717 buf.append(lineDelimiter);
1719 buf.append(lineDelimiter);
1720 return buf.toString();
1724 * @deprecated Overwrite createTypeMembers(IType, IImportsManager,
1725 * IProgressMonitor) instead
1727 // protected void createTypeMembers(IType newType, IImportsStructure
1728 // imports, IProgressMonitor monitor) throws CoreException {
1732 * Hook method that gets called from <code>createType</code> to support
1733 * adding of unanticipated methods, fields, and inner types to the created
1736 * Implementers can use any methods defined on <code>IType</code> to
1737 * manipulate the new type.
1740 * The source code of the new type will be formtted using the platform's
1741 * formatter. Needed imports are added by the wizard at the end of the type
1742 * creation process using the given import manager.
1746 * the new type created via <code>createType</code>
1748 * an import manager which can be used to add new imports
1750 * a progress monitor to report progress. Must not be
1753 * @see #createType(IProgressMonitor)
1755 // protected void createTypeMembers(IType newType, ImportsManager imports,
1756 // IProgressMonitor monitor) throws CoreException {
1757 // // call for compatibility
1758 // createTypeMembers(newType,
1759 // ((ImportsManager)imports).getImportsStructure(), monitor);
1761 // // default implementation does nothing
1762 // // example would be
1763 // // String mainMathod= "public void foo(Vector vec) {}"
1764 // // createdType.createMethod(main, null, false, null);
1765 // // imports.addImport("java.lang.Vector");
1768 * @deprecated Instead of file templates, the new type code template
1769 * specifies the stub for a compilation unit.
1771 protected String getFileComment(ICompilationUnit parentCU) {
1775 private boolean isValidComment(String template) {
1776 IScanner scanner = ToolFactory.createScanner(true, false, false); // ,
1778 scanner.setSource(template.toCharArray());
1780 int next = scanner.getNextToken();
1781 while (next == ITerminalSymbols.TokenNameCOMMENT_LINE
1782 || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC
1783 || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) {
1784 next = scanner.getNextToken();
1786 return next == ITerminalSymbols.TokenNameEOF;
1787 } catch (InvalidInputException e) {
1793 * Hook method that gets called from <code>createType</code> to retrieve a
1794 * type comment. This default implementation returns the content of the
1795 * 'typecomment' template.
1797 * @return the type comment or <code>null</code> if a type comment is not
1800 protected String getTypeComment(ICompilationUnit parentCU) {
1801 if (PreferenceConstants.getPreferenceStore().getBoolean(
1802 PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
1804 StringBuffer typeName = new StringBuffer();
1805 if (isEnclosingTypeSelected()) {
1808 .getTypeQualifiedName(getEnclosingType()))
1811 typeName.append(getTypeName());
1812 String comment = CodeGeneration.getTypeComment(parentCU,
1813 typeName.toString(), String.valueOf('\n'));
1814 if (comment != null && isValidComment(comment)) {
1817 } catch (CoreException e) {
1818 PHPeclipsePlugin.log(e);
1825 * @deprecated Use getTemplate(String,ICompilationUnit,int)
1827 protected String getTemplate(String name, ICompilationUnit parentCU) {
1828 return getTemplate(name, parentCU, 0);
1832 * Returns the string resulting from evaluation the given template in the
1833 * context of the given compilation unit. This accesses the normal template
1834 * page, not the code templates. To use code templates use
1835 * <code>constructCUContent</code> to construct a compilation unit stub or
1836 * getTypeComment for the comment of the type.
1839 * the template to be evaluated
1841 * the templates evaluation context
1843 * a source offset into the parent compilation unit. The template
1844 * is evalutated at the given source offset
1846 protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
1848 Template[] templates = Templates.getInstance().getTemplates(name);
1849 if (templates.length > 0) {
1851 .evaluateTemplate(templates[0], parentCU, pos);
1853 } catch (CoreException e) {
1854 PHPeclipsePlugin.log(e);
1855 } catch (BadLocationException e1) {
1856 // TODO Auto-generated catch block
1857 e1.printStackTrace();
1858 } catch (TemplateException e1) {
1859 // TODO Auto-generated catch block
1860 e1.printStackTrace();
1867 * createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
1869 // protected IMethod[] createInheritedMethods(IType type, boolean
1870 // doConstructors, boolean doUnimplementedMethods, IImportsStructure
1871 // imports, IProgressMonitor monitor) throws CoreException {
1872 // return createInheritedMethods(type, doConstructors,
1873 // doUnimplementedMethods, new ImportsManager(imports), monitor);
1876 * Creates the bodies of all unimplemented methods and constructors and adds
1877 * them to the type. Method is typically called by implementers of
1878 * <code>NewTypeWizardPage</code> to add needed method and constructors.
1881 * the type for which the new methods and constructor are to be
1883 * @param doConstructors
1884 * if <code>true</code> unimplemented constructors are created
1885 * @param doUnimplementedMethods
1886 * if <code>true</code> unimplemented methods are created
1888 * an import manager to add all neded import statements
1890 * a progress monitor to report progress
1892 // protected IMethod[] createInheritedMethods(IType type, boolean
1893 // doConstructors, boolean doUnimplementedMethods, ImportsManager imports,
1894 // IProgressMonitor monitor) throws CoreException {
1895 // ArrayList newMethods= new ArrayList();
1896 // ITypeHierarchy hierarchy= null;
1897 // CodeGenerationSettings settings=
1898 // JavaPreferencesSettings.getCodeGenerationSettings();
1900 // if (doConstructors) {
1901 // hierarchy= type.newSupertypeHierarchy(monitor);
1902 // IType superclass= hierarchy.getSuperclass(type);
1903 // if (superclass != null) {
1904 // String[] constructors= StubUtility.evalConstructors(type, superclass,
1905 // settings, imports.getImportsStructure());
1906 // if (constructors != null) {
1907 // for (int i= 0; i < constructors.length; i++) {
1908 // newMethods.add(constructors[i]);
1914 // if (doUnimplementedMethods) {
1915 // if (hierarchy == null) {
1916 // hierarchy= type.newSupertypeHierarchy(monitor);
1918 // String[] unimplemented= StubUtility.evalUnimplementedMethods(type,
1919 // hierarchy, false, settings, null, imports.getImportsStructure());
1920 // if (unimplemented != null) {
1921 // for (int i= 0; i < unimplemented.length; i++) {
1922 // newMethods.add(unimplemented[i]);
1926 // IMethod[] createdMethods= new IMethod[newMethods.size()];
1927 // for (int i= 0; i < newMethods.size(); i++) {
1928 // String content= (String) newMethods.get(i) + '\n'; // content will be
1929 // formatted, ok to use \n
1930 // createdMethods[i]= type.createMethod(content, null, false, null);
1932 // return createdMethods;
1934 // ---- creation ----------------
1936 * Returns the runnable that creates the type using the current settings.
1937 * The returned runnable must be executed in the UI thread.
1939 * @return the runnable to create the new type
1941 // public IRunnableWithProgress getRunnable() {
1942 // return new IRunnableWithProgress() {
1943 // public void run(IProgressMonitor monitor) throws
1944 // InvocationTargetException, InterruptedException {
1946 // if (monitor == null) {
1947 // monitor= new NullProgressMonitor();
1949 // createType(monitor);
1950 // } catch (CoreException e) {
1951 // throw new InvocationTargetException(e);