Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2005, 2009 BEA Systems, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: wharley@bea.com - initial API and implementation /
 
 package org.eclipse.jdt.apt.ui.internal.preferences;
 
 import java.util.List;
 import java.util.Map;
 
 
 import  org.eclipse.swt.SWT;
 import  org.eclipse.swt.graphics.Image;
 import  org.eclipse.swt.widgets.Composite;
 import  org.eclipse.swt.widgets.Control;
 
 import  org.eclipse.core.runtime.CoreException;
 import  org.eclipse.core.runtime.IPath;
 import  org.eclipse.core.runtime.Path;
 import  org.eclipse.core.runtime.preferences.IScopeContext;
 
 
 
 
 
 
Data and controls for the Java Annotation Factory Path preference page.
 
 
 	private static final int IDX_UP= 0;
 	private static final int IDX_DOWN= 1;
 	// 2
 	private static final int IDX_ADDJAR= 3;
 	private static final int IDX_ADDEXTJAR= 4;
 	private static final int IDX_ADDVAR= 5;
 	// 6
 	private static final int IDX_EDIT= 7;
 	private static final int IDX_ADVANCED= 8;
 	private static final int IDX_REMOVE= 9;
 	// 10
 	private static final int IDX_ENABLEALL= 11;
 	private static final int IDX_DISABLEALL= 12;
 
 	private final static String[] buttonLabels = {
 		null,                    // 2
 		null,                    // 6
 		null,                    // 10
 	};

Event handler for factory path list control
	private class FactoryPathAdapter implements IListAdapterIDialogFieldListener {
        public void customButtonPressed(ListDialogField fieldint index) {
        }
        public void selectionChanged(ListDialogField field) {
        	boolean enableRemove = canRemove();
        	field.enableButton(enableRemove);
        	boolean enableEdit = canEdit();
        	field.enableButton(enableEdit);
        	boolean enableAdvanced = canAdvanced();
        	field.enableButton(enableAdvanced);
        }

        
This method gets called when, among other things, a checkbox is clicked. However, it doesn't get any information about which item it was whose checkbox was clicked. We could hook into the list control's CheckboxTableViewer event listener for changes to individual checkboxes; but that does not get called for enableAll and disableAll events.
		public void dialogFieldChanged(DialogField field) {
			}
        }
		public void doubleClicked(ListDialogField field) {
        	if (canEdit()) {
        		editSelectedItem();
        	}
        }
	}
	private class FactoryPathLabelProvider extends LabelProvider implements ITableLabelProvider {
		public Image getColumnImage(Object elementint columnIndex) {
			return null;
		}
		public String getColumnText(Object elementint columnIndex) {
			if (!(element instanceof FactoryPathEntry)) {
				return ""//$NON-NLS-1$
			}
			if (columnIndex == 0) {
				return fpe._fc.toString();
			}
			else {
				return ""//$NON-NLS-1$
			}
		}
	}

The factory path is a list of containers, plus some information about each container. That makes it a list of FactoryPathEntry.
	private static class FactoryPathEntry {
		/* shallow copies - beware! */
		public final FactoryContainer _fc;
		// CONSTRUCTORS
			 = fc;
			 = attr;
		}
		// CONVERSION TO/FROM INDIVIDUAL ELEMENTS
			for (FactoryPathEntry fpe : list) {
				map.put(fpe._fcfpe._attr);
			}
			return map;
		}
			for (Map.Entry<FactoryContainerAttributesentry : map.entrySet()) {
				FactoryPathEntry fpe = new FactoryPathEntry(entry.getKey(), entry.getValue());
				list.add(fpe);
			}
			return list;
		}
		// SUPPORT FOR COMPARISON
		public boolean equals(Object obj) {
			if (!(obj instanceof FactoryPathEntry))
				return false;
			return .equals(fpe._fc) && .equals(fpe._attr);
		}
		public int hashCode() {
			return .hashCode() ^ .hashCode();
		}
	}
	private Composite fBlockControl// the control representing the entire configuration block
The factory path at the time this pref pane was launched. Use this to see if anything changed at save time.
	private final IJavaProject fJProj;

The GUI control representing the factory path. Its data items are of type FactoryPathEntry.
True while inside setListContents(). Used in order to efficiently and correctly add new elements to the factory list: short-circuits the factory list field listener code.
	private boolean fSettingListContents = false;
			IProject projectIWorkbenchPreferenceContainer container) {
		super(contextprojectnew Key[] {}, container);
		 = JavaCore.create(project);
		new CheckedListDialogField(adapterlabelProvider);
	}

Respond to the user checking the "enabled" checkbox of an entry in the factory path control, by replacing the FactoryPathEntry with a new one with the correct "enabled" value. We don't have information about which entry was changed, so we have to look at all of them. This is inefficient - somewhere around O(n log n) depending on how the list is implemented - but hopefully the list is not so huge that it's a problem.
	private void updateFactoryPathEntries() {
		for (FactoryPathEntry fpe : getListContents()) {
			boolean checked = .isChecked(fpe);
			if (checked != fpe._attr.isEnabled()) {
				fpe._attr.setEnabled(checked);
			}
		}
	}

Respond to a button in the button bar. Most buttons are handled by code in CheckedListDialogField; this method is for the rest, e.g., Add External Jar.

Parameters:
index
	public void customButtonPressed(int index) {
		FactoryPathEntry[] newEntries = null;
		switch (index) {
		case // add jars in project
			newEntriesopenJarFileDialog(null);
			addEntries(newEntries);
			break;
		case // add external jars
			newEntriesopenExtJarFileDialog(null);
			addEntries(newEntries);
			break;
		case // add jar from classpath variable
			newEntriesopenVariableSelectionDialog(null);
			addEntries(newEntries);
			break;
		case // edit selected item
			if (canEdit()) {
			}
			break;
		case // advanced options
			break;
		}
	}

Can't remove a selection that contains a plugin.
	private boolean canRemove() {
		boolean containsPluginfalse;
		for (FactoryPathEntry fpe : selected) {
				containsPlugin = true;
				break;
			}
		}
		return !containsPlugin;
	}

Can only edit a single item at a time. Can't edit plugins.
	private boolean canEdit() {
		if (selected.size() != 1) {
			return false;
		}
		FactoryContainer fc = selected.get(0).;
	}

Can only launch the 'advanced' dialog on a single item at a time.
	private boolean canAdvanced() {
		return (selected.size() == 1);
	}

Edit the item selected. Precondition: exactly one item is selected in the list, and it is an editable item (not a plugin).

Parameters:
field a listbox of FactoryContainers.
	private void editSelectedItem() {
		if (selected.size() != 1) {
			return;
		}
		FactoryPathEntry original = selected.get(0);
		FactoryPathEntry[] edited = null;
		switch (original._fc.getType()) {
		case :
			return;
		case :
			editedopenExtJarFileDialog(original);
			break;
		case :
			editedopenVariableSelectionDialog(original);
			break;
		case :
			editedopenJarFileDialog(original);
			break;
		}
		if (edited != null && edited.length > 0) {
			.replaceElement(originaledited[0]);
		}
	}
	/* (non-Javadoc)
	 * @see org.eclipse.jdt.apt.ui.internal.preferences.BaseConfigurationBlock#createContents(org.eclipse.swt.widgets.Composite)
	 */
	protected Control createContents(Composite parent) {
		setShell(parent.getShell());
		new Composite(parent, SWT.NONE);
		.setFont(parent.getFont());
		LayoutUtil.doDefaultLayout(new DialogField[] {  }, true, SWT.DEFAULT, SWT.DEFAULT);
		// bugzilla 139101: only enable Advanced and Edit buttons if there is a selection
	}
	public boolean hasProjectSpecificOptionsNoCache(IProject project) {
		return (project == null) ? false : AptConfig.hasProjectSpecificFactoryPath(JavaCore.create(project));
	}

Initialize the user interface based on the cached original settings.
	protected void initContents() {
	}

Save reference copies of the settings, so we can see if anything changed. This must stay in sync with the actual saved values for the rebuild logic to work; so be sure to call this any time you save (eg in performApply()).
	protected void cacheOriginalValues() {
		IFactoryPath ifp = AptConfig.getFactoryPath();
		// we'll risk this downcast because we're such good buddies with apt.core.
		 = FactoryPathEntry.pathListFromMap(path);
	}
	/*
	 * Helper method to get rid of unchecked conversion warning
	 */
	@SuppressWarnings("unchecked")
		return contents;
	}
	/*
	 * Helper method to get rid of unchecked conversion warning
	 */
	@SuppressWarnings("unchecked")
		return contents;
	}

Add new entries to the list control. Differs from setListContents() in that the list is not cleared first, and the entries are not copied before being added to the list.

Parameters:
entries can be null.
	private void addEntries(FactoryPathEntry[] entries) {
		if (null == entries) {
			return;
		}
		int insertAt;
		if (selectedElements.size() == 1) {
			insertAt.getIndexOfElement(selectedElements.get(0)) + 1;
else {
		}
		try {
			for (int i = 0; i < entries.length; ++i) {
				.addElement(entries[i], insertAt + i);
				.setChecked(entries[i], entries[i]..isEnabled());
			}
		}
		finally {
		}
	}

Set the contents of the list control. The FPEs in the input list will be copied; the originals are left untouched, so that if the list control's contents are modified they can be compared with the original.

Parameters:
fpeList can be null.
	private void setListContents(List<FactoryPathEntryfpeList) {
		try {
			if (fpeList == null) {
				return;
			}
			for (FactoryPathEntry originalFpe : fpeList) {
				// clone, because we may later want to compare with the original.
				FactoryPathEntry fpe = new FactoryPathEntry(originalFpe._fcnew Attributes(originalFpe._attr));
			}
		}
		finally {
		}
	}

Get all the containers of a certain type currently on the list. The format of the returned paths will depend on the container type: for EXTJAR it will be an absolute path; for WKSPJAR it will be a path relative to the workspace root; for VARJAR it will be a path whose first segment is the name of a classpath variable.

Parameters:
type may not be PLUGIN
ignore null, or an item to not put on the list (used when editing an existing item).
Returns:
an array, possibly empty (but never null)
	private IPath[] getExistingPaths(FactoryContainer.FactoryType typeFactoryContainer ignore) {
		}
		// find out how many entries there are of this type
		int countType = 0;
		for (FactoryPathEntry fpe : all) {
			FactoryContainer fc = fpe._fc;
			if (fc.getType() == type && fc != ignore) {
				++countType;
			}
		}
		// create an array of paths, one per entry of this type
		IPath[] some = new IPath[countType];
		int i = 0;
		for (FactoryPathEntry fpe : all) {
			FactoryContainer fc = fpe._fc;
			if (fc.getType() == type && fc != ignore) {
				some[i++] = new Path(fc.getId());
			}
		}
		return some;
	}

Launch the "advanced options" dialog, which displays the factory classes contained by the selected container and allows the user to specify options that are needed only in certain special cases. We treat advanced options as an attribute of the factory path, not of the container; the same container may have different advanced options in different projects. We treat advanced options the same way as the "enabled" flag.
	private void advancedOptionsDialog() {
		if (selected.size() != 1) {
			return;
		}
		FactoryPathEntry originalselected.get(0);
			new AdvancedFactoryPathOptionsDialog(getShell(), original._fcoriginal._attr);
		if (dialog.open() == .) {
			original._attr = dialog.getResult();
			// If the dialog could change the enabled attribute, we would also
			// need to update the checkbox in the GUI here.  But it doesn't.
		}
	}

Add or edit a project-relative jar file. Only possible when editing project properties; this method is disabled in workspace prefs.

Parameters:
original null, or an existing list entry to be edited
Returns:
a list of additional factory path entries to be added
		if ( == null) {
			return null;
		}
		if (original == null) {
			IPath[] results= BuildPathDialogAccess.chooseJAREntries(getShell(), .getPath(), new IPath[0]);
			if (results == null) {
				return null;
			}
			for (int i= 0; i < results.lengthi++) {
				IResource resourceroot.findMember(results[i]);
				if (resource instanceof IFile) {
					FactoryContainer fc = FactoryPathUtil.newWkspJarFactoryContainer(results[i]);
					// assume defaults of enabled=true, runInAptMode=false
					FactoryPath.Attributes attr = new FactoryPath.Attributes(truefalse);
					FactoryPathEntry fpe = new FactoryPathEntry(fcattr);
					res.add(fpe);
				}
				//TODO: handle missing jars
			}
			return res.toArray(new FactoryPathEntry[res.size()]);
		}
		else {
			IPath[] existingPaths = getExistingPaths(..original._fc);
			IPath result= BuildPathDialogAccess.configureJAREntry(getShell(), new Path(original._fc.getId()), existingPaths);
			if (result == null) {
				return null;
			}
			IResource resourceroot.findMember(result);
			if (resource instanceof IFile) {
				FactoryPathEntry[] edited = new FactoryPathEntry[1];
				FactoryContainer fc= FactoryPathUtil.newWkspJarFactoryContainer(result);
				// Use prior value for isEnabled.  Assume default of runInAptMode=false
				FactoryPath.Attributes attr = new FactoryPath.Attributes(original._attr.isEnabled(), false);
				edited[0]= new FactoryPathEntry(fcattr);
				return edited;
			}
			//TODO: handle missing jars
			return null;
 		}
	}

Add or edit an external (not project-relative) jar file.

Parameters:
original null, or an existing list entry to be edited
Returns:
a list of additional factory path entries to be added
		if (original == null) {
			IPath[] selected= BuildPathDialogAccess.chooseExternalJAREntries(getShell());
			if (selected == null) {
				return null;
			}
			for (int i= 0; i < selected.lengthi++) {
				FactoryContainer fc = FactoryPathUtil.newExtJarFactoryContainer(selected[i].toFile());
				// assume defaults of enabled=true, runInAptMode=false
				FactoryPath.Attributes attr = new FactoryPath.Attributes(truefalse);
				FactoryPathEntry fpe = new FactoryPathEntry(fcattr);
				res.add(fpe);
			}
			return res.toArray(new FactoryPathEntry[res.size()]);
		}
		else {
			IPath result= BuildPathDialogAccess.configureExternalJAREntry(getShell(), new Path(original._fc.getId()));
			if (result == null) {
				return null;
			}
			FactoryContainer fc= FactoryPathUtil.newExtJarFactoryContainer(result.toFile());
			// Use prior value for isEnabled.  Assume default of runInAptMode=false
			FactoryPath.Attributes attr = new FactoryPath.Attributes(original._attr.isEnabled(), false);
			edited[0]= new FactoryPathEntry(fcattr);
			return edited;
		}
	}

Add or edit an external (not project-relative) jar file whose location includes a classpath variable name.

Parameters:
original null, or an existing list entry to be edited
Returns:
a list of additional factory path entries to be added
		if (original == null) {
			IPath[] selected= BuildPathDialogAccess.chooseVariableEntries(getShell(), new IPath[0]);
			if (selected == null) {
				return null;
			}
			for (int i= 0; i < selected.lengthi++) {
				FactoryContainer fc= FactoryPathUtil.newVarJarFactoryContainer(selected[i]);
				// assume defaults of enabled=true, runInAptMode=false
				FactoryPath.Attributes attr = new FactoryPath.Attributes(truefalse);
				FactoryPathEntry fpe = new FactoryPathEntry(fcattr);
				res.add(fpe);
			}
			return res.toArray(new FactoryPathEntry[res.size()]);
		}
		else {
			IPath[] existingPaths = getExistingPaths(..original._fc);
			IPath result= BuildPathDialogAccess.configureVariableEntry(getShell(), new Path(original._fc.getId()), existingPaths);
			if (result == null) {
				return null;
			}
			FactoryContainer fc= FactoryPathUtil.newVarJarFactoryContainer(result);
			// Use prior value for isEnabled.  Assume default of runInAptMode=false
			FactoryPath.Attributes attr = new FactoryPath.Attributes(original._attr.isEnabled(), false);
			edited[0]= new FactoryPathEntry(fcattr);
			return edited;
		}
	}
	/* (non-Javadoc)
	 * @see org.eclipse.jdt.apt.ui.internal.preferences.BaseConfigurationBlock#updateModel(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
	 */
	protected void updateModel(DialogField field) {
		// We don't use IEclipsePreferences for this pane, so no need to do anything.
	}
	/* (non-Javadoc)
	 * @see org.eclipse.jdt.apt.ui.internal.preferences.BaseConfigurationBlock#validateSettings(org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock.Key, java.lang.String, java.lang.String)
	 */
	protected void validateSettings(Key changedKeyString oldValueString newValue) {
		// TODO: validate that all the specified factory containers exist?
	}
	protected void saveSettings() {
		if (( != null) && !.isEnabled()) {
			// We're in a project properties pane but the entire configuration
			// block control is disabled.  That means the per-project settings checkbox
			// is unchecked.  To save that state, we'll delete the settings file.
			fp = null;
		}
		else {
			List<FactoryPathEntrycontainers;
			containers = getListContents();
			map = FactoryPathEntry.pathMapFromList(containers);
			fp = new FactoryPath();
		}
		try {
			AptConfig.setFactoryPath(fp);
		}
		catch (CoreException e) {
			ExceptionHandler.handle(e.getShell(), titlemessage);
		}
		super.saveSettings();
	}

If per-project, restore list contents to current workspace settings; the per-project settings checkbox will be cleared for us automatically. If workspace, restore list contents to factory-default settings.
	public void performDefaults() {
		// we'll risk this downcast because we're such good buddies with apt.core.
		List<FactoryPathEntrydefaults = FactoryPathEntry.pathListFromMap(map);
		setListContents(defaults);
	}

Returns:
true if settings or project-specificness changed since the pane was launched - that is, if there is anything to save.
	protected boolean settingsChanged(IScopeContext currContext) {
		if ( == null) {
			// shouldn't happen, but just in case it does, consider it a change.
			return true;
		}
		// Is the new path the same size, containing the same items
		// in the same order?  We rely on FactoryPathEntry.equals() here.
		return !.equals(newPath);
	}
New to GrepCode? Check out our FAQ X