0001: /*******************************************************************************
0002: * Copyright (c) 2000, 2007 IBM Corporation and others.
0003: * All rights reserved. This program and the accompanying materials
0004: * are made available under the terms of the Eclipse Public License v1.0
0005: * which accompanies this distribution, and is available at
0006: * http://www.eclipse.org/legal/epl-v10.html
0007: *
0008: * Contributors:
0009: * IBM Corporation - initial API and implementation
0010: *******************************************************************************/package org.eclipse.jdt.internal.ui.preferences;
0011:
0012: import java.io.File;
0013: import java.io.FileInputStream;
0014: import java.io.FileOutputStream;
0015: import java.io.IOException;
0016: import java.io.InputStream;
0017: import java.io.OutputStream;
0018: import java.lang.reflect.InvocationTargetException;
0019: import java.util.ArrayList;
0020: import java.util.Arrays;
0021: import java.util.HashMap;
0022: import java.util.HashSet;
0023: import java.util.Iterator;
0024: import java.util.List;
0025: import java.util.Map;
0026:
0027: import javax.xml.parsers.DocumentBuilder;
0028: import javax.xml.parsers.DocumentBuilderFactory;
0029: import javax.xml.parsers.ParserConfigurationException;
0030: import javax.xml.transform.OutputKeys;
0031: import javax.xml.transform.Transformer;
0032: import javax.xml.transform.TransformerException;
0033: import javax.xml.transform.TransformerFactory;
0034: import javax.xml.transform.dom.DOMSource;
0035: import javax.xml.transform.stream.StreamResult;
0036:
0037: import org.eclipse.core.runtime.CoreException;
0038: import org.eclipse.core.runtime.IPath;
0039: import org.eclipse.core.runtime.IProgressMonitor;
0040: import org.eclipse.core.runtime.IStatus;
0041: import org.eclipse.core.runtime.MultiStatus;
0042: import org.eclipse.core.runtime.NullProgressMonitor;
0043: import org.eclipse.core.runtime.Path;
0044:
0045: import org.eclipse.core.resources.IFile;
0046: import org.eclipse.core.resources.IProject;
0047: import org.eclipse.core.resources.IResource;
0048: import org.eclipse.core.resources.IWorkspaceRoot;
0049: import org.eclipse.core.resources.ResourcesPlugin;
0050:
0051: import org.eclipse.swt.SWT;
0052: import org.eclipse.swt.events.KeyEvent;
0053: import org.eclipse.swt.graphics.Point;
0054: import org.eclipse.swt.layout.GridData;
0055: import org.eclipse.swt.widgets.Composite;
0056: import org.eclipse.swt.widgets.Control;
0057: import org.eclipse.swt.widgets.FileDialog;
0058: import org.eclipse.swt.widgets.Shell;
0059:
0060: import org.eclipse.jface.dialogs.Dialog;
0061: import org.eclipse.jface.dialogs.IDialogSettings;
0062: import org.eclipse.jface.dialogs.MessageDialog;
0063: import org.eclipse.jface.dialogs.StatusDialog;
0064: import org.eclipse.jface.operation.IRunnableContext;
0065: import org.eclipse.jface.operation.IRunnableWithProgress;
0066: import org.eclipse.jface.preference.PreferencePage;
0067: import org.eclipse.jface.resource.StringConverter;
0068: import org.eclipse.jface.viewers.AbstractTreeViewer;
0069: import org.eclipse.jface.viewers.StructuredSelection;
0070: import org.eclipse.jface.window.Window;
0071:
0072: import org.eclipse.ui.IWorkbench;
0073: import org.eclipse.ui.IWorkbenchPreferencePage;
0074: import org.eclipse.ui.PlatformUI;
0075:
0076: import org.eclipse.jdt.core.ClasspathContainerInitializer;
0077: import org.eclipse.jdt.core.IAccessRule;
0078: import org.eclipse.jdt.core.IClasspathAttribute;
0079: import org.eclipse.jdt.core.IClasspathContainer;
0080: import org.eclipse.jdt.core.IClasspathEntry;
0081: import org.eclipse.jdt.core.IJavaProject;
0082: import org.eclipse.jdt.core.JavaCore;
0083: import org.eclipse.jdt.core.JavaModelException;
0084:
0085: import org.eclipse.jdt.internal.corext.util.Messages;
0086:
0087: import org.eclipse.jdt.ui.JavaUI;
0088: import org.eclipse.jdt.ui.wizards.BuildPathDialogAccess;
0089: import org.eclipse.jdt.ui.wizards.ClasspathAttributeConfiguration;
0090:
0091: import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
0092: import org.eclipse.jdt.internal.ui.IUIConstants;
0093: import org.eclipse.jdt.internal.ui.JavaPlugin;
0094: import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
0095: import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
0096: import org.eclipse.jdt.internal.ui.wizards.buildpaths.AccessRulesDialog;
0097: import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathSupport;
0098: import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElement;
0099: import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElementAttribute;
0100: import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElementSorter;
0101: import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListLabelProvider;
0102: import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPUserLibraryElement;
0103: import org.eclipse.jdt.internal.ui.wizards.buildpaths.ClasspathAttributeConfigurationDescriptors;
0104: import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
0105: import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
0106: import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
0107: import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
0108: import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
0109: import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
0110: import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
0111: import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
0112: import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
0113: import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
0114: import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
0115: import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
0116:
0117: import org.w3c.dom.Document;
0118: import org.w3c.dom.Element;
0119: import org.w3c.dom.Node;
0120: import org.w3c.dom.NodeList;
0121: import org.xml.sax.InputSource;
0122: import org.xml.sax.SAXException;
0123:
0124: public class UserLibraryPreferencePage extends PreferencePage implements
0125: IWorkbenchPreferencePage {
0126:
0127: public static final String ID = "org.eclipse.jdt.ui.preferences.UserLibraryPreferencePage"; //$NON-NLS-1$
0128: public static final String DATA_DO_CREATE = "do_create"; //$NON-NLS-1$
0129: public static final String DATA_LIBRARY_TO_SELECT = "select_library"; //$NON-NLS-1$
0130:
0131: public static class LibraryNameDialog extends StatusDialog
0132: implements IDialogFieldListener {
0133:
0134: private StringDialogField fNameField;
0135: private SelectionButtonDialogField fIsSystemField;
0136:
0137: private CPUserLibraryElement fElementToEdit;
0138: private List fExistingLibraries;
0139:
0140: public LibraryNameDialog(Shell parent,
0141: CPUserLibraryElement elementToEdit,
0142: List existingLibraries) {
0143: super (parent);
0144: if (elementToEdit == null) {
0145: setTitle(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_new_title);
0146: } else {
0147: setTitle(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_edit_title);
0148: }
0149:
0150: fElementToEdit = elementToEdit;
0151: fExistingLibraries = existingLibraries;
0152:
0153: fNameField = new StringDialogField();
0154: fNameField.setDialogFieldListener(this );
0155: fNameField
0156: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_label);
0157:
0158: fIsSystemField = new SelectionButtonDialogField(SWT.CHECK);
0159: fIsSystemField
0160: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_issystem_label);
0161:
0162: if (elementToEdit != null) {
0163: fNameField.setText(elementToEdit.getName());
0164: fIsSystemField.setSelection(elementToEdit
0165: .isSystemLibrary());
0166: } else {
0167: fNameField.setText(""); //$NON-NLS-1$
0168: fIsSystemField.setSelection(false);
0169: }
0170: }
0171:
0172: /* (non-Javadoc)
0173: * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
0174: */
0175: protected Control createDialogArea(Composite parent) {
0176: Composite composite = (Composite) super
0177: .createDialogArea(parent);
0178: LayoutUtil.doDefaultLayout(composite, new DialogField[] {
0179: fNameField, fIsSystemField }, true, SWT.DEFAULT,
0180: SWT.DEFAULT);
0181: fNameField.postSetFocusOnDialogField(parent.getDisplay());
0182:
0183: Dialog.applyDialogFont(composite);
0184:
0185: PlatformUI.getWorkbench().getHelpSystem()
0186: .setHelp(composite,
0187: IJavaHelpContextIds.CP_EDIT_USER_LIBRARY);
0188:
0189: return composite;
0190: }
0191:
0192: /* (non-Javadoc)
0193: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
0194: */
0195: public void dialogFieldChanged(DialogField field) {
0196: if (field == fNameField) {
0197: updateStatus(validateSettings());
0198: }
0199: }
0200:
0201: private IStatus validateSettings() {
0202: String name = fNameField.getText();
0203: if (name.length() == 0) {
0204: return new StatusInfo(
0205: IStatus.ERROR,
0206: PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_error_entername);
0207: }
0208: for (int i = 0; i < fExistingLibraries.size(); i++) {
0209: CPUserLibraryElement curr = (CPUserLibraryElement) fExistingLibraries
0210: .get(i);
0211: if (curr != fElementToEdit
0212: && name.equals(curr.getName())) {
0213: return new StatusInfo(
0214: IStatus.ERROR,
0215: Messages
0216: .format(
0217: PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_error_exists,
0218: name));
0219: }
0220: }
0221: IStatus status = ResourcesPlugin.getWorkspace()
0222: .validateName(name, IResource.FILE);
0223: if (status.matches(IStatus.ERROR)) {
0224: return new StatusInfo(IStatus.ERROR,
0225: "Name contains invalid characters."); //$NON-NLS-1$
0226: }
0227: return StatusInfo.OK_STATUS;
0228: }
0229:
0230: public CPUserLibraryElement getNewLibrary() {
0231: CPListElement[] entries = null;
0232: if (fElementToEdit != null) {
0233: entries = fElementToEdit.getChildren();
0234: }
0235: return new CPUserLibraryElement(fNameField.getText(),
0236: fIsSystemField.isSelected(), entries);
0237: }
0238:
0239: }
0240:
0241: public static class LoadSaveDialog extends StatusDialog implements
0242: IStringButtonAdapter, IDialogFieldListener, IListAdapter {
0243:
0244: private static final String VERSION1 = "1"; //$NON-NLS-1$ // using OS strings for archive path and source attachment
0245: private static final String CURRENT_VERSION = "2"; //$NON-NLS-1$
0246:
0247: private static final String TAG_ROOT = "eclipse-userlibraries"; //$NON-NLS-1$
0248: private static final String TAG_VERSION = "version"; //$NON-NLS-1$
0249: private static final String TAG_LIBRARY = "library"; //$NON-NLS-1$
0250: private static final String TAG_SOURCEATTACHMENT = "source"; //$NON-NLS-1$
0251: private static final String TAG_ARCHIVE_PATH = "path"; //$NON-NLS-1$
0252: private static final String TAG_ARCHIVE = "archive"; //$NON-NLS-1$
0253: private static final String TAG_SYSTEMLIBRARY = "systemlibrary"; //$NON-NLS-1$
0254: private static final String TAG_NAME = "name"; //$NON-NLS-1$
0255: private static final String TAG_JAVADOC = "javadoc"; //$NON-NLS-1$
0256: private static final String TAG_NATIVELIB_PATHS = "nativelibpaths"; //$NON-NLS-1$
0257: private static final String TAG_ACCESSRULES = "accessrules"; //$NON-NLS-1$
0258: private static final String TAG_ACCESSRULE = "accessrule"; //$NON-NLS-1$
0259: private static final String TAG_RULE_KIND = "kind"; //$NON-NLS-1$
0260: private static final String TAG_RULE_PATTERN = "pattern"; //$NON-NLS-1$
0261:
0262: private static final String PREF_LASTPATH = JavaUI.ID_PLUGIN
0263: + ".lastuserlibrary"; //$NON-NLS-1$
0264: private static final String PREF_USER_LIBRARY_LOADSAVE_SIZE = "UserLibraryLoadSaveDialog.size"; //$NON-NLS-1$
0265:
0266: private List fExistingLibraries;
0267: private IDialogSettings fSettings;
0268:
0269: private File fLastFile;
0270:
0271: private StringButtonDialogField fLocationField;
0272: private CheckedListDialogField fExportImportList;
0273: private Point fInitialSize;
0274: private final boolean fIsSave;
0275:
0276: public LoadSaveDialog(Shell shell, boolean isSave,
0277: List existingLibraries, IDialogSettings dialogSettings) {
0278: super (shell);
0279: initializeDialogUnits(shell);
0280:
0281: setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
0282:
0283: fExistingLibraries = existingLibraries;
0284: fSettings = dialogSettings;
0285: fLastFile = null;
0286: fIsSave = isSave;
0287:
0288: int defaultWidth = convertWidthInCharsToPixels(80);
0289: int defaultHeigth = convertHeightInCharsToPixels(34);
0290: String lastSize = fSettings
0291: .get(PREF_USER_LIBRARY_LOADSAVE_SIZE);
0292: if (lastSize != null) {
0293: fInitialSize = StringConverter.asPoint(lastSize,
0294: new Point(defaultWidth, defaultHeigth));
0295: } else {
0296: fInitialSize = new Point(defaultWidth, defaultHeigth);
0297: }
0298:
0299: if (isSave()) {
0300: setTitle(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_title);
0301: } else {
0302: setTitle(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_title);
0303: }
0304:
0305: fLocationField = new StringButtonDialogField(this );
0306: fLocationField
0307: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_label);
0308: fLocationField
0309: .setButtonLabel(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_button);
0310: fLocationField.setDialogFieldListener(this );
0311:
0312: String[] buttonNames = new String[] {
0313: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_selectall_button,
0314: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_deselectall_button };
0315: fExportImportList = new CheckedListDialogField(this ,
0316: buttonNames, new CPListLabelProvider());
0317: fExportImportList.setCheckAllButtonIndex(0);
0318: fExportImportList.setUncheckAllButtonIndex(1);
0319: fExportImportList
0320: .setViewerComparator(new CPListElementSorter());
0321: fExportImportList.setDialogFieldListener(this );
0322: if (isSave()) {
0323: fExportImportList
0324: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_save_label);
0325: fExportImportList.setElements(fExistingLibraries);
0326: fExportImportList.checkAll(true);
0327: } else {
0328: fExportImportList
0329: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_load_label);
0330: }
0331: String lastPath = fSettings.get(PREF_LASTPATH);
0332: if (lastPath != null) {
0333: fLocationField.setText(lastPath);
0334: } else {
0335: fLocationField.setText(""); //$NON-NLS-1$
0336: }
0337: }
0338:
0339: protected Point getInitialSize() {
0340: return fInitialSize;
0341: }
0342:
0343: private boolean isSave() {
0344: return fIsSave;
0345: }
0346:
0347: /* (non-Javadoc)
0348: * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
0349: */
0350: protected Control createDialogArea(Composite parent) {
0351: Composite composite = (Composite) super
0352: .createDialogArea(parent);
0353: DialogField[] fields;
0354: if (isSave()) {
0355: fields = new DialogField[] { fExportImportList,
0356: fLocationField };
0357: } else {
0358: fields = new DialogField[] { fLocationField,
0359: fExportImportList };
0360: }
0361: LayoutUtil.doDefaultLayout(composite, fields, true,
0362: SWT.DEFAULT, SWT.DEFAULT);
0363: fExportImportList.getListControl(null).setLayoutData(
0364: new GridData(GridData.FILL_BOTH));
0365:
0366: fLocationField.postSetFocusOnDialogField(parent
0367: .getDisplay());
0368:
0369: Dialog.applyDialogFont(composite);
0370:
0371: if (isSave()) {
0372: PlatformUI.getWorkbench().getHelpSystem().setHelp(
0373: composite,
0374: IJavaHelpContextIds.CP_EXPORT_USER_LIBRARY);
0375: } else {
0376: PlatformUI.getWorkbench().getHelpSystem().setHelp(
0377: composite,
0378: IJavaHelpContextIds.CP_IMPORT_USER_LIBRARY);
0379: }
0380:
0381: return composite;
0382: }
0383:
0384: /* (non-Javadoc)
0385: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
0386: */
0387: public void changeControlPressed(DialogField field) {
0388: String label = isSave() ? PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_filedialog_save_title
0389: : PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_filedialog_load_title;
0390: FileDialog dialog = new FileDialog(getShell(),
0391: isSave() ? SWT.SAVE : SWT.OPEN);
0392: dialog.setText(label);
0393: dialog.setFilterExtensions(new String[] {
0394: "*.userlibraries", "*.*" }); //$NON-NLS-1$ //$NON-NLS-2$
0395: String lastPath = fLocationField.getText();
0396: if (lastPath.length() == 0 || !new File(lastPath).exists()) {
0397: lastPath = fSettings.get(PREF_LASTPATH);
0398: }
0399: if (lastPath != null) {
0400: dialog.setFileName(lastPath);
0401: }
0402: String fileName = dialog.open();
0403: if (fileName != null) {
0404: fSettings.put(PREF_LASTPATH, fileName);
0405: fLocationField.setText(fileName);
0406: }
0407: }
0408:
0409: private IStatus updateShownLibraries(IStatus status) {
0410: if (!status.isOK()) {
0411: fExportImportList.removeAllElements();
0412: fExportImportList.setEnabled(false);
0413: fLastFile = null;
0414: } else {
0415: File file = new File(fLocationField.getText());
0416: if (!file.equals(fLastFile)) {
0417: fLastFile = file;
0418: try {
0419: List elements = loadLibraries(file);
0420: fExportImportList.setElements(elements);
0421: fExportImportList.checkAll(true);
0422: fExportImportList.setEnabled(true);
0423: if (elements.isEmpty()) {
0424: return new StatusInfo(
0425: IStatus.ERROR,
0426: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_error_empty);
0427: }
0428: } catch (IOException e) {
0429: fExportImportList.removeAllElements();
0430: fExportImportList.setEnabled(false);
0431: return new StatusInfo(
0432: IStatus.ERROR,
0433: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_error_invalidfile);
0434: }
0435: }
0436: }
0437: return status;
0438: }
0439:
0440: /* (non-Javadoc)
0441: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
0442: */
0443: public void dialogFieldChanged(DialogField field) {
0444: if (field == fLocationField) {
0445: IStatus status = validateSettings();
0446: if (!isSave()) {
0447: status = updateShownLibraries(status);
0448: }
0449: updateStatus(status);
0450: } else if (field == fExportImportList) {
0451: updateStatus(validateSettings());
0452: }
0453: }
0454:
0455: /* (non-Javadoc)
0456: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField, int)
0457: */
0458: public void customButtonPressed(ListDialogField field, int index) {
0459: }
0460:
0461: /* (non-Javadoc)
0462: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField)
0463: */
0464: public void selectionChanged(ListDialogField field) {
0465: }
0466:
0467: /* (non-Javadoc)
0468: * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter#doubleClicked(org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField)
0469: */
0470: public void doubleClicked(ListDialogField field) {
0471: List selectedElements = fExportImportList
0472: .getSelectedElements();
0473: if (selectedElements.size() == 1) {
0474: Object elem = selectedElements.get(0);
0475: fExportImportList.setChecked(elem, !fExportImportList
0476: .isChecked(elem));
0477: }
0478: }
0479:
0480: /* (non-Javadoc)
0481: * @see org.eclipse.jface.dialogs.Dialog#okPressed()
0482: */
0483: protected void okPressed() {
0484: if (isSave()) {
0485: final File file = new File(fLocationField.getText());
0486: if (file.exists()) {
0487: String title = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_overwrite_title;
0488: String message = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_overwrite_message;
0489: if (!MessageDialog.openQuestion(getShell(), title,
0490: message)) {
0491: return;
0492: }
0493: }
0494: try {
0495: String encoding = "UTF-8"; //$NON-NLS-1$
0496: IPath filePath = Path.fromOSString(file
0497: .getCanonicalPath());
0498: final IPath workspacePath = ResourcesPlugin
0499: .getWorkspace().getRoot().getLocation();
0500: if (filePath.matchingFirstSegments(workspacePath) == workspacePath
0501: .segmentCount()) {
0502: IPath path = filePath
0503: .removeFirstSegments(workspacePath
0504: .segmentCount());
0505: path = path.makeRelative();
0506: final IFile result = ResourcesPlugin
0507: .getWorkspace().getRoot().getFile(path);
0508: try {
0509: encoding = result.getCharset(true);
0510: } catch (CoreException exception) {
0511: JavaPlugin.log(exception);
0512: }
0513: }
0514: final List elements = fExportImportList
0515: .getCheckedElements();
0516: final String charset = encoding;
0517: IRunnableContext context = PlatformUI
0518: .getWorkbench().getProgressService();
0519: try {
0520: context.run(true, true,
0521: new IRunnableWithProgress() {
0522: public void run(
0523: IProgressMonitor monitor)
0524: throws InvocationTargetException,
0525: InterruptedException {
0526: try {
0527: saveLibraries(elements,
0528: file, charset,
0529: monitor);
0530: } catch (IOException e) {
0531: throw new InvocationTargetException(
0532: e);
0533: }
0534: }
0535: });
0536: fSettings.put(PREF_LASTPATH, file.getPath());
0537: } catch (InvocationTargetException e) {
0538: String errorTitle = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_title;
0539: String errorMessage = Messages
0540: .format(
0541: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_message,
0542: e.getMessage());
0543: ExceptionHandler.handle(e, getShell(),
0544: errorTitle, errorMessage);
0545: return;
0546: } catch (InterruptedException e) {
0547: // cancelled
0548: return;
0549: }
0550: String savedTitle = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_ok_title;
0551: String savedMessage = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_ok_message;
0552: MessageDialog.openInformation(getShell(),
0553: savedTitle, savedMessage);
0554: } catch (IOException exception) {
0555: JavaPlugin.log(exception);
0556: }
0557: } else {
0558: HashSet map = new HashSet(fExistingLibraries.size());
0559: for (int k = 0; k < fExistingLibraries.size(); k++) {
0560: CPUserLibraryElement elem = (CPUserLibraryElement) fExistingLibraries
0561: .get(k);
0562: map.add(elem.getName());
0563: }
0564: int nReplaced = 0;
0565: List elements = getLoadedLibraries();
0566: for (int i = 0; i < elements.size(); i++) {
0567: CPUserLibraryElement curr = (CPUserLibraryElement) elements
0568: .get(i);
0569: if (map.contains(curr.getName())) {
0570: nReplaced++;
0571: }
0572: }
0573: if (nReplaced > 0) {
0574: String replaceTitle = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_title;
0575: String replaceMessage;
0576: if (nReplaced == 1) {
0577: replaceMessage = PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_message;
0578: } else {
0579: replaceMessage = Messages
0580: .format(
0581: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_multiple_message,
0582: String.valueOf(nReplaced));
0583: }
0584: if (!MessageDialog.openConfirm(getShell(),
0585: replaceTitle, replaceMessage)) {
0586: return;
0587: }
0588: }
0589: }
0590: super .okPressed();
0591: }
0592:
0593: /* (non-Javadoc)
0594: * @see org.eclipse.jface.dialogs.Dialog#close()
0595: */
0596: public boolean close() {
0597: Point point = getShell().getSize();
0598: fSettings.put(PREF_USER_LIBRARY_LOADSAVE_SIZE,
0599: StringConverter.asString(point));
0600: return super .close();
0601: }
0602:
0603: private IStatus validateSettings() {
0604: String name = fLocationField.getText();
0605: fLastFile = null;
0606: if (isSave()) {
0607: if (name.length() == 0) {
0608: return new StatusInfo(
0609: IStatus.ERROR,
0610: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_save_enterlocation);
0611: }
0612: File file = new File(name);
0613: if (file.isDirectory()) {
0614: return new StatusInfo(
0615: IStatus.ERROR,
0616: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_save_invalid);
0617: }
0618: if (fExportImportList.getCheckedSize() == 0) {
0619: return new StatusInfo(
0620: IStatus.ERROR,
0621: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_error_save_nothingselected);
0622: }
0623: fLastFile = file;
0624: } else {
0625: if (name.length() == 0) {
0626: return new StatusInfo(
0627: IStatus.ERROR,
0628: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_load_enterlocation);
0629: }
0630: if (!new File(name).isFile()) {
0631: return new StatusInfo(
0632: IStatus.ERROR,
0633: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_load_invalid);
0634: }
0635: if (fExportImportList.getSize() > 0
0636: && fExportImportList.getCheckedSize() == 0) {
0637: return new StatusInfo(
0638: IStatus.ERROR,
0639: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_error_load_nothingselected);
0640: }
0641: }
0642: return new StatusInfo();
0643: }
0644:
0645: protected static void saveLibraries(List libraries, File file,
0646: String encoding, IProgressMonitor monitor)
0647: throws IOException {
0648: OutputStream stream = new FileOutputStream(file);
0649: try {
0650: DocumentBuilder docBuilder = null;
0651: DocumentBuilderFactory factory = DocumentBuilderFactory
0652: .newInstance();
0653: factory.setValidating(false);
0654: docBuilder = factory.newDocumentBuilder();
0655: Document document = docBuilder.newDocument();
0656:
0657: // Create the document
0658: Element rootElement = document.createElement(TAG_ROOT);
0659: document.appendChild(rootElement);
0660:
0661: rootElement.setAttribute(TAG_VERSION, CURRENT_VERSION);
0662:
0663: for (int i = 0; i < libraries.size(); i++) {
0664: Element libraryElement = document
0665: .createElement(TAG_LIBRARY);
0666: rootElement.appendChild(libraryElement);
0667:
0668: CPUserLibraryElement curr = (CPUserLibraryElement) libraries
0669: .get(i);
0670: libraryElement.setAttribute(TAG_NAME, curr
0671: .getName());
0672: libraryElement.setAttribute(TAG_SYSTEMLIBRARY,
0673: String.valueOf(curr.isSystemLibrary()));
0674:
0675: CPListElement[] children = curr.getChildren();
0676: for (int k = 0; k < children.length; k++) {
0677: CPListElement child = children[k];
0678:
0679: Element childElement = document
0680: .createElement(TAG_ARCHIVE);
0681: libraryElement.appendChild(childElement);
0682:
0683: childElement.setAttribute(TAG_ARCHIVE_PATH,
0684: child.getPath().toPortableString());
0685: IPath sourceAttachment = (IPath) child
0686: .getAttribute(CPListElement.SOURCEATTACHMENT);
0687: if (sourceAttachment != null) {
0688: childElement
0689: .setAttribute(TAG_SOURCEATTACHMENT,
0690: sourceAttachment
0691: .toPortableString());
0692:
0693: }
0694: String javadocLocation = (String) child
0695: .getAttribute(CPListElement.JAVADOC);
0696: if (javadocLocation != null) {
0697: childElement.setAttribute(TAG_JAVADOC,
0698: javadocLocation);
0699: }
0700: String nativeLibPath = (String) child
0701: .getAttribute(CPListElement.NATIVE_LIB_PATH);
0702: if (nativeLibPath != null) {
0703: childElement.setAttribute(
0704: TAG_NATIVELIB_PATHS, nativeLibPath);
0705: }
0706: IAccessRule[] accessRules = (IAccessRule[]) child
0707: .getAttribute(CPListElement.ACCESSRULES);
0708: if (accessRules != null
0709: && accessRules.length > 0) {
0710: Element rulesElement = document
0711: .createElement(TAG_ACCESSRULES);
0712: childElement.appendChild(rulesElement);
0713: for (int n = 0; n < accessRules.length; n++) {
0714: IAccessRule rule = accessRules[n];
0715: Element ruleElement = document
0716: .createElement(TAG_ACCESSRULE);
0717: rulesElement.appendChild(ruleElement);
0718: ruleElement.setAttribute(TAG_RULE_KIND,
0719: String.valueOf(rule.getKind()));
0720: ruleElement.setAttribute(
0721: TAG_RULE_PATTERN, rule
0722: .getPattern()
0723: .toPortableString());
0724: }
0725: }
0726: }
0727: }
0728:
0729: // Write the document to the stream
0730: Transformer transformer = TransformerFactory
0731: .newInstance().newTransformer();
0732: transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
0733: transformer.setOutputProperty(OutputKeys.ENCODING,
0734: encoding);
0735: transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
0736: transformer
0737: .setOutputProperty(
0738: "{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
0739:
0740: DOMSource source = new DOMSource(document);
0741: StreamResult result = new StreamResult(stream);
0742: transformer.transform(source, result);
0743: } catch (ParserConfigurationException e) {
0744: throw new IOException(e.getMessage());
0745: } catch (TransformerException e) {
0746: throw new IOException(e.getMessage());
0747: } finally {
0748: try {
0749: stream.close();
0750: } catch (IOException e) {
0751: // ignore
0752: }
0753: if (monitor != null) {
0754: monitor.done();
0755: }
0756: }
0757: }
0758:
0759: private static List loadLibraries(File file) throws IOException {
0760: InputStream stream = new FileInputStream(file);
0761: Element cpElement;
0762: try {
0763: DocumentBuilder parser = DocumentBuilderFactory
0764: .newInstance().newDocumentBuilder();
0765: cpElement = parser.parse(new InputSource(stream))
0766: .getDocumentElement();
0767: } catch (SAXException e) {
0768: throw new IOException(
0769: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
0770: } catch (ParserConfigurationException e) {
0771: throw new IOException(
0772: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
0773: } finally {
0774: stream.close();
0775: }
0776:
0777: if (!cpElement.getNodeName().equalsIgnoreCase(TAG_ROOT)) {
0778: throw new IOException(
0779: PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
0780: }
0781:
0782: String version = cpElement.getAttribute(TAG_VERSION);
0783:
0784: NodeList libList = cpElement
0785: .getElementsByTagName(TAG_LIBRARY);
0786: int length = libList.getLength();
0787:
0788: ArrayList result = new ArrayList(length);
0789: for (int i = 0; i < length; i++) {
0790: Node lib = libList.item(i);
0791: if (!(lib instanceof Element)) {
0792: continue;
0793: }
0794: Element libElement = (Element) lib;
0795: String name = libElement.getAttribute(TAG_NAME);
0796: boolean isSystem = Boolean.valueOf(
0797: libElement.getAttribute(TAG_SYSTEMLIBRARY))
0798: .booleanValue();
0799:
0800: CPUserLibraryElement newLibrary = new CPUserLibraryElement(
0801: name, isSystem, null);
0802: result.add(newLibrary);
0803:
0804: NodeList archiveList = libElement
0805: .getElementsByTagName(TAG_ARCHIVE);
0806: for (int k = 0; k < archiveList.getLength(); k++) {
0807: Node archiveNode = archiveList.item(k);
0808: if (!(archiveNode instanceof Element)) {
0809: continue;
0810: }
0811: Element archiveElement = (Element) archiveNode;
0812:
0813: String pathString = archiveElement
0814: .getAttribute(TAG_ARCHIVE_PATH);
0815: IPath path = version.equals(VERSION1) ? Path
0816: .fromOSString(pathString) : Path
0817: .fromPortableString(pathString);
0818: path = path.makeAbsolute(); // only necessary for manually edited files: bug 202373
0819: CPListElement newArchive = new CPListElement(
0820: newLibrary, null,
0821: IClasspathEntry.CPE_LIBRARY, path, null);
0822: newLibrary.add(newArchive);
0823:
0824: if (archiveElement
0825: .hasAttribute(TAG_SOURCEATTACHMENT)) {
0826: String sourceAttachString = archiveElement
0827: .getAttribute(TAG_SOURCEATTACHMENT);
0828: IPath sourceAttach = version.equals(VERSION1) ? Path
0829: .fromOSString(sourceAttachString)
0830: : Path
0831: .fromPortableString(sourceAttachString);
0832: newArchive.setAttribute(
0833: CPListElement.SOURCEATTACHMENT,
0834: sourceAttach);
0835: }
0836: if (archiveElement.hasAttribute(TAG_JAVADOC)) {
0837: String javadoc = archiveElement
0838: .getAttribute(TAG_JAVADOC);
0839: newArchive.setAttribute(CPListElement.JAVADOC,
0840: javadoc);
0841: }
0842: if (archiveElement
0843: .hasAttribute(TAG_NATIVELIB_PATHS)) {
0844: String nativeLibPath = archiveElement
0845: .getAttribute(TAG_NATIVELIB_PATHS);
0846: newArchive.setAttribute(
0847: CPListElement.NATIVE_LIB_PATH,
0848: nativeLibPath);
0849: }
0850: NodeList rulesParentNodes = archiveElement
0851: .getElementsByTagName(TAG_ACCESSRULES);
0852: if (rulesParentNodes.getLength() > 0
0853: && rulesParentNodes.item(0) instanceof Element) {
0854: Element ruleParentElement = (Element) rulesParentNodes
0855: .item(0); // take first, ignore others
0856: NodeList ruleElements = ruleParentElement
0857: .getElementsByTagName(TAG_ACCESSRULE);
0858: int nRuleElements = ruleElements.getLength();
0859: if (nRuleElements > 0) {
0860: ArrayList resultingRules = new ArrayList(
0861: nRuleElements);
0862: for (int n = 0; n < nRuleElements; n++) {
0863: Node node = ruleElements.item(n);
0864: if (node instanceof Element) {
0865: Element ruleElement = (Element) node;
0866: try {
0867: int kind = Integer
0868: .parseInt(ruleElement
0869: .getAttribute(TAG_RULE_KIND));
0870: IPath pattern = Path
0871: .fromPortableString(ruleElement
0872: .getAttribute(TAG_RULE_PATTERN));
0873: resultingRules.add(JavaCore
0874: .newAccessRule(pattern,
0875: kind));
0876: } catch (NumberFormatException e) {
0877: // ignore
0878: }
0879: }
0880: }
0881: newArchive
0882: .setAttribute(
0883: CPListElement.ACCESSRULES,
0884: resultingRules
0885: .toArray(new IAccessRule[resultingRules
0886: .size()]));
0887: }
0888: }
0889: }
0890: }
0891: return result;
0892: }
0893:
0894: public List getLoadedLibraries() {
0895: return fExportImportList.getCheckedElements();
0896: }
0897: }
0898:
0899: private IDialogSettings fDialogSettings;
0900: private TreeListDialogField fLibraryList;
0901: private IJavaProject fDummyProject;
0902: private ClasspathAttributeConfigurationDescriptors fAttributeDescriptors;
0903:
0904: private static final int IDX_NEW = 0;
0905: private static final int IDX_EDIT = 1;
0906: private static final int IDX_ADD = 2;
0907: private static final int IDX_REMOVE = 3;
0908: private static final int IDX_UP = 5;
0909: private static final int IDX_DOWN = 6;
0910: private static final int IDX_LOAD = 8;
0911: private static final int IDX_SAVE = 9;
0912:
0913: /**
0914: * Constructor for ClasspathVariablesPreferencePage
0915: */
0916: public UserLibraryPreferencePage() {
0917: setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
0918: fDummyProject = createPlaceholderProject();
0919:
0920: fAttributeDescriptors = JavaPlugin.getDefault()
0921: .getClasspathAttributeConfigurationDescriptors();
0922:
0923: // title only used when page is shown programatically
0924: setTitle(PreferencesMessages.UserLibraryPreferencePage_title);
0925: setDescription(PreferencesMessages.UserLibraryPreferencePage_description);
0926: noDefaultAndApplyButton();
0927:
0928: fDialogSettings = JavaPlugin.getDefault().getDialogSettings();
0929:
0930: UserLibraryAdapter adapter = new UserLibraryAdapter();
0931: String[] buttonLabels = new String[] {
0932: PreferencesMessages.UserLibraryPreferencePage_libraries_new_button,
0933: PreferencesMessages.UserLibraryPreferencePage_libraries_edit_button,
0934: PreferencesMessages.UserLibraryPreferencePage_libraries_addjar_button,
0935: PreferencesMessages.UserLibraryPreferencePage_libraries_remove_button,
0936: null,
0937: PreferencesMessages.UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_up_button,
0938: PreferencesMessages.UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_down_button,
0939: null,
0940:
0941: PreferencesMessages.UserLibraryPreferencePage_libraries_load_button,
0942: PreferencesMessages.UserLibraryPreferencePage_libraries_save_button };
0943:
0944: fLibraryList = new TreeListDialogField(adapter, buttonLabels,
0945: new CPListLabelProvider());
0946: fLibraryList
0947: .setLabelText(PreferencesMessages.UserLibraryPreferencePage_libraries_label);
0948:
0949: String[] names = JavaCore.getUserLibraryNames();
0950: ArrayList elements = new ArrayList();
0951:
0952: for (int i = 0; i < names.length; i++) {
0953: IPath path = new Path(JavaCore.USER_LIBRARY_CONTAINER_ID)
0954: .append(names[i]);
0955: try {
0956: IClasspathContainer container = JavaCore
0957: .getClasspathContainer(path, fDummyProject);
0958: elements.add(new CPUserLibraryElement(names[i],
0959: container, fDummyProject));
0960: } catch (JavaModelException e) {
0961: JavaPlugin.log(e);
0962: // ignore
0963: }
0964: }
0965: fLibraryList.setElements(elements);
0966: fLibraryList.setViewerComparator(new CPListElementSorter());
0967:
0968: doSelectionChanged(fLibraryList); //update button enable state
0969: }
0970:
0971: private static IJavaProject createPlaceholderProject() {
0972: String name = "####internal"; //$NON-NLS-1$
0973: IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
0974: while (true) {
0975: IProject project = root.getProject(name);
0976: if (!project.exists()) {
0977: return JavaCore.create(project);
0978: }
0979: name += '1';
0980: }
0981: }
0982:
0983: /* (non-Javadoc)
0984: * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
0985: */
0986: public void applyData(Object data) {
0987: if (data instanceof Map) {
0988: Map map = (Map) data;
0989: Object selectedLibrary = map.get(DATA_LIBRARY_TO_SELECT);
0990: boolean createIfNotExists = Boolean.TRUE.equals(map
0991: .get(DATA_DO_CREATE));
0992: if (selectedLibrary instanceof String) {
0993: int nElements = fLibraryList.getSize();
0994: for (int i = 0; i < nElements; i++) {
0995: CPUserLibraryElement curr = (CPUserLibraryElement) fLibraryList
0996: .getElement(i);
0997: if (curr.getName().equals(selectedLibrary)) {
0998: fLibraryList
0999: .selectElements(new StructuredSelection(
1000: curr));
1001: fLibraryList.expandElement(curr, 1);
1002: break;
1003: }
1004: }
1005: if (createIfNotExists) {
1006: CPUserLibraryElement elem = new CPUserLibraryElement(
1007: (String) selectedLibrary, null,
1008: createPlaceholderProject());
1009: fLibraryList.addElement(elem);
1010: fLibraryList
1011: .selectElements(new StructuredSelection(
1012: elem));
1013: }
1014: }
1015: }
1016: }
1017:
1018: /*
1019: * (non-Javadoc)
1020: * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
1021: */
1022: public void createControl(Composite parent) {
1023: super .createControl(parent);
1024: PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
1025: IJavaHelpContextIds.CP_USERLIBRARIES_PREFERENCE_PAGE);
1026: }
1027:
1028: /*
1029: * @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
1030: */
1031: protected Control createContents(Composite parent) {
1032: Composite composite = new Composite(parent, SWT.NONE);
1033: composite.setFont(parent.getFont());
1034: LayoutUtil.doDefaultLayout(composite,
1035: new DialogField[] { fLibraryList }, true);
1036: LayoutUtil.setHorizontalGrabbing(fLibraryList
1037: .getTreeControl(null));
1038: Dialog.applyDialogFont(composite);
1039: return composite;
1040: }
1041:
1042: /*
1043: * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
1044: */
1045: public void init(IWorkbench workbench) {
1046: }
1047:
1048: /*
1049: * @see PreferencePage#performDefaults()
1050: */
1051: protected void performDefaults() {
1052: super .performDefaults();
1053: }
1054:
1055: /*
1056: * @see PreferencePage#performOk()
1057: */
1058: public boolean performOk() {
1059: try {
1060: PlatformUI.getWorkbench().getProgressService().run(true,
1061: true, new IRunnableWithProgress() {
1062: public void run(IProgressMonitor monitor)
1063: throws InvocationTargetException {
1064: try {
1065: if (monitor != null) {
1066: monitor = new NullProgressMonitor();
1067: }
1068:
1069: updateUserLibararies(monitor);
1070: } catch (CoreException e) {
1071: throw new InvocationTargetException(e);
1072: } finally {
1073: monitor.done();
1074: }
1075: }
1076: });
1077: } catch (InterruptedException e) {
1078: // cancelled by user
1079: } catch (InvocationTargetException e) {
1080: String title = PreferencesMessages.UserLibraryPreferencePage_config_error_title;
1081: String message = PreferencesMessages.UserLibraryPreferencePage_config_error_message;
1082: ExceptionHandler.handle(e, getShell(), title, message);
1083: }
1084: return true;
1085: }
1086:
1087: private void updateUserLibararies(IProgressMonitor monitor)
1088: throws CoreException {
1089: List list = fLibraryList.getElements();
1090: HashSet oldNames = new HashSet(Arrays.asList(JavaCore
1091: .getUserLibraryNames()));
1092: int nExisting = list.size();
1093:
1094: HashSet newEntries = new HashSet(list.size());
1095: for (int i = 0; i < nExisting; i++) {
1096: CPUserLibraryElement element = (CPUserLibraryElement) list
1097: .get(i);
1098: boolean contained = oldNames.remove(element.getName());
1099: if (!contained) {
1100: newEntries.add(element);
1101: }
1102: }
1103:
1104: int len = nExisting + oldNames.size();
1105: monitor
1106: .beginTask(
1107: PreferencesMessages.UserLibraryPreferencePage_operation,
1108: len);
1109: MultiStatus multiStatus = new MultiStatus(
1110: JavaUI.ID_PLUGIN,
1111: IStatus.OK,
1112: PreferencesMessages.UserLibraryPreferencePage_operation_error,
1113: null);
1114:
1115: ClasspathContainerInitializer initializer = JavaCore
1116: .getClasspathContainerInitializer(JavaCore.USER_LIBRARY_CONTAINER_ID);
1117: IJavaProject jproject = fDummyProject;
1118:
1119: for (int i = 0; i < nExisting; i++) {
1120: CPUserLibraryElement element = (CPUserLibraryElement) list
1121: .get(i);
1122: IPath path = element.getPath();
1123: if (newEntries.contains(element)
1124: || element.hasChanges(JavaCore
1125: .getClasspathContainer(path, jproject))) {
1126: IClasspathContainer updatedContainer = element
1127: .getUpdatedContainer();
1128: try {
1129: initializer.requestClasspathContainerUpdate(path,
1130: jproject, updatedContainer);
1131: } catch (CoreException e) {
1132: multiStatus.add(e.getStatus());
1133: }
1134: }
1135: monitor.worked(1);
1136: }
1137:
1138: Iterator iter = oldNames.iterator();
1139: while (iter.hasNext()) {
1140: String name = (String) iter.next();
1141:
1142: IPath path = new Path(JavaCore.USER_LIBRARY_CONTAINER_ID)
1143: .append(name);
1144: try {
1145: initializer.requestClasspathContainerUpdate(path,
1146: jproject, null);
1147: } catch (CoreException e) {
1148: multiStatus.add(e.getStatus());
1149: }
1150: monitor.worked(1);
1151: }
1152:
1153: if (!multiStatus.isOK()) {
1154: throw new CoreException(multiStatus);
1155: }
1156: }
1157:
1158: private CPUserLibraryElement getSingleSelectedLibrary(List selected) {
1159: if (selected.size() == 1
1160: && selected.get(0) instanceof CPUserLibraryElement) {
1161: return (CPUserLibraryElement) selected.get(0);
1162: }
1163: return null;
1164: }
1165:
1166: private void editAttributeEntry(CPListElementAttribute elem) {
1167: String key = elem.getKey();
1168: CPListElement selElement = elem.getParent();
1169: if (key.equals(CPListElement.SOURCEATTACHMENT)) {
1170: IClasspathEntry result = BuildPathDialogAccess
1171: .configureSourceAttachment(getShell(), selElement
1172: .getClasspathEntry());
1173: if (result != null) {
1174: selElement.setAttribute(CPListElement.SOURCEATTACHMENT,
1175: result.getSourceAttachmentPath());
1176: fLibraryList.refresh(elem);
1177: fLibraryList.update(selElement);
1178: }
1179: } else if (key.equals(CPListElement.ACCESSRULES)) {
1180: AccessRulesDialog dialog = new AccessRulesDialog(
1181: getShell(), selElement, null, false);
1182: if (dialog.open() == Window.OK) {
1183: selElement.setAttribute(CPListElement.ACCESSRULES,
1184: dialog.getAccessRules());
1185: fLibraryList.refresh(elem);
1186: fLibraryList.expandElement(elem, 2);
1187: }
1188: } else if (!elem.isBuiltIn()) {
1189: ClasspathAttributeConfiguration config = fAttributeDescriptors
1190: .get(key);
1191: if (config != null) {
1192: IClasspathAttribute result = config.performEdit(
1193: getShell(), elem.getClasspathAttributeAccess());
1194: if (result != null) {
1195: elem.setValue(result.getValue());
1196: fLibraryList.refresh(elem);
1197: }
1198: }
1199: }
1200: }
1201:
1202: protected void doSelectionChanged(TreeListDialogField field) {
1203: List list = field.getSelectedElements();
1204: field.enableButton(IDX_REMOVE, canRemove(list));
1205: field.enableButton(IDX_EDIT, canEdit(list));
1206: field.enableButton(IDX_ADD, canAdd(list));
1207: field.enableButton(IDX_UP, canMoveUp(list));
1208: field.enableButton(IDX_DOWN, canMoveDown(list));
1209: field.enableButton(IDX_SAVE, field.getSize() > 0);
1210: }
1211:
1212: protected void doCustomButtonPressed(TreeListDialogField field,
1213: int index) {
1214: if (index == IDX_NEW) {
1215: editUserLibraryElement(null);
1216: } else if (index == IDX_ADD) {
1217: doAdd(field.getSelectedElements());
1218: } else if (index == IDX_REMOVE) {
1219: doRemove(field.getSelectedElements());
1220: } else if (index == IDX_EDIT) {
1221: doEdit(field.getSelectedElements());
1222: } else if (index == IDX_SAVE) {
1223: doSave();
1224: } else if (index == IDX_LOAD) {
1225: doLoad();
1226: } else if (index == IDX_UP) {
1227: doMoveUp(field.getSelectedElements());
1228: } else if (index == IDX_DOWN) {
1229: doMoveDown(field.getSelectedElements());
1230: }
1231: }
1232:
1233: protected void doDoubleClicked(TreeListDialogField field) {
1234: List selected = field.getSelectedElements();
1235: if (canEdit(selected)) {
1236: doEdit(field.getSelectedElements());
1237: }
1238: }
1239:
1240: protected void doKeyPressed(TreeListDialogField field,
1241: KeyEvent event) {
1242: if (event.character == SWT.DEL && event.stateMask == 0) {
1243: List selection = field.getSelectedElements();
1244: if (canRemove(selection)) {
1245: doRemove(selection);
1246: }
1247: }
1248: }
1249:
1250: private void doEdit(List selected) {
1251: if (selected.size() == 1) {
1252: Object curr = selected.get(0);
1253: if (curr instanceof CPListElementAttribute) {
1254: editAttributeEntry((CPListElementAttribute) curr);
1255: } else if (curr instanceof CPUserLibraryElement) {
1256: editUserLibraryElement((CPUserLibraryElement) curr);
1257: } else if (curr instanceof CPListElement) {
1258: CPListElement elem = (CPListElement) curr;
1259: editArchiveElement(elem, (CPUserLibraryElement) elem
1260: .getParentContainer());
1261: }
1262: doSelectionChanged(fLibraryList);
1263: }
1264: }
1265:
1266: private void editUserLibraryElement(CPUserLibraryElement element) {
1267: LibraryNameDialog dialog = new LibraryNameDialog(getShell(),
1268: element, fLibraryList.getElements());
1269: if (dialog.open() == Window.OK) {
1270: CPUserLibraryElement newLibrary = dialog.getNewLibrary();
1271: if (element != null) {
1272: fLibraryList.replaceElement(element, newLibrary);
1273: } else {
1274: fLibraryList.addElement(newLibrary);
1275: }
1276: fLibraryList.expandElement(newLibrary,
1277: AbstractTreeViewer.ALL_LEVELS);
1278: fLibraryList.selectElements(new StructuredSelection(
1279: newLibrary));
1280: }
1281: }
1282:
1283: private void editArchiveElement(CPListElement existingElement,
1284: CPUserLibraryElement parent) {
1285: CPListElement[] elements = openExtJarFileDialog(
1286: existingElement, parent);
1287: if (elements != null) {
1288: for (int i = 0; i < elements.length; i++) {
1289: if (existingElement != null) {
1290: parent.replace(existingElement, elements[i]);
1291: } else {
1292: parent.add(elements[i]);
1293: }
1294: }
1295: fLibraryList.refresh(parent);
1296: fLibraryList.selectElements(new StructuredSelection(Arrays
1297: .asList(elements)));
1298: fLibraryList.expandElement(parent, 2);
1299: }
1300: }
1301:
1302: private void doRemove(List selected) {
1303: Object selectionAfter = null;
1304: for (int i = 0; i < selected.size(); i++) {
1305: Object curr = selected.get(i);
1306: if (curr instanceof CPUserLibraryElement) {
1307: fLibraryList.removeElement(curr);
1308: } else if (curr instanceof CPListElement) {
1309: Object parent = ((CPListElement) curr)
1310: .getParentContainer();
1311: if (parent instanceof CPUserLibraryElement) {
1312: CPUserLibraryElement elem = (CPUserLibraryElement) parent;
1313: elem.remove((CPListElement) curr);
1314: fLibraryList.refresh(elem);
1315: selectionAfter = parent;
1316: }
1317: } else if (curr instanceof CPListElementAttribute) {
1318: CPListElementAttribute attrib = (CPListElementAttribute) curr;
1319: if (attrib.isBuiltIn()) {
1320: Object value = null;
1321: String key = attrib.getKey();
1322: if (key.equals(CPListElement.ACCESSRULES)) {
1323: value = new IAccessRule[0];
1324: }
1325: attrib.getParent().setAttribute(key, value);
1326: fLibraryList.refresh(attrib);
1327: } else {
1328: ClasspathAttributeConfiguration config = fAttributeDescriptors
1329: .get(attrib.getKey());
1330: if (config != null) {
1331: IClasspathAttribute result = config
1332: .performRemove(attrib
1333: .getClasspathAttributeAccess());
1334: if (result != null) {
1335: attrib.setValue(result.getValue());
1336: fLibraryList.refresh(attrib);
1337: }
1338: }
1339: }
1340: }
1341: }
1342: if (fLibraryList.getSelectedElements().isEmpty()) {
1343: if (selectionAfter != null) {
1344: fLibraryList.selectElements(new StructuredSelection(
1345: selectionAfter));
1346: } else {
1347: fLibraryList.selectFirstElement();
1348: }
1349: } else {
1350: doSelectionChanged(fLibraryList);
1351: }
1352: }
1353:
1354: private void doAdd(List list) {
1355: if (canAdd(list)) {
1356: CPUserLibraryElement element = getSingleSelectedLibrary(list);
1357: editArchiveElement(null, element);
1358: }
1359: }
1360:
1361: private void doLoad() {
1362: List existing = fLibraryList.getElements();
1363: LoadSaveDialog dialog = new LoadSaveDialog(getShell(), false,
1364: existing, fDialogSettings);
1365: if (dialog.open() == Window.OK) {
1366: HashMap map = new HashMap(existing.size());
1367: for (int k = 0; k < existing.size(); k++) {
1368: CPUserLibraryElement elem = (CPUserLibraryElement) existing
1369: .get(k);
1370: map.put(elem.getName(), elem);
1371: }
1372:
1373: List list = dialog.getLoadedLibraries();
1374: for (int i = 0; i < list.size(); i++) {
1375: CPUserLibraryElement elem = (CPUserLibraryElement) list
1376: .get(i);
1377: CPUserLibraryElement found = (CPUserLibraryElement) map
1378: .get(elem.getName());
1379: if (found == null) {
1380: existing.add(elem);
1381: map.put(elem.getName(), elem);
1382: } else {
1383: existing.set(existing.indexOf(found), elem); // replace
1384: }
1385: }
1386: fLibraryList.setElements(existing);
1387: fLibraryList.selectElements(new StructuredSelection(list));
1388: }
1389: }
1390:
1391: private void doSave() {
1392: LoadSaveDialog dialog = new LoadSaveDialog(getShell(), true,
1393: fLibraryList.getElements(), fDialogSettings);
1394: dialog.open();
1395: }
1396:
1397: private boolean canAdd(List list) {
1398: return getSingleSelectedLibrary(list) != null;
1399: }
1400:
1401: private boolean canEdit(List list) {
1402: if (list.size() != 1)
1403: return false;
1404:
1405: Object firstElement = list.get(0);
1406: if (firstElement instanceof IAccessRule)
1407: return false;
1408: if (firstElement instanceof CPListElementAttribute) {
1409: CPListElementAttribute attrib = (CPListElementAttribute) firstElement;
1410: if (!attrib.isBuiltIn()) {
1411: ClasspathAttributeConfiguration config = fAttributeDescriptors
1412: .get(attrib.getKey());
1413: return config != null
1414: && config.canEdit(attrib
1415: .getClasspathAttributeAccess());
1416: }
1417: }
1418: return true;
1419: }
1420:
1421: private boolean canRemove(List list) {
1422: if (list.size() == 0) {
1423: return false;
1424: }
1425: for (int i = 0; i < list.size(); i++) {
1426: Object elem = list.get(i);
1427: if (elem instanceof CPListElementAttribute) {
1428: CPListElementAttribute attrib = (CPListElementAttribute) elem;
1429: if (attrib.isNonModifiable()) {
1430: return false;
1431: }
1432: if (attrib.isBuiltIn()) {
1433: if (attrib.getKey().equals(
1434: CPListElement.ACCESSRULES)) {
1435: return ((IAccessRule[]) attrib.getValue()).length > 0;
1436: }
1437: if (attrib.getValue() == null) {
1438: return false;
1439: }
1440: } else {
1441: ClasspathAttributeConfiguration config = fAttributeDescriptors
1442: .get(attrib.getKey());
1443: if (config == null
1444: || !config.canRemove(attrib
1445: .getClasspathAttributeAccess())) {
1446: return false;
1447: }
1448: }
1449: } else if (elem instanceof CPListElement) {
1450: // ok to remove
1451: } else if (elem instanceof CPUserLibraryElement) {
1452: // ok to remove
1453: } else { // unknown element
1454: return false;
1455: }
1456: }
1457: return true;
1458: }
1459:
1460: private CPUserLibraryElement getCommonParent(List list) {
1461: CPUserLibraryElement parent = null;
1462: for (int i = 0, len = list.size(); i < len; i++) {
1463: Object curr = list.get(i);
1464: if (curr instanceof CPListElement) {
1465: Object elemParent = ((CPListElement) curr)
1466: .getParentContainer();
1467: if (parent == null) {
1468: if (elemParent instanceof CPUserLibraryElement) {
1469: parent = (CPUserLibraryElement) elemParent;
1470: } else {
1471: return null;
1472: }
1473: } else if (parent != elemParent) {
1474: return null;
1475: }
1476: } else {
1477: return null;
1478: }
1479: }
1480: return parent;
1481: }
1482:
1483: private void doMoveUp(List list) {
1484: CPUserLibraryElement parent = getCommonParent(list);
1485: if (parent != null) {
1486: parent.moveUp(list);
1487: fLibraryList.refresh(parent);
1488: doSelectionChanged(fLibraryList);
1489: }
1490: }
1491:
1492: private void doMoveDown(List list) {
1493: CPUserLibraryElement parent = getCommonParent(list);
1494: if (parent != null) {
1495: parent.moveDown(list);
1496: fLibraryList.refresh(parent);
1497: doSelectionChanged(fLibraryList);
1498: }
1499: }
1500:
1501: private boolean canMoveUp(List list) {
1502: CPUserLibraryElement parent = getCommonParent(list);
1503: if (parent != null) {
1504: CPListElement[] children = parent.getChildren();
1505: for (int i = 0, len = Math
1506: .min(list.size(), children.length); i < len; i++) {
1507: if (!list.contains(children[i])) {
1508: return true;
1509: }
1510: }
1511: }
1512: return false;
1513: }
1514:
1515: private boolean canMoveDown(List list) {
1516: CPUserLibraryElement parent = getCommonParent(list);
1517: if (parent != null) {
1518: CPListElement[] children = parent.getChildren();
1519: for (int i = children.length - 1, end = Math.max(0,
1520: children.length - list.size()); i >= end; i--) {
1521: if (!list.contains(children[i])) {
1522: return true;
1523: }
1524: }
1525: }
1526: return false;
1527: }
1528:
1529: private CPListElement[] openExtJarFileDialog(
1530: CPListElement existing, Object parent) {
1531: String lastUsedPath;
1532: if (existing != null) {
1533: lastUsedPath = existing.getPath().removeLastSegments(1)
1534: .toOSString();
1535: } else {
1536: lastUsedPath = fDialogSettings
1537: .get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
1538: if (lastUsedPath == null) {
1539: lastUsedPath = ""; //$NON-NLS-1$
1540: }
1541: }
1542: String title = (existing == null) ? PreferencesMessages.UserLibraryPreferencePage_browsejar_new_title
1543: : PreferencesMessages.UserLibraryPreferencePage_browsejar_edit_title;
1544:
1545: FileDialog dialog = new FileDialog(getShell(),
1546: existing == null ? SWT.MULTI : SWT.SINGLE);
1547: dialog.setText(title);
1548: dialog.setFilterExtensions(new String[] { "*.jar;*.zip" }); //$NON-NLS-1$
1549: dialog.setFilterPath(lastUsedPath);
1550: if (existing != null) {
1551: dialog.setFileName(existing.getPath().lastSegment());
1552: }
1553:
1554: String res = dialog.open();
1555: if (res == null) {
1556: return null;
1557: }
1558: String[] fileNames = dialog.getFileNames();
1559: int nChosen = fileNames.length;
1560:
1561: IPath filterPath = Path.fromOSString(dialog.getFilterPath());
1562: CPListElement[] elems = new CPListElement[nChosen];
1563: for (int i = 0; i < nChosen; i++) {
1564: IPath path = filterPath.append(fileNames[i]).makeAbsolute();
1565: CPListElement curr = new CPListElement(parent, null,
1566: IClasspathEntry.CPE_LIBRARY, path, null);
1567: curr.setAttribute(CPListElement.SOURCEATTACHMENT,
1568: BuildPathSupport.guessSourceAttachment(curr));
1569: curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport
1570: .guessJavadocLocation(curr));
1571: elems[i] = curr;
1572: }
1573: fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog
1574: .getFilterPath());
1575:
1576: return elems;
1577: }
1578:
1579: private class UserLibraryAdapter implements ITreeListAdapter {
1580:
1581: private final Object[] EMPTY = new Object[0];
1582:
1583: public void customButtonPressed(TreeListDialogField field,
1584: int index) {
1585: doCustomButtonPressed(field, index);
1586: }
1587:
1588: public void selectionChanged(TreeListDialogField field) {
1589: doSelectionChanged(field);
1590: }
1591:
1592: public void doubleClicked(TreeListDialogField field) {
1593: doDoubleClicked(field);
1594: }
1595:
1596: public void keyPressed(TreeListDialogField field, KeyEvent event) {
1597: doKeyPressed(field, event);
1598: }
1599:
1600: public Object[] getChildren(TreeListDialogField field,
1601: Object element) {
1602: if (element instanceof CPUserLibraryElement) {
1603: CPUserLibraryElement elem = (CPUserLibraryElement) element;
1604: return elem.getChildren();
1605: } else if (element instanceof CPListElement) {
1606: return ((CPListElement) element).getChildren(false);
1607: } else if (element instanceof CPListElementAttribute) {
1608: CPListElementAttribute attribute = (CPListElementAttribute) element;
1609: if (CPListElement.ACCESSRULES
1610: .equals(attribute.getKey())) {
1611: return (IAccessRule[]) attribute.getValue();
1612: }
1613: }
1614: return EMPTY;
1615: }
1616:
1617: public Object getParent(TreeListDialogField field,
1618: Object element) {
1619: if (element instanceof CPListElementAttribute) {
1620: return ((CPListElementAttribute) element).getParent();
1621: } else if (element instanceof CPListElement) {
1622: return ((CPListElement) element).getParentContainer();
1623: }
1624: return null;
1625: }
1626:
1627: public boolean hasChildren(TreeListDialogField field,
1628: Object element) {
1629: return getChildren(field, element).length > 0;
1630: }
1631:
1632: }
1633:
1634: }
|