KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > editor > site > CategorySection


1 /*******************************************************************************
2  * Copyright (c) 2003, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.internal.ui.editor.site;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.HashSet JavaDoc;
16
17 import org.eclipse.core.resources.IFile;
18 import org.eclipse.core.runtime.CoreException;
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.jface.action.Action;
21 import org.eclipse.jface.action.IMenuManager;
22 import org.eclipse.jface.action.Separator;
23 import org.eclipse.jface.operation.IRunnableWithProgress;
24 import org.eclipse.jface.viewers.ISelection;
25 import org.eclipse.jface.viewers.IStructuredSelection;
26 import org.eclipse.jface.viewers.ITreeContentProvider;
27 import org.eclipse.jface.viewers.LabelProvider;
28 import org.eclipse.jface.viewers.StructuredSelection;
29 import org.eclipse.jface.viewers.TreeViewer;
30 import org.eclipse.jface.viewers.ViewerDropAdapter;
31 import org.eclipse.jface.window.Window;
32 import org.eclipse.osgi.util.NLS;
33 import org.eclipse.pde.core.IModelChangedEvent;
34 import org.eclipse.pde.internal.core.FeatureModelManager;
35 import org.eclipse.pde.internal.core.IFeatureModelDelta;
36 import org.eclipse.pde.internal.core.IFeatureModelListener;
37 import org.eclipse.pde.internal.core.PDECore;
38 import org.eclipse.pde.internal.core.ifeature.IFeature;
39 import org.eclipse.pde.internal.core.ifeature.IFeatureImport;
40 import org.eclipse.pde.internal.core.ifeature.IFeatureModel;
41 import org.eclipse.pde.internal.core.isite.ISiteCategory;
42 import org.eclipse.pde.internal.core.isite.ISiteCategoryDefinition;
43 import org.eclipse.pde.internal.core.isite.ISiteFeature;
44 import org.eclipse.pde.internal.core.isite.ISiteModel;
45 import org.eclipse.pde.internal.core.site.WorkspaceSiteModel;
46 import org.eclipse.pde.internal.ui.PDEPlugin;
47 import org.eclipse.pde.internal.ui.PDEUIMessages;
48 import org.eclipse.pde.internal.ui.build.BuildSiteJob;
49 import org.eclipse.pde.internal.ui.editor.ModelDataTransfer;
50 import org.eclipse.pde.internal.ui.editor.PDEFormPage;
51 import org.eclipse.pde.internal.ui.editor.TreeSection;
52 import org.eclipse.pde.internal.ui.editor.feature.FeatureEditor;
53 import org.eclipse.pde.internal.ui.elements.DefaultContentProvider;
54 import org.eclipse.pde.internal.ui.parts.TreePart;
55 import org.eclipse.pde.internal.ui.wizards.FeatureSelectionDialog;
56 import org.eclipse.swt.SWT;
57 import org.eclipse.swt.custom.BusyIndicator;
58 import org.eclipse.swt.dnd.DND;
59 import org.eclipse.swt.dnd.DragSourceEvent;
60 import org.eclipse.swt.dnd.DragSourceListener;
61 import org.eclipse.swt.dnd.DropTargetEvent;
62 import org.eclipse.swt.dnd.Transfer;
63 import org.eclipse.swt.dnd.TransferData;
64 import org.eclipse.swt.graphics.Point;
65 import org.eclipse.swt.graphics.Rectangle;
66 import org.eclipse.swt.widgets.Composite;
67 import org.eclipse.swt.widgets.Control;
68 import org.eclipse.swt.widgets.Item;
69 import org.eclipse.ui.PlatformUI;
70 import org.eclipse.ui.actions.ActionFactory;
71 import org.eclipse.ui.forms.widgets.FormToolkit;
72 import org.eclipse.ui.forms.widgets.Section;
73 import org.osgi.framework.Version;
74
75 public class CategorySection extends TreeSection implements
76         IFeatureModelListener {
77     private static final int BUTTON_ADD_CATEGORY = 0;
78
79     private static final int BUTTON_ADD_FEATURE = 1;
80
81     private static final int BUTTON_IMPORT_ENVIRONMENT = 3;
82     
83     private static final int BUTTON_BUILD_FEATURE = 5;
84
85     private static final int BUTTON_BUILD_ALL = 6;
86     
87     private static int newCategoryCounter;
88
89     private ISiteModel fModel;
90
91     private TreePart fCategoryTreePart;
92
93     private TreeViewer fCategoryViewer;
94     
95     private LabelProvider fSiteLabelProvider;
96
97     class CategoryContentProvider extends DefaultContentProvider implements
98             ITreeContentProvider {
99         public Object JavaDoc[] getElements(Object JavaDoc inputElement) {
100             // model = (ISite) inputElement;
101
ArrayList JavaDoc result = new ArrayList JavaDoc();
102             ISiteCategoryDefinition[] catDefs = fModel.getSite()
103                     .getCategoryDefinitions();
104             for (int i = 0; i < catDefs.length; i++) {
105                 result.add(catDefs[i]);
106             }
107             ISiteFeature[] features = fModel.getSite().getFeatures();
108             for (int i = 0; i < features.length; i++) {
109                 if (features[i].getCategories().length == 0)
110                     result.add(new SiteFeatureAdapter(null, features[i]));
111             }
112             return result.toArray();
113         }
114
115         public Object JavaDoc[] getChildren(Object JavaDoc parent) {
116             if (parent instanceof ISiteCategoryDefinition) {
117                 ISiteCategoryDefinition catDef = (ISiteCategoryDefinition) parent;
118                 ISiteFeature[] features = fModel.getSite().getFeatures();
119                 HashSet JavaDoc result = new HashSet JavaDoc();
120                 for (int i = 0; i < features.length; i++) {
121                     ISiteCategory[] cats = features[i].getCategories();
122                     for (int j = 0; j < cats.length; j++) {
123                         if (cats[j].getDefinition() != null
124                                 && cats[j].getDefinition().equals(catDef)) {
125                             result.add(new SiteFeatureAdapter(
126                                     cats[j].getName(), features[i]));
127                         }
128                     }
129                 }
130                 return result.toArray();
131             }
132             return new Object JavaDoc[0];
133         }
134
135         public Object JavaDoc getParent(Object JavaDoc element) {
136             return null;
137         }
138
139         public boolean hasChildren(Object JavaDoc element) {
140             if (element instanceof ISiteCategoryDefinition) {
141                 ISiteCategoryDefinition catDef = (ISiteCategoryDefinition) element;
142                 ISiteFeature[] features = fModel.getSite().getFeatures();
143                 for (int i = 0; i < features.length; i++) {
144                     ISiteCategory[] cats = features[i].getCategories();
145                     for (int j = 0; j < cats.length; j++) {
146                         if (cats[j].getDefinition() != null
147                                 && cats[j].getDefinition().equals(catDef)) {
148                             return true;
149                         }
150                     }
151                 }
152             }
153             return false;
154         }
155     }
156
157     public CategorySection(PDEFormPage formPage, Composite parent) {
158         super(formPage, parent, Section.DESCRIPTION, new String JavaDoc[] {
159                 PDEUIMessages.CategorySection_new,
160                 PDEUIMessages.CategorySection_add,
161                 null, PDEUIMessages.CategorySection_environment,
162                     null, PDEUIMessages.CategorySection_build,
163                 PDEUIMessages.CategorySection_buildAll });
164         getSection().setText(
165                 PDEUIMessages.CategorySection_title);
166         getSection().setDescription(
167                 PDEUIMessages.CategorySection_desc);
168     }
169
170     /*
171      * (non-Javadoc)
172      *
173      * @see org.eclipse.update.ui.forms.internal.FormSection#createClient(org.eclipse.swt.widgets.Composite,
174      * org.eclipse.update.ui.forms.internal.FormWidgetFactory)
175      */

176     public void createClient(Section section, FormToolkit toolkit) {
177         fModel = (ISiteModel) getPage().getModel();
178         fModel.addModelChangedListener(this);
179
180         Composite container = createClientContainer(section, 2, toolkit);
181         createViewerPartControl(container, SWT.SINGLE, 2, toolkit);
182         fCategoryTreePart = getTreePart();
183         fCategoryViewer = fCategoryTreePart.getTreeViewer();
184         fCategoryViewer.setContentProvider(new CategoryContentProvider());
185         fSiteLabelProvider = new SiteLabelProvider();
186         fCategoryViewer.setLabelProvider(fSiteLabelProvider);
187
188         fCategoryViewer.setInput(fModel.getSite());
189         int ops = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_DEFAULT;
190         Transfer[] transfers = new Transfer[] { ModelDataTransfer.getInstance() };
191         if (isEditable()) {
192             fCategoryViewer.addDropSupport(ops, transfers,
193                     new ViewerDropAdapter(fCategoryViewer) {
194                         public void dragEnter(DropTargetEvent event) {
195                             Object JavaDoc target = determineTarget(event);
196                             if (target == null && event.detail == DND.DROP_COPY) {
197                                 event.detail = DND.DROP_MOVE;
198                             }
199                             super.dragEnter(event);
200                         }
201
202                         /*
203                          * (non-Javadoc)
204                          *
205                          * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
206                          */

207                         public void dragOperationChanged(DropTargetEvent event) {
208                             Object JavaDoc target = determineTarget(event);
209                             if (target == null && event.detail == DND.DROP_COPY) {
210                                 event.detail = DND.DROP_MOVE;
211                             }
212                             super.dragOperationChanged(event);
213                         }
214
215                         /*
216                          * (non-Javadoc)
217                          *
218                          * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragOver(org.eclipse.swt.dnd.DropTargetEvent)
219                          */

220                         public void dragOver(DropTargetEvent event) {
221                             Object JavaDoc target = determineTarget(event);
222                             if (target == null && event.detail == DND.DROP_COPY) {
223                                 event.detail = DND.DROP_MOVE;
224                             }
225                             super.dragOver(event);
226                         }
227
228                         /**
229                          * Returns the position of the given event's coordinates
230                          * relative to its target. The position is determined to
231                          * be before, after, or on the item, based on some
232                          * threshold value.
233                          *
234                          * @param event
235                          * the event
236                          * @return one of the <code>LOCATION_* </code>
237                          * constants defined in this class
238                          */

239                         protected int determineLocation(DropTargetEvent event) {
240                             if (!(event.item instanceof Item)) {
241                                 return LOCATION_NONE;
242                             }
243                             Item item = (Item) event.item;
244                             Point coordinates = new Point(event.x, event.y);
245                             coordinates = getViewer().getControl().toControl(
246                                     coordinates);
247                             if (item != null) {
248                                 Rectangle bounds = getBounds(item);
249                                 if (bounds == null) {
250                                     return LOCATION_NONE;
251                                 }
252                             }
253                             return LOCATION_ON;
254                         }
255
256                         public boolean performDrop(Object JavaDoc data) {
257                             if (!(data instanceof Object JavaDoc[]))
258                                 return false;
259                             Object JavaDoc target = getCurrentTarget();
260
261                             int op = getCurrentOperation();
262                             Object JavaDoc[] objects = (Object JavaDoc[]) data;
263                             if (objects.length > 0
264                                     && objects[0] instanceof SiteFeatureAdapter) {
265                                 if (op == DND.DROP_COPY && target != null) {
266                                     copyFeature(
267                                             (SiteFeatureAdapter) objects[0],
268                                             target);
269                                 } else {
270                                     moveFeature(
271                                             (SiteFeatureAdapter) objects[0],
272                                             target);
273                                 }
274                                 return true;
275                             }
276                             return false;
277                         }
278
279                         public boolean validateDrop(Object JavaDoc target,
280                                 int operation, TransferData transferType) {
281                             return (target instanceof ISiteCategoryDefinition || target == null);
282                         }
283
284                     });
285         }
286
287         fCategoryViewer.addDragSupport(DND.DROP_MOVE | DND.DROP_COPY,
288                 transfers, new DragSourceListener() {
289                     public void dragStart(DragSourceEvent event) {
290                         IStructuredSelection ssel = (IStructuredSelection) fCategoryViewer
291                                 .getSelection();
292                         if (ssel == null
293                                 || ssel.isEmpty()
294                                 || !(ssel.getFirstElement() instanceof SiteFeatureAdapter)) {
295                             event.doit = false;
296                         }
297                     }
298
299                     public void dragSetData(DragSourceEvent event) {
300                         IStructuredSelection ssel = (IStructuredSelection) fCategoryViewer
301                                 .getSelection();
302                         event.data = ssel.toArray();
303                     }
304
305                     public void dragFinished(DragSourceEvent event) {
306                     }
307                 });
308         
309         fCategoryTreePart.setButtonEnabled(BUTTON_ADD_CATEGORY, isEditable());
310         fCategoryTreePart.setButtonEnabled(BUTTON_ADD_FEATURE, isEditable());
311         fCategoryTreePart.setButtonEnabled(BUTTON_BUILD_FEATURE, isEditable());
312         fCategoryTreePart.setButtonEnabled(BUTTON_BUILD_ALL, isEditable());
313
314         // fCategoryViewer.expandAll();
315
toolkit.paintBordersFor(container);
316         section.setClient(container);
317         initialize();
318     }
319
320     private boolean categoryExists(String JavaDoc name) {
321         ISiteCategoryDefinition [] defs = fModel.getSite().getCategoryDefinitions();
322         for (int i=0; i<defs.length; i++) {
323             ISiteCategoryDefinition def = defs[i];
324             String JavaDoc dname = def.getName();
325             if (dname!=null && dname.equals(name))
326                 return true;
327         }
328         return false;
329     }
330     
331     private void copyFeature(SiteFeatureAdapter adapter, Object JavaDoc target) {
332         ISiteFeature feature = findRealFeature(adapter);
333         if (feature == null) {
334             return;
335         }
336         /*
337          * if (adapter.category == null) { moveFeature(adapter, target); } else
338          */
if (target != null && target instanceof ISiteCategoryDefinition) {
339             addCategory(feature, ((ISiteCategoryDefinition) target).getName());
340         }
341     }
342
343     private void addCategory(ISiteFeature aFeature, String JavaDoc catName) {
344         try {
345             if (aFeature == null)
346                 return;
347             ISiteCategory[] cats = aFeature.getCategories();
348             for (int j = 0; j < cats.length; j++) {
349                 if (cats[j].getName().equals(catName))
350                     return;
351             }
352             ISiteCategory cat = fModel.getFactory().createCategory(aFeature);
353             cat.setName(catName);
354             expandCategory(catName);
355             aFeature.addCategories(new ISiteCategory[] { cat });
356         } catch (CoreException e) {
357         }
358     }
359
360     private void moveFeature(SiteFeatureAdapter adapter, Object JavaDoc target) {
361         ISiteFeature feature = findRealFeature(adapter);
362         if (feature == null) {
363             return;
364         }
365         if (adapter.category != null) {
366             removeCategory(feature, adapter.category);
367         }
368         if (target != null && target instanceof ISiteCategoryDefinition) {
369             addCategory(feature, ((ISiteCategoryDefinition) target).getName());
370         }
371     }
372
373     protected void buttonSelected(int index) {
374         switch (index) {
375         case BUTTON_ADD_CATEGORY:
376             handleAddCategoryDefinition();
377             break;
378         case BUTTON_ADD_FEATURE:
379             handleNewFeature();
380             break;
381         case BUTTON_BUILD_FEATURE:
382             handleBuild();
383             break;
384         case BUTTON_BUILD_ALL:
385             handleBuild(fModel.getSite().getFeatures());
386             break;
387         case BUTTON_IMPORT_ENVIRONMENT:
388             handleImportEnvironment();
389         }
390     }
391
392     protected void handleDoubleClick(IStructuredSelection ssel) {
393         Object JavaDoc selected = ssel.getFirstElement();
394         if (selected instanceof SiteFeatureAdapter) {
395             IFeature feature = findFeature(((SiteFeatureAdapter) selected).feature);
396             FeatureEditor.openFeatureEditor(feature);
397         }
398     }
399
400     protected void selectionChanged(IStructuredSelection selection) {
401         getPage().getPDEEditor().setSelection(selection);
402         updateButtons();
403     }
404
405     private void handleAddCategoryDefinition() {
406         String JavaDoc name = NLS.bind(PDEUIMessages.CategorySection_newCategoryName, Integer .toString(++newCategoryCounter));
407         while (categoryExists(name)) {
408             name = NLS.bind(PDEUIMessages.CategorySection_newCategoryName, Integer .toString(++newCategoryCounter));
409         }
410         String JavaDoc label = NLS.bind(PDEUIMessages.CategorySection_newCategoryLabel, Integer .toString(newCategoryCounter));
411         ISiteCategoryDefinition categoryDef = fModel.getFactory()
412                 .createCategoryDefinition();
413         try {
414             categoryDef.setName(name);
415             categoryDef.setLabel(label);
416             fModel.getSite().addCategoryDefinitions(
417                     new ISiteCategoryDefinition[] { categoryDef });
418         } catch (CoreException e) {
419             PDEPlugin.logException(e);
420         }
421         fCategoryViewer.setSelection(new StructuredSelection(categoryDef), true);
422     }
423
424     private boolean handleRemove() {
425         IStructuredSelection ssel = (IStructuredSelection) fCategoryViewer
426                 .getSelection();
427         Object JavaDoc object = ssel.getFirstElement();
428         if (object == null)
429             return true;
430         if (object instanceof ISiteCategoryDefinition) {
431             return handleRemoveCategoryDefinition((ISiteCategoryDefinition) object);
432         }
433         return handleRemoveSiteFeatureAdapter((SiteFeatureAdapter) object);
434     }
435
436     private boolean handleRemoveCategoryDefinition(
437             ISiteCategoryDefinition catDef) {
438         try {
439             Object JavaDoc[] children = ((CategoryContentProvider) fCategoryViewer
440                     .getContentProvider()).getChildren(catDef);
441             for (int i = 0; i < children.length; i++) {
442                 SiteFeatureAdapter adapter = (SiteFeatureAdapter) children[i];
443                 ISiteCategory[] cats = adapter.feature.getCategories();
444                 for (int j = 0; j < cats.length; j++) {
445                     if (adapter.category.equals(cats[j].getName()))
446                         adapter.feature
447                                 .removeCategories(new ISiteCategory[] { cats[j] });
448                 }
449                 if (adapter.feature.getCategories().length == 0) {
450                     fModel.getSite().removeFeatures(
451                             new ISiteFeature[] { adapter.feature });
452                 }
453             }
454             fModel.getSite().removeCategoryDefinitions(
455                     new ISiteCategoryDefinition[] { catDef });
456             return true;
457         } catch (CoreException e) {
458         }
459         return false;
460     }
461
462     private boolean handleRemoveSiteFeatureAdapter(SiteFeatureAdapter adapter) {
463         try {
464             ISiteFeature feature = adapter.feature;
465             if (adapter.category == null) {
466                 fModel.getSite().removeFeatures(new ISiteFeature[] { feature });
467             } else {
468                 removeCategory(feature, adapter.category);
469                 if (feature.getCategories().length == 0)
470                     fModel.getSite().removeFeatures(
471                             new ISiteFeature[] { feature });
472             }
473             return true;
474         } catch (CoreException e) {
475         }
476         return false;
477     }
478
479     private void removeCategory(ISiteFeature aFeature, String JavaDoc catName) {
480         try {
481             if (aFeature == null)
482                 return;
483             ISiteCategory[] cats = aFeature.getCategories();
484             for (int i = 0; i < cats.length; i++) {
485                 if (catName.equals(cats[i].getName()))
486                     aFeature.removeCategories(new ISiteCategory[] { cats[i] });
487             }
488         } catch (CoreException e) {
489         }
490     }
491
492     private ISiteFeature findRealFeature(SiteFeatureAdapter adapter) {
493         ISiteFeature featureCopy = adapter.feature;
494         ISiteFeature[] features = fModel.getSite().getFeatures();
495         for (int i = 0; i < features.length; i++) {
496             if (features[i].getId().equals(featureCopy.getId())
497                     && features[i].getVersion()
498                             .equals(featureCopy.getVersion())) {
499                 return features[i];
500             }
501         }
502         return null;
503     }
504
505     public void dispose() {
506         super.dispose();
507         FeatureModelManager mng = PDECore.getDefault().getFeatureModelManager();
508         mng.removeFeatureModelListener(this);
509         fModel.removeModelChangedListener(this);
510         if (fSiteLabelProvider != null)
511             fSiteLabelProvider.dispose();
512     }
513
514     protected void fillContextMenu(IMenuManager manager) {
515         Action removeAction = new Action(PDEUIMessages.CategorySection_remove) {
516             public void run() {
517                 doGlobalAction(ActionFactory.DELETE.getId());
518             }
519         };
520         removeAction.setEnabled(isEditable());
521         manager.add(removeAction);
522         getPage().getPDEEditor().getContributor().contextMenuAboutToShow(
523                 manager);
524
525         ISelection selection = fCategoryViewer.getSelection();
526         if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
527             Object JavaDoc o = ((IStructuredSelection) selection)
528                     .getFirstElement();
529             if (o instanceof SiteFeatureAdapter) {
530                 final SiteFeatureAdapter adapter = (SiteFeatureAdapter)o;
531                 manager.add(new Separator());
532                 
533                 Action synchronizeAction = new SynchronizePropertiesAction(adapter.feature, fModel);
534                 manager.add(synchronizeAction);
535                 synchronizeAction.setEnabled(isEditable());
536
537                 Action buildAction = new Action(PDEUIMessages.CategorySection_build) {
538                             public void run() {
539                                 handleBuild(new ISiteFeature[] { adapter.feature });
540                             }
541                         };
542                 manager.add(buildAction);
543                 buildAction.setEnabled(isEditable()&& findFeature(adapter.feature) != null );
544
545             }
546         }
547
548     }
549
550     public boolean doGlobalAction(String JavaDoc actionId) {
551         if (actionId.equals(ActionFactory.CUT.getId())) {
552             handleRemove();
553             return false;
554         }
555         if (actionId.equals(ActionFactory.PASTE.getId())) {
556             doPaste();
557             return true;
558         }
559         if (actionId.equals(ActionFactory.DELETE.getId())) {
560             return handleRemove();
561         }
562         return false;
563     }
564
565     public void refresh() {
566         fCategoryViewer.refresh();
567         updateButtons();
568         super.refresh();
569     }
570
571     private void updateButtons() {
572         if(!isEditable()){
573             return;
574         }
575         IStructuredSelection sel = (IStructuredSelection) fCategoryViewer
576                 .getSelection();
577         fCategoryTreePart.setButtonEnabled(BUTTON_BUILD_FEATURE,
578                 !sel.isEmpty()
579                         && sel.getFirstElement() instanceof SiteFeatureAdapter
580                         && findFeature(((SiteFeatureAdapter) sel
581                                 .getFirstElement()).feature) != null);
582         int featureCount = fModel.getSite().getFeatures().length;
583         fCategoryTreePart.setButtonEnabled(BUTTON_BUILD_ALL, featureCount > 0);
584         fCategoryTreePart.setButtonEnabled(BUTTON_IMPORT_ENVIRONMENT, featureCount > 0);
585     }
586
587     public void modelChanged(IModelChangedEvent e) {
588         markStale();
589     }
590
591     public void initialize() {
592         refresh();
593         FeatureModelManager mng = PDECore.getDefault().getFeatureModelManager();
594         mng.addFeatureModelListener(this);
595     }
596
597     /*
598      * (non-Javadoc)
599      *
600      * @see org.eclipse.pde.internal.ui.editor.StructuredViewerSection#doPaste(java.lang.Object,
601      * java.lang.Object[])
602      */

603     protected void doPaste(Object JavaDoc target, Object JavaDoc[] objects) {
604         try {
605             for (int i = 0; i < objects.length; i++) {
606                 if (objects[i] instanceof SiteFeatureAdapter) {
607                     copyFeature((SiteFeatureAdapter) objects[i], target);
608                 } else if (objects[i] instanceof ISiteCategoryDefinition) {
609                     fModel
610                             .getSite()
611                             .addCategoryDefinitions(
612                                     new ISiteCategoryDefinition[] { (ISiteCategoryDefinition) objects[i] });
613                 }
614             }
615         } catch (CoreException e) {
616         }
617     }
618
619     /*
620      * (non-Javadoc)
621      *
622      * @see org.eclipse.pde.internal.ui.editor.StructuredViewerSection#canPaste(java.lang.Object,
623      * java.lang.Object[])
624      */

625     protected boolean canPaste(Object JavaDoc target, Object JavaDoc[] objects) {
626         if (target == null || target instanceof ISiteCategoryDefinition) {
627             for (int i = 0; i < objects.length; i++) {
628                 if (objects[i] instanceof SiteFeatureAdapter)
629                     return true;
630                 if (objects[i] instanceof ISiteCategoryDefinition) {
631                     String JavaDoc name = ((ISiteCategoryDefinition) objects[i])
632                             .getName();
633                     ISiteCategoryDefinition[] defs = fModel.getSite()
634                             .getCategoryDefinitions();
635                     for (int j = 0; j < defs.length; j++) {
636                         ISiteCategoryDefinition def = defs[j];
637                         String JavaDoc dname = def.getName();
638                         if (dname != null && dname.equals(name))
639                             return false;
640                     }
641                     return true;
642                 }
643             }
644         }
645         return false;
646     }
647     
648     private void handleBuild() {
649         IStructuredSelection sel = (IStructuredSelection) fCategoryViewer
650                 .getSelection();
651         if (!sel.isEmpty()
652                 && sel.getFirstElement() instanceof SiteFeatureAdapter) {
653             ISiteFeature feature = ((SiteFeatureAdapter) sel.getFirstElement()).feature;
654             handleBuild(new ISiteFeature[] { feature });
655         }
656     }
657
658     private void handleBuild(ISiteFeature[] sFeatures) {
659         if (sFeatures.length == 0)
660             return;
661         IFeatureModel[] models = getFeatureModels(sFeatures);
662         if (models.length == 0)
663             return;
664         ensureContentSaved();
665         ISiteModel buildSiteModel = new WorkspaceSiteModel((IFile) fModel.getUnderlyingResource());
666         try {
667             buildSiteModel.load();
668         } catch (CoreException e) {
669             PDEPlugin.logException(e);
670             return;
671         }
672
673         BuildSiteJob job = new BuildSiteJob(models, buildSiteModel);
674         job.setUser(true);
675         job.schedule();
676     }
677
678     /**
679      * Finds a feature with the same id and version as a site feature. If
680      * feature is not found, but feature with a M.m.s.qualifier exists it will
681      * be returned.
682      *
683      * @param siteFeature
684      * @return IFeature or null
685      */

686     public static IFeature findFeature(ISiteFeature siteFeature) {
687         IFeatureModel model = PDECore.getDefault().getFeatureModelManager()
688                 .findFeatureModelRelaxed(siteFeature.getId(),
689                         siteFeature.getVersion());
690         if (model != null)
691             return model.getFeature();
692         return null;
693     }
694
695     private IFeatureModel[] getFeatureModels(ISiteFeature[] sFeatures) {
696         ArrayList JavaDoc list = new ArrayList JavaDoc();
697         for (int i = 0; i < sFeatures.length; i++) {
698             IFeatureModel model = PDECore.getDefault().getFeatureModelManager()
699                     .findFeatureModelRelaxed(sFeatures[i].getId(),
700                             sFeatures[i].getVersion());
701             if (model != null)
702                 list.add(model);
703         }
704         return (IFeatureModel[]) list.toArray(new IFeatureModel[list.size()]);
705     }
706
707     private void handleImportEnvironment() {
708         IStructuredSelection sel = (IStructuredSelection) fCategoryViewer
709                 .getSelection();
710         ISiteFeature feature = null;
711         if (!sel.isEmpty()
712                 && sel.getFirstElement() instanceof SiteFeatureAdapter) {
713             feature = ((SiteFeatureAdapter) sel.getFirstElement()).feature;
714         }
715         final ISiteFeature selectedFeature = feature;
716         BusyIndicator.showWhile(fCategoryTreePart.getControl().getDisplay(),
717                 new Runnable JavaDoc() {
718                     public void run() {
719                         new SynchronizePropertiesAction(selectedFeature,
720                                 getModel()).run();
721                     }
722                 });
723     }
724     
725     private void handleNewFeature() {
726         final Control control = fCategoryViewer.getControl();
727         BusyIndicator.showWhile(control.getDisplay(), new Runnable JavaDoc() {
728             public void run() {
729                 IFeatureModel[] allModels = PDECore.getDefault()
730                         .getFeatureModelManager().getModels();
731                 ArrayList JavaDoc newModels = new ArrayList JavaDoc();
732                 for (int i = 0; i < allModels.length; i++) {
733                     if (canAdd(allModels[i]))
734                         newModels.add(allModels[i]);
735                 }
736                 IFeatureModel[] candidateModels = (IFeatureModel[]) newModels
737                         .toArray(new IFeatureModel[newModels.size()]);
738                 FeatureSelectionDialog dialog = new FeatureSelectionDialog(
739                         fCategoryViewer.getTree().getShell(), candidateModels,
740                         true);
741                 if (dialog.open() == Window.OK) {
742                     Object JavaDoc[] models = dialog.getResult();
743                     try {
744                         doAdd(models);
745                     } catch (CoreException e) {
746                         PDEPlugin.log(e);
747                     }
748                 }
749             }
750         });
751     }
752
753     private boolean canAdd(IFeatureModel candidate) {
754         ISiteFeature[] features = fModel.getSite().getFeatures();
755         IFeature cfeature = candidate.getFeature();
756
757         for (int i = 0; i < features.length; i++) {
758             ISiteFeature bfeature = features[i];
759             if (bfeature.getId().equals(cfeature.getId())
760                     && bfeature.getVersion().equals(cfeature.getVersion()))
761                 return false;
762         }
763         return true;
764     }
765
766     public static ISiteFeature createSiteFeature(ISiteModel model,
767             IFeatureModel featureModel) throws CoreException {
768         IFeature feature = featureModel.getFeature();
769         ISiteFeature sfeature = model.getFactory().createFeature();
770         sfeature.setId(feature.getId());
771         sfeature.setVersion(feature.getVersion());
772         // sfeature.setURL(model.getBuildModel().getSiteBuild().getFeatureLocation()
773
// + "/" + feature.getId() + "_" + feature.getVersion() + ".jar");
774
// //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
775
sfeature
776                 .setURL("features/" + feature.getId() + "_" + formatVersion(feature.getVersion()) + ".jar"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
777
sfeature.setOS(feature.getOS());
778         sfeature.setWS(feature.getWS());
779         sfeature.setArch(feature.getArch());
780         sfeature.setNL(feature.getNL());
781         sfeature.setIsPatch(isFeaturePatch(feature));
782         return sfeature;
783     }
784     
785     private static String JavaDoc formatVersion(String JavaDoc version) {
786         try {
787             Version v = new Version(version);
788             return v.toString();
789         } catch (IllegalArgumentException JavaDoc e){
790         }
791         return version;
792     }
793
794     private static boolean isFeaturePatch(IFeature feature) {
795         IFeatureImport[] imports = feature.getImports();
796         for (int i = 0; i < imports.length; i++) {
797             if (imports[i].isPatch())
798                 return true;
799         }
800         return false;
801     }
802
803     public ISiteModel getModel() {
804         return fModel;
805     }
806
807     /**
808      *
809      * @param candidates
810      * Array of IFeatureModel
811      * @param monitor
812      * @throws CoreException
813      */

814     public void doAdd(Object JavaDoc[] candidates)
815             throws CoreException {
816         // Category to add features to
817
String JavaDoc categoryName = null;
818         ISelection selection = fCategoryViewer.getSelection();
819         if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
820             Object JavaDoc element = ((IStructuredSelection) selection)
821                     .getFirstElement();
822             if (element instanceof ISiteCategoryDefinition) {
823                 categoryName = ((ISiteCategoryDefinition) element).getName();
824             } else if (element instanceof SiteFeatureAdapter) {
825                 categoryName = ((SiteFeatureAdapter) element).category;
826             }
827         }
828         //
829
ISiteFeature[] added = new ISiteFeature[candidates.length];
830         for (int i = 0; i < candidates.length; i++) {
831             IFeatureModel candidate = (IFeatureModel) candidates[i];
832             ISiteFeature child = createSiteFeature(fModel, candidate);
833             if (categoryName != null) {
834                 addCategory(child, categoryName);
835             }
836             added[i] = child;
837         }
838
839         // Update model
840
fModel.getSite().addFeatures(added);
841         // Select last added feature
842
if (added.length > 0) {
843             if (categoryName != null) {
844                 expandCategory(categoryName);
845             }
846             fCategoryViewer.setSelection(new StructuredSelection(
847                     new SiteFeatureAdapter(categoryName, added[added.length-1])),
848                     true);
849         }
850     }
851
852     private void ensureContentSaved() {
853         if (getPage().getEditor().isDirty()) {
854             try {
855                 IRunnableWithProgress op = new IRunnableWithProgress() {
856                     public void run(IProgressMonitor monitor) {
857                         getPage().getEditor().doSave(monitor);
858                     }
859                 };
860                 PlatformUI.getWorkbench().getProgressService().runInUI(
861                         PDEPlugin.getActiveWorkbenchWindow(), op,
862                         PDEPlugin.getWorkspace().getRoot());
863             } catch (InvocationTargetException JavaDoc e) {
864                 PDEPlugin.logException(e);
865             } catch (InterruptedException JavaDoc e) {
866             }
867         }
868     }
869     void fireSelection() {
870         fCategoryViewer.setSelection(fCategoryViewer.getSelection());
871     }
872     /* (non-Javadoc)
873      * @see org.eclipse.ui.forms.AbstractFormPart#setFormInput(java.lang.Object)
874      */

875     public boolean setFormInput(Object JavaDoc input) {
876         if (input instanceof ISiteCategoryDefinition){
877             fCategoryViewer.setSelection(new StructuredSelection(input), true);
878             return true;
879         }
880         if (input instanceof SiteFeatureAdapter ) {
881             // first, expand the category, otherwise tree will not find the feature
882
String JavaDoc category = ((SiteFeatureAdapter)input).category;
883             if(category!=null){
884                 expandCategory(category);
885             }
886             fCategoryViewer.setSelection(new StructuredSelection(input), true);
887             return true;
888         }
889         return super.setFormInput(input);
890     }
891     private void expandCategory(String JavaDoc category){
892         if(category!=null){
893             ISiteCategoryDefinition[] catDefs = fModel.getSite().getCategoryDefinitions();
894             for (int i = 0; i < catDefs.length; i++) {
895                 if (category.equals(catDefs[i].getName())){
896                     fCategoryViewer.expandToLevel(catDefs[i], 1);
897                     break;
898                 }
899             }
900         }
901         
902     }
903     public void modelsChanged(IFeatureModelDelta delta) {
904         markStale();
905     }
906 }
907
Popular Tags