Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a2c031e9eca010a7f2e787f8584bd7343af6dd99 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*******************************************************************************
 * Copyright (c) 2008-2010 Sonatype, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *      Sonatype, Inc. - initial API and implementation
 *******************************************************************************/

package org.eclipse.m2e.editor.pom;

import static org.eclipse.m2e.editor.pom.FormUtils.isEmpty;

import java.util.Iterator;
import org.apache.maven.project.MavenProject;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.core.IMavenConstants;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.MavenProjectManager;
import org.eclipse.m2e.core.ui.internal.actions.OpenPomAction;
import org.eclipse.m2e.core.ui.internal.dialogs.InputHistory;
import org.eclipse.m2e.core.ui.internal.editing.PomEdits;
import org.eclipse.m2e.core.ui.internal.editing.PomEdits.Operation;
import org.eclipse.m2e.core.ui.internal.editing.PomEdits.OperationTuple;

import static org.eclipse.m2e.core.ui.internal.editing.PomEdits.*;

import org.eclipse.m2e.editor.MavenEditorImages;
import org.eclipse.m2e.editor.internal.Messages;
import org.eclipse.m2e.editor.pom.PropertiesSection.PropertyElement;
import org.eclipse.m2e.editor.xml.internal.FormHoverProvider;
import org.eclipse.m2e.model.edit.pom.Model;
import org.eclipse.m2e.model.edit.pom.Parent;
import org.eclipse.m2e.model.edit.pom.PomPackage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.wst.sse.core.internal.provisional.IModelStateListener;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;


/**
 * This class provides basic page editor functionality (event listeners, readonly, etc)
 * 
 * @author Anton Kraev
 * @author Eugene Kuleshov
 */
public abstract class MavenPomEditorPage extends FormPage implements Adapter {
  private static final String MODIFY_LISTENER = "MODIFY_LISTENER";

  private static final String VALUE_PROVIDER = "VALUE_PROVIDER";

  private static final Logger LOG = LoggerFactory.getLogger(MavenPomEditorPage.class);

  // parent editor
  protected final MavenPomEditor pomEditor;

  // model
  protected Model model;

  // Notifier target
  protected Notifier target;

  // are we already updating model
  protected boolean updatingModel;
  
  private boolean updatingModel2 = false;

  // have we loaded data?
  private boolean dataLoaded;

  private InputHistory inputHistory;
  
  protected static PomPackage POM_PACKAGE = PomPackage.eINSTANCE;

  private Action selectParentAction;

  private IModelStateListener listener;
  
  private boolean alreadyShown = false;

  
  
  public MavenPomEditorPage(MavenPomEditor pomEditor, String id, String title) {
    super(pomEditor, id, title);
    this.pomEditor = pomEditor;
    this.inputHistory = new InputHistory(id);
    listener = new IModelStateListener() {
      public void modelResourceMoved(IStructuredModel oldModel, IStructuredModel newModel) {
      }
      public void modelResourceDeleted(IStructuredModel model) {
      }
      public void modelReinitialized(IStructuredModel structuredModel) {
      }
      public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) {
      }
      public void modelChanged(IStructuredModel model) {
        if (!updatingModel2) {
          loadData();
        }
      }
      public void modelAboutToBeReinitialized(IStructuredModel structuredModel) {
      }
      public void modelAboutToBeChanged(IStructuredModel model) {
      }
    };
    
  }
  
  public MavenPomEditor getPomEditor() {
    return pomEditor;
  }
  
  public final void performEditOperation(PomEdits.Operation operation, Logger logger, String logMessage) {
    try {
      updatingModel2 = true;
      PomEdits.performOnDOMDocument(new PomEdits.OperationTuple(getPomEditor().getDocument(), operation));
    } catch(Exception e) {
      logger.error(logMessage, e);
    } finally {
      updatingModel2 = false;
    }
  }

  @Override
  protected void createFormContent(IManagedForm managedForm) {
    ScrolledForm form = managedForm.getForm();
    IToolBarManager toolBarManager = form.getToolBarManager();

//    toolBarManager.add(pomEditor.showAdvancedTabsAction);
    
    selectParentAction = new Action(Messages.MavenPomEditorPage_action_open, MavenEditorImages.PARENT_POM) {
      public void run() {
        // XXX listen to parent modification and accordingly enable/disable action
        final Parent parent = model.getParent();
        if(parent!=null && !isEmpty(parent.getGroupId()) && !isEmpty(parent.getArtifactId()) && !isEmpty(parent.getVersion())) {
          new Job(Messages.MavenPomEditorPage_job_opening) {
            protected IStatus run(IProgressMonitor monitor) {
              OpenPomAction.openEditor(parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), monitor);
              return Status.OK_STATUS;
            }
          }.schedule();
        }
      }
    };
    toolBarManager.add(selectParentAction);
    updateParentAction();
    
    
    toolBarManager.add(new Action(Messages.MavenPomEditorPage_actio_refresh, MavenEditorImages.REFRESH) {
      public void run() {
        pomEditor.reload();
      }
    });
    
    form.updateToolBar();

    // compatibility proxy to support Eclipse 3.2
    FormUtils.decorateHeader(managedForm.getToolkit(), form.getForm());
    
    inputHistory.load();
  }
  
  public void setActive(boolean active) {
    super.setActive(active);
    
    doLoadData(active);
    if (active) {
      getPomEditor().getModel().addModelStateListener(listener);      
    } else {
      getPomEditor().getModel().removeModelStateListener(listener);      
    }
    if (active && alreadyShown) {
      loadData();
    } 
    alreadyShown  = true;
    
    //MNGECLIPSE-2674 checkreadonly is only calculated once, no need
    // to update everytime this page gets active
    boolean readOnly = pomEditor.checkReadOnly();
    if (readOnly) {
      // only perform when readonly==true, to prevent enabling all buttons on the page.
      FormUtils.setReadonly((Composite) getPartControl(), readOnly);
    }
  }

  public boolean isReadOnly() {
    return pomEditor.checkReadOnly();
  }
  
  private void doLoadData(boolean active) {
    try {
      if(active && !dataLoaded) {
        dataLoaded = true;
//      new Job("Loading pom.xml") {
//        protected IStatus run(IProgressMonitor monitor) {
        model = pomEditor.readProjectDocument();
        if(model != null) {
          if(getPartControl() != null) {
            getPartControl().getDisplay().asyncExec(new Runnable() {
              public void run() {
                updatingModel = true;
                try {
                  loadData();
                  updateParentAction();
                  registerListeners();
                } catch(Throwable e) {
                  LOG.error("Error loading data", e); //$NON-NLS-1$
                } finally {
                  updatingModel = false;
                }
              }
            });
          }
        }

      }
      
      //error markers have to be always updated..
      IFile pomFile = pomEditor.getPomFile();
      if(pomFile != null) {
        String text = "";  //$NON-NLS-1$
        IMarker[] markers = pomFile.findMarkers(IMavenConstants.MARKER_ID, true, IResource.DEPTH_ZERO);
        IMarker max = null;
        int maxSev = -1;
        if(markers != null) {
          for(IMarker mark : markers) {
            IMarker toAdd = max;
            int sev = mark.getAttribute(IMarker.SEVERITY, -1);
            if(sev > maxSev) {
              max = mark;
              maxSev = sev;
            } else {
              toAdd = mark;
            }
            if (toAdd != null) {
              //errors get prepended while warnings get appended.
              if (toAdd.getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR) {
                text = NLS.bind(Messages.MavenPomEditorPage_error_add, toAdd.getAttribute(IMarker.MESSAGE, "")) + text; //$NON-NLS-2$
              } else {
                text = text + NLS.bind(Messages.MavenPomEditorPage_warning_add, toAdd.getAttribute(IMarker.MESSAGE, ""));  //$NON-NLS-2$
              }
            }
          }
        }
        if(max != null) {
          String head; 
          String maxText = max.getAttribute(IMarker.MESSAGE, Messages.MavenPomEditorPage_error_unknown);
          if (text.length() > 0) {
            //if we have multiple errors
            text = NLS.bind(Messages.MavenPomEditorPage_add_desc,
                maxText, text);
            if (markers != null) {
              String number = new Integer(markers.length - 1).toString();
              head = NLS.bind(Messages.FormUtils_click_for_details2, maxText.length() > FormUtils.MAX_MSG_LENGTH ? maxText.substring(0, FormUtils.MAX_MSG_LENGTH) : maxText, number);
            } else {
              head = maxText;
              if (head.length() > FormUtils.MAX_MSG_LENGTH) {
                head = NLS.bind(Messages.FormUtils_click_for_details, head.substring(0, FormUtils.MAX_MSG_LENGTH));
              }
            }
          } else {
            //only this one
            text = maxText;
            head = maxText;
            if (head.length() > FormUtils.MAX_MSG_LENGTH) {
              head = NLS.bind(Messages.FormUtils_click_for_details, head.substring(0, FormUtils.MAX_MSG_LENGTH));
            }
          }
          int severity;
          switch(max.getAttribute(IMarker.SEVERITY, -1)) {
            case IMarker.SEVERITY_ERROR: {
              severity = IMessageProvider.ERROR;
              break;
            }
            case IMarker.SEVERITY_WARNING: {
              severity = IMessageProvider.WARNING;
              break;
            }
            case IMarker.SEVERITY_INFO: {
              severity = IMessageProvider.INFORMATION;
              break;
            }
            default: {
              severity = IMessageProvider.NONE;
            }
          }
          setErrorMessageForMarkers(head, text, severity, markers);
        } else {
          setErrorMessageForMarkers(null, null, IMessageProvider.NONE, new IMarker[0]);
        }
      }
    } catch(final CoreException ex) {
      LOG.error(ex.getMessage(), ex);
      final String msg = ex.getMessage();
      setErrorMessageForMarkers(msg, msg, IMessageProvider.ERROR, new IMarker[0]);
    }

  }
  
  private void setErrorMessageForMarkers(final String msg, final String tip, final int severity, final IMarker[] markers) {
    if (getPartControl() != null && !getPartControl().isDisposed()) {
      getPartControl().getDisplay().asyncExec(new Runnable() {
        public void run() {
          FormHoverProvider.Execute runnable = FormHoverProvider.createHoverRunnable(getManagedForm().getForm().getShell(), markers, getPomEditor().getSourcePage().getTextViewer());
          if (!getManagedForm().getForm().isDisposed()) {
            if (runnable != null) {
              FormUtils.setMessageWithPerformer(getManagedForm().getForm(), msg, severity, runnable);
            } else {
              FormUtils.setMessageAndTTip(getManagedForm().getForm(), msg, tip, severity);
            }
          }
        }
      });
    }
  }

  public void setErrorMessage(final String msg, final int severity) {
    if(getPartControl()!=null && !getPartControl().isDisposed()) {
      getPartControl().getDisplay().asyncExec(new Runnable() {
        public void run() {
          if (!getManagedForm().getForm().isDisposed()) {
            FormUtils.setMessage(getManagedForm().getForm(), msg, severity);
          }
        }
      });
    }
  }

  public Notifier getTarget() {
    return target;
  }

  public boolean isAdapterForType(Object type) {
    return false;
  }
  
  public void reload() {
    deRegisterListeners();
    boolean oldDataLoaded = dataLoaded;
    dataLoaded = false;
    doLoadData(oldDataLoaded);
  }

  public synchronized void notifyChanged(Notification notification) {
    if(updatingModel) {
      return;
    }
    
    updatingModel = true;
    try {
      switch(notification.getEventType()) {
        //TODO: fine-grained notification?
        case Notification.ADD:
        case Notification.MOVE:
        case Notification.REMOVE:
        case Notification.UNSET:
        case Notification.ADD_MANY: //this is for properties (clear/addAll is used for any properties update)
        case Notification.REMOVE_MANY:  
          if (getManagedForm() != null) {
            updateView(notification);
            updateParentAction();
          }
          break;
        case Notification.SET: {
          Object newValue = notification.getNewValue();
          Object oldValue = notification.getOldValue();
          if (newValue instanceof String && oldValue instanceof String && newValue.equals(oldValue)) {
            //the idea here is that triggering a view update for something that didn't change is not useful.
            //still there are other notifications that are similar (File>Revert or SCM team update seem to trigger
            // a complete reload of the model, which triggers a cloud of notification events..
            break;
          }
          if (getManagedForm() != null) {
            updateView(notification);
            updateParentAction();
          }
          break;
        }

        default:
          break;
          
        // case Notification.ADD_MANY:
        // case Notification.REMOVE_MANY:
      }

    } catch(Exception ex) {
      LOG.error("Can't update view", ex); //$NON-NLS-1$
    } finally {
      updatingModel = false;
    }
    
    registerListeners();
  }

  private void updateParentAction() {
    if (selectParentAction != null && model != null) {
      Parent par = model.getParent();
      if (par != null && par.getGroupId() != null && par.getArtifactId() != null && par.getVersion() != null) {
        selectParentAction.setEnabled(true);
      } else {
        selectParentAction.setEnabled(false);
      }
    }
  }
  
  /**
   * creates a text field/Ccombo decoration that shows the evaluated value 
   * @param control
   */
  public final void createEvaluatorInfo(final Control control) {
    if (!(control instanceof Text || control instanceof CCombo)) {
      throw new IllegalArgumentException("Not a Text or CCombo");
    }
    FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
        FieldDecorationRegistry.DEC_INFORMATION);
    final ControlDecoration decoration = new ControlDecoration(control, SWT.RIGHT | SWT.TOP) {

      /* (non-Javadoc)
       * @see org.eclipse.jface.fieldassist.ControlDecoration#getDescriptionText()
       */
      @Override
      public String getDescriptionText() {
        MavenProject mp = getPomEditor().getMavenProject();
        if (mp != null) {
          return FormUtils.simpleInterpolate(mp, control instanceof Text ? ((Text)control).getText() : ((CCombo)control).getText());
        }
        return "Cannot interpolate expressions, not resolvable file.";
      }
      
    };
    decoration.setShowOnlyOnFocus(false);
    decoration.setImage(fieldDecoration.getImage());
    decoration.setShowHover(true);
    decoration.hide(); //hide and wait for the value to be set.
    decoration.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        decoration.showHoverText(decoration.getDescriptionText());
      }
    });
    ModifyListener listener = new ModifyListener() {
      public void modifyText(ModifyEvent e) {
        String text = control instanceof Text ? ((Text)control).getText() : ((CCombo)control).getText();
        if (text.indexOf("${") != -1 && text.indexOf("}") != -1) {
          decoration.show();
        } else {
          decoration.hide();
        }
      }
    };
    if (control instanceof Text) {
      ((Text)control).addModifyListener(listener);
    } else {
      ((CCombo)control).addModifyListener(listener);
    }
    control.addMouseTrackListener(new MouseTrackListener() {
      public void mouseHover(MouseEvent e) {
        decoration.showHoverText(decoration.getDescriptionText());
      }
      
      public void mouseExit(MouseEvent e) {
        decoration.hideHover();
      }
      
      public void mouseEnter(MouseEvent e) {
      }
    });
  }  

  public void dispose() {
    inputHistory.save();
    getPomEditor().getModel().removeModelStateListener(listener);      
    
    deRegisterListeners();
    
    super.dispose();
  }

  public void setTarget(Notifier newTarget) {
    this.target = newTarget;
  }

  public Model getModel() {
    return model;
  }

  public abstract void loadData();

  public abstract void updateView(Notification notification);

  public void registerListeners() {
    if(model!=null) {
      doRegister(model);
      
      for(Iterator<?> it = model.eAllContents(); it.hasNext();) {
        Object next = it.next();
        if (next instanceof EObject)
          doRegister((EObject) next);
      }
    }
  }

  private void doRegister(EObject object) {
    if (!object.eAdapters().contains(this)) {
      object.eAdapters().add(this);
    }
  }

  public void deRegisterListeners() {
    if(model!=null) {
      model.eAdapters().remove(this);
      for(Iterator<?> it = model.eAllContents(); it.hasNext(); ) {
        Object next = it.next();
        if(next instanceof EObject) {
          EObject object = (EObject) next;
          object.eAdapters().remove(this);
        }
      }
    }
  }
  
  public void setElementValueProvider(Control control, ElementValueProvider provider) {
    control.setData(VALUE_PROVIDER, provider);
  }
  
  public void setModifyListener(final Control control) {
    Assert.isTrue(control instanceof CCombo || control instanceof Text || control instanceof Combo);
    
    ModifyListener ml = new ModifyListener() {
      String getText(Control control) {
        if (control instanceof Text) {
          return ((Text)control).getText(); 
        }
        if (control instanceof Combo) {
          return ((Combo)control).getText();
        }
        if (control instanceof CCombo) {
          return ((CCombo)control).getText();
        }
        throw new IllegalStateException();
      }
      
      public void modifyText(ModifyEvent e) {
        final ElementValueProvider provider = (ElementValueProvider) control.getData(VALUE_PROVIDER);
        if (provider == null) {
          throw new IllegalStateException("no value provider for " + control);
        }
        try {
          updatingModel2 = true;
          performOnDOMDocument(new OperationTuple(getPomEditor().getDocument(), new Operation() {
            public void process(Document document) {
              String text = getText(control);
              if (isEmpty(text) || text.equals(provider.getDefaultValue())) {
                //remove value
                Element el = provider.find(document);
                if (el != null) {
                  Node parent = el.getParentNode();
                  if (parent instanceof Element) {
                    removeChild((Element)parent, el);
                    removeIfNoChildElement((Element)parent);
                  }
                }
              } else {
                //set value and any parents..
                Element el = provider.get(document);
                setText(el, text);
              }
            }
          }));
        } catch(Exception e1) {
          LOG.error("Error updating document", e1);
        } finally {
          updatingModel2 = false;
        }
      }
    };
    control.setData(MODIFY_LISTENER, ml);
  }


  public void removeNotifyListener(Text control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.removeModifyListener(listener);
      }
    }
  }
  
  public void addNotifyListener(Text control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.addModifyListener(listener);
      }
    }
  }
    

  public void removeNotifyListener(CCombo control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.removeModifyListener(listener);
      }
    }
  }
  
  public void addNotifyListener(CCombo control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.addModifyListener(listener);
      }
    }
  }

  public void removeNotifyListener(Combo control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.removeModifyListener(listener);
      }
    }
  }
  
  public void addNotifyListener(Combo control) {
    if(!control.isDisposed()) {
      ModifyListener listener = (ModifyListener) control.getData(MODIFY_LISTENER);
      if (listener != null) {
        control.addModifyListener(listener);
      }
    }
  }

  public IMavenProjectFacade findModuleProject(String moduleName) {
    IFile pomFile = pomEditor.getPomFile();
    if(pomFile != null) {
      return findModuleProject(pomFile, moduleName);
    }
    return null;
  }

  private IMavenProjectFacade findModuleProject(IFile pomFile, String module) {
    IPath modulePath = pomFile.getParent().getLocation();
    if (modulePath == null) return null;
    modulePath = modulePath.append(module);
    //it's possible to have the pom file name in the module path..
    if (!modulePath.lastSegment().endsWith("pom.xml")) { //$NON-NLS-1$
      modulePath = modulePath.append("pom.xml"); //$NON-NLS-1$
    }
    MavenProjectManager projectManager = MavenPlugin.getDefault().getMavenProjectManager();
    IMavenProjectFacade[] facades = projectManager.getProjects();
    for(int i = 0; i < facades.length; i++ ) {
      if(facades[i].getPom().getLocation().equals(modulePath)) {
        return facades[i];
      }
    }
    return null;
  }
  
  public IFile findModuleFile(String moduleName) {
    IFile pomFile = pomEditor.getPomFile();
    if(pomFile!=null) {
      IPath modulePath = pomFile.getParent().getLocation();
      if (modulePath == null) return null;
      modulePath = modulePath.append(moduleName);
      //it's possible to have the pom file name in the module path..
      if (!modulePath.lastSegment().endsWith("pom.xml")) { //$NON-NLS-1$
        modulePath = modulePath.append("pom.xml"); //$NON-NLS-1$
      }
      IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(modulePath);
      return file;
    }
    return null;
  }
  
  public void initPopupMenu(Viewer viewer, String id) {
    MenuManager menuMgr = new MenuManager("#PopupMenu-" + id); //$NON-NLS-1$
    menuMgr.setRemoveAllWhenShown(true);
    
    Menu menu = menuMgr.createContextMenu(viewer.getControl());
  
    viewer.getControl().setMenu(menu);
    
    getEditorSite().registerContextMenu(MavenPomEditor.EDITOR_ID + id, menuMgr, viewer, false);
  }

  /*
   * returns added/removed/updated EObject from notification (convenience method for detail forms)
   */
  public static Object getFromNotification(Notification notification) {
    if(notification.getFeature() != null && !(notification.getFeature() instanceof EAttribute)) {
      // for structuralFeatures, return new value (for insert/delete)
      return notification.getNewValue();
    } else {
      // for attributes, return the notifier as it contains all new attributes (attribute modified)
      return notification.getNotifier();
    }
  }

  /**
   * Adapter for Text, Combo and CCombo widgets 
   */
  public interface TextAdapter {
    String getText();
    void addModifyListener(ModifyListener listener);
  }

  public IProject getProject() {
    IFile pomFile = pomEditor.getPomFile();
    return pomFile != null? pomFile.getProject(): null;
  }

  protected void addToHistory(Control control) {
    inputHistory.add(control);
  }

  /**
   * pages gets notified when cached effective model has changed.
   */
  public void mavenProjectHasChanged() {
  }
}

Back to the top