Debian Codegraph @

plugins/org.eclipse.emf.edit.ui/src/org/eclipse/emf/edit/ui/util/FindAndReplaceTarget.java

raw
1 /*
2 * Copyright (c) Eclipse contributors and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v2.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v20.html
7 */
8 package org.eclipse.emf.edit.ui.util;
9
10
11 import java.lang.reflect.Field;
12 import java.lang.reflect.Method;
13 import java.text.Collator;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.TreeMap;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import org.eclipse.core.runtime.IStatus;
29 import org.eclipse.core.runtime.Status;
30 import org.eclipse.emf.common.CommonPlugin;
31 import org.eclipse.emf.common.command.Command;
32 import org.eclipse.emf.common.command.CompoundCommand;
33 import org.eclipse.emf.common.ui.viewer.IStyledLabelDecorator;
34 import org.eclipse.emf.common.ui.viewer.IViewerProvider;
35 import org.eclipse.emf.ecore.EAttribute;
36 import org.eclipse.emf.ecore.EDataType;
37 import org.eclipse.emf.ecore.util.EcoreUtil;
38 import org.eclipse.emf.edit.command.SetCommand;
39 import org.eclipse.emf.edit.domain.EditingDomain;
40 import org.eclipse.emf.edit.domain.IEditingDomainProvider;
41 import org.eclipse.emf.edit.provider.IItemLabelProvider;
42 import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
43 import org.eclipse.emf.edit.provider.IItemPropertySource;
44 import org.eclipse.emf.edit.provider.ItemPropertyDescriptorDecorator;
45 import org.eclipse.emf.edit.ui.EMFEditUIPlugin;
46 import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
47 import org.eclipse.emf.edit.ui.action.FindAction;
48 import org.eclipse.emf.edit.ui.provider.DecoratingColumLabelProvider;
49 import org.eclipse.emf.edit.ui.provider.DelegatingStyledCellLabelProvider;
50 import org.eclipse.emf.edit.ui.provider.PropertyDescriptor;
51 import org.eclipse.emf.edit.ui.provider.PropertySource;
52 import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
53 import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage.ExtendedPropertySheetEntry;
54 import org.eclipse.jface.action.IAction;
55 import org.eclipse.jface.dialogs.Dialog;
56 import org.eclipse.jface.dialogs.IDialogSettings;
57 import org.eclipse.jface.text.IFindReplaceTarget;
58 import org.eclipse.jface.text.IFindReplaceTargetExtension;
59 import org.eclipse.jface.text.IFindReplaceTargetExtension3;
60 import org.eclipse.jface.text.IRegion;
61 import org.eclipse.jface.text.Region;
62 import org.eclipse.jface.viewers.CellLabelProvider;
63 import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
64 import org.eclipse.jface.viewers.IContentProvider;
65 import org.eclipse.jface.viewers.ILabelDecorator;
66 import org.eclipse.jface.viewers.ILabelProvider;
67 import org.eclipse.jface.viewers.ILabelProviderListener;
68 import org.eclipse.jface.viewers.ISelection;
69 import org.eclipse.jface.viewers.IStructuredContentProvider;
70 import org.eclipse.jface.viewers.IStructuredSelection;
71 import org.eclipse.jface.viewers.StructuredSelection;
72 import org.eclipse.jface.viewers.StructuredViewer;
73 import org.eclipse.jface.viewers.StyledString;
74 import org.eclipse.jface.viewers.StyledString.Styler;
75 import org.eclipse.jface.viewers.TreePath;
76 import org.eclipse.jface.viewers.Viewer;
77 import org.eclipse.swt.SWT;
78 import org.eclipse.swt.events.SelectionAdapter;
79 import org.eclipse.swt.events.SelectionEvent;
80 import org.eclipse.swt.graphics.Color;
81 import org.eclipse.swt.graphics.Font;
82 import org.eclipse.swt.graphics.FontData;
83 import org.eclipse.swt.graphics.Image;
84 import org.eclipse.swt.graphics.Point;
85 import org.eclipse.swt.graphics.Rectangle;
86 import org.eclipse.swt.graphics.TextStyle;
87 import org.eclipse.swt.layout.GridData;
88 import org.eclipse.swt.widgets.Button;
89 import org.eclipse.swt.widgets.Combo;
90 import org.eclipse.swt.widgets.Composite;
91 import org.eclipse.swt.widgets.Control;
92 import org.eclipse.swt.widgets.Display;
93 import org.eclipse.swt.widgets.Event;
94 import org.eclipse.swt.widgets.Listener;
95 import org.eclipse.swt.widgets.Shell;
96 import org.eclipse.swt.widgets.Text;
97 import org.eclipse.swt.widgets.Tree;
98 import org.eclipse.swt.widgets.TreeItem;
99 import org.eclipse.ui.IPartListener;
100 import org.eclipse.ui.IViewPart;
101 import org.eclipse.ui.IWorkbenchPage;
102 import org.eclipse.ui.IWorkbenchPart;
103 import org.eclipse.ui.IWorkbenchPartSite;
104 import org.eclipse.ui.PartInitException;
105 import org.eclipse.ui.part.IPage;
106 import org.eclipse.ui.part.WorkbenchPart;
107 import org.eclipse.ui.plugin.AbstractUIPlugin;
108 import org.eclipse.ui.views.properties.IPropertyDescriptor;
109 import org.eclipse.ui.views.properties.IPropertySource;
110 import org.eclipse.ui.views.properties.IPropertySourceProvider;
111 import org.eclipse.ui.views.properties.PropertySheet;
112 import org.eclipse.ui.views.properties.PropertySheetPage;
113 import org.eclipse.ui.views.properties.PropertySheetSorter;
114
115
116 /**
117 * An implementation of a find and replace target specialized to work with EMF Editors and EMF's {@link ExtendedPropertySheetPage}.
118 * Because platform internals are used, which are subject to arbitrary change, this class is final and the constructor is private.
119 * The only public entry point for creating an instance is {@link #getAdapter(Class, IWorkbenchPart, AbstractUIPlugin)}.
120 * <p>
121 * This find and replace target expects to be used by the platform's {@code org.eclipse.ui.texteditor.FindReplaceDialog},
122 * i.e., it reuses the same find and replace dialog that is used by the platform's text editors,
123 * specializing that dialog with addition controls, i.e., support for a {@link SearchType search type} control.
124 * </p>
125 * <p>
126 * To exploit this implementation, {@link FindAction create} a find action the constructor of a derived {@link EditingDomainActionBarContributor}
127 * and specialize the {@link WorkbenchPart#getAdapter(Class)} method in the editor implementation class to call the {@link #getAdapter(Class, IWorkbenchPart, AbstractUIPlugin) getAdapter} method of this class.
128 * This will result in the {@code Find/Replace...} appearing in the context menu and {@code Edit} menu, bound to the search hot key, generally {@code Ctrl-F},
129 * and will result in an instance of this class being created, bound to the viewers in your editor.
130 * But take note, this implementation's behavior is <b>invasive</b>, i.e., it replaces the label provider of the structure viewer with a wrapper label provider
131 * that is able to show boxes around the matching search text.
132 * <p>
133 * <p>
134 * If your content trees are potentially infinite, or you otherwise wish to control which parts of the tree are searched, you can specialize each structured viewer's {@link StructuredViewerTreeIterator}.
135 * If you have specialized property sheet's {@link PropertySheetPage#setSorter(PropertySheetSorter) sorter}, you must {@link #setCollator(Collator) set the collator} used by this implementation to sort properties and property categories.
136 * </p>
137 *
138 * @since 2.14
139 */
140 public final class FindAndReplaceTarget implements IFindReplaceTarget, IFindReplaceTargetExtension, IFindReplaceTargetExtension3
141 {
142 /**
143 * A map for managing the association between a workbench part and it associated find and replace target.
144 */
145 private static final Map<IWorkbenchPart, FindAndReplaceTarget> FIND_AND_REPLACE_TARGETS = new HashMap<IWorkbenchPart, FindAndReplaceTarget>();
146
147 /**
148 * A styler for drawing a box around matching text.
149 */
150 private static final Styler MATCH_STYLER = new Styler()
151 {
152 @Override
153 public void applyStyles(TextStyle textStyle)
154 {
155 textStyle.borderStyle = SWT.BORDER_SOLID;
156 }
157 };
158
159 /**
160 * Provides access to the {@code fIsRegExCheckBox} of a {@code org.eclipse.ui.texteditor.FindReplaceDialog}.
161 */
162 private static final Field F_IS_REGEX_CHECK_BOX_FIELD;
163
164 /**
165 * Provides access to the {@code fSelectedRangeRadioButton} of a {@code org.eclipse.ui.texteditor.FindReplaceDialog}.
166 */
167 private static final Field F_SELECTED_RANGE_RADIO_BUTTON_FIELD;
168
169 /**
170 * Provides access to the {@code fTarget} of a {@code org.eclipse.ui.texteditor.FindReplaceDialog}.
171 */
172 private static final Field F_TARGET_FIELD;
173
174 /**
175 * Provides access to the {@code findReplaceLogic} of a {@code org.eclipse.ui.texteditor.FindReplaceDialog}.
176 */
177 private static final Field FIND_REPLACE_LOGIC_FIELD;
178
179 static
180 {
181 Field fIsRegExCheckBoxField = null;
182 Field fSelectedRangeRadioButtonField = null;
183 Field fTarget = null;
184 Field findReplaceLogic = null;
185 try
186 {
187 Class<?> findReplaceDialogClass = CommonPlugin.loadClass("org.eclipse.ui.workbench.texteditor", "org.eclipse.ui.texteditor.FindReplaceDialog");
188 fIsRegExCheckBoxField = findReplaceDialogClass.getDeclaredField("fIsRegExCheckBox");
189 fIsRegExCheckBoxField.setAccessible(true);
190 fSelectedRangeRadioButtonField = findReplaceDialogClass.getDeclaredField("fSelectedRangeRadioButton");
191 fSelectedRangeRadioButtonField.setAccessible(true);
192 try
193 {
194 fTarget = findReplaceDialogClass.getDeclaredField("fTarget");
195 fTarget.setAccessible(true);
196 }
197 catch (Throwable throwable)
198 {
199 findReplaceLogic = findReplaceDialogClass.getDeclaredField("findReplaceLogic");
200 findReplaceLogic.setAccessible(true);
201 }
202 }
203 catch (Throwable throwable)
204 {
205 // Ignore.
206 }
207 F_IS_REGEX_CHECK_BOX_FIELD = fIsRegExCheckBoxField;
208 F_SELECTED_RANGE_RADIO_BUTTON_FIELD = fSelectedRangeRadioButtonField;
209 F_TARGET_FIELD = fTarget;
210 FIND_REPLACE_LOGIC_FIELD = findReplaceLogic;
211 }
212
213 /**
214 * We need a tiny font to produce a bit of white space in the labels.
215 * @see #hookLabelProvider()
216 */
217 private static final Map<Font, Font> TINY_FONT = new HashMap<Font, Font>();
218
219 /**
220 * A listener for when parts are closed to clean up the {@link #FIND_AND_REPLACE_TARGETS}.
221 * @see #getAdapter(Class, IWorkbenchPart, AbstractUIPlugin)
222 */
223 private static final IPartListener PART_LISTENER = new IPartListener()
224 {
225 public void partOpened(IWorkbenchPart part)
226 {
227 }
228
229 public void partDeactivated(IWorkbenchPart part)
230 {
231 }
232
233 public void partClosed(IWorkbenchPart part)
234 {
235 synchronized (FIND_AND_REPLACE_TARGETS)
236 {
237 FindAndReplaceTarget findAndReplaceTarget = FIND_AND_REPLACE_TARGETS.remove(part);
238 if (findAndReplaceTarget != null)
239 {
240 findAndReplaceTarget.dispose();
241 }
242 }
243 }
244
245 public void partBroughtToTop(IWorkbenchPart part)
246 {
247 }
248
249 public void partActivated(IWorkbenchPart part)
250 {
251 }
252 };
253
254 /**
255 * The workbench part of this find and replace target.
256 */
257 private final IWorkbenchPart workbenchPart;
258
259 /**
260 * The plugin used for saving and fetching the dialog settings of the find/replace dialog.
261 */
262 private final AbstractUIPlugin plugin;
263
264 /**
265 * The collator used to {@link org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.TextData#sort(List, Object) sort properties}.
266 */
267 Collator collator = Collator.getInstance();
268
269 /**
270 * A cleanup action for removing the paint lister from the properties view and for refreshing its labels.
271 *
272 * @see FindAndReplaceTarget#propertiesCleanup()
273 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
274 */
275 private Runnable propertiesCleanup;
276
277 /**
278 * A cleanup action for when the session ends.
279 *
280 * @see #addSearchTypeControl()
281 * @see #endSession()
282 */
283 private Runnable sessionCleanup;
284
285 /**
286 * A cleanup action for when the workbench part is disposed.
287 *
288 * @see #addSearchTypeControl()
289 * @see #dispose()
290 */
291 private Runnable disposeCleanup;
292
293 /**
294 * If an advanced property needs to be displayed for search results and that action is currently not checked,
295 * it will be checked and this cleanup action will be set to restore the state when the session ends.
296 *
297 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
298 */
299 private Runnable filterChangeCleanup;
300
301 /**
302 * Properties are always search assuming the are categorized.
303 * The properties view state will be changed to match, and if it was changed, this cleanup action will be set to restore the state when the session ends.
304 *
305 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
306 */
307 private Runnable categoriesChangeCleanup;
308
309 /**
310 * Set to the objects in the selection of the viewer by {@link #getLineSelection()} and used by {@link #setScope(IRegion)}.
311 */
312 private List<?> selectionScope;
313
314 /**
315 * Use to control the scope of all objects that will be searched.
316 */
317 private Set<Object> selectionScopeObjects;
318
319 /**
320 * Initialized with the initial text to search based on the text of whatever is select in whatever viewer is active.
321 */
322 private String selectionText;
323
324 /**
325 * The current selected item.
326 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
327 */
328 private Data.Item selectedItem;
329
330 /**
331 * The current selection start.
332 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
333 */
334 private int selectedItemStart;
335
336 /**
337 * The current pattern being selected.
338 * @see #setSelection(boolean, StructuredViewer, org.eclipse.emf.edit.ui.util.FindAndReplaceTarget.Data.Item, int, Pattern)
339 */
340 private Pattern selectedItemPattern;
341
342 /**
343 * The command for doing replace-all.
344 * @see #replaceSelectionAll(String, boolean)
345 * @see #setReplaceAllMode(boolean)
346 */
347 private CompoundCommand replaceAllCommand;
348
349 /**
350 * Used for processing all replacements.
351 */
352 private int pendingReplacements = -1;
353
354 /**
355 * Used to control whether replace-all is enabled. Of course you can only modify editable properties.
356 */
357 private boolean findReplaceable;
358
359 /**
360 * The types of things to search.
361 */
362 private FindAndReplaceTarget.SearchType searchType;
363
364 /**
365 * A tree item in the properties view that's currently being processed for search/replace.
366 */
367 private TreeItem specialTreeItem;
368
369 /**
370 * If the special tree item can't show the matching text, e.g., because there are control characters, this handles the display of the matching text.
371 */
372 private int specialStart;
373
374 /**
375 * This avoids changes in {@link #setScope(IRegion)} while the properties view is being made visible.
376 */
377 private boolean suspendScopeChanges;
378
379 /**
380 * Adapter the workbench part to an {@link IFindReplaceTarget}.
381 * @param adapter the adapter type; only {@code IFindReplaceTarget.class} will return a non-null result.
382 * @param workbenchPart the workbench part to adapt.
383 * @param plugin the plugin used for {@link AbstractUIPlugin#getDialogSettings() dialog settings}.
384 * @return a {@link FindAndReplaceTarget} or {@code null}.
385 */
386 public static <T> T getAdapter(Class<T> adapter, IWorkbenchPart workbenchPart, AbstractUIPlugin plugin)
387 {
388 if (adapter == IFindReplaceTarget.class)
389 {
390 synchronized (FindAndReplaceTarget.FIND_AND_REPLACE_TARGETS)
391 {
392 FindAndReplaceTarget findAndReplaceTarget = FindAndReplaceTarget.FIND_AND_REPLACE_TARGETS.get(workbenchPart);
393 if (findAndReplaceTarget == null)
394 {
395 workbenchPart.getSite().getPage().addPartListener(PART_LISTENER);
396 findAndReplaceTarget = new FindAndReplaceTarget(workbenchPart, plugin);
397 FindAndReplaceTarget.FIND_AND_REPLACE_TARGETS.put(workbenchPart, findAndReplaceTarget);
398 }
399 return adapter.cast(findAndReplaceTarget);
400 }
401 }
402 return null;
403 }
404
405 /**
406 * Creates an instance for the given workbench part and the plugin used for {@link AbstractUIPlugin#getDialogSettings() dialog settings}.
407 * @param workbenchPart the workbench part.
408 * @param plugin the plugin used for dialog settings.
409 */
410 private FindAndReplaceTarget(IWorkbenchPart workbenchPart, AbstractUIPlugin plugin)
411 {
412 this.workbenchPart = workbenchPart;
413 this.plugin = plugin;
414 }
415
416 /**
417 * Returns the collator used to sort properties and property categories.
418 * @return the collator used to sort properties and property categories.
419 */
420 public Collator getCollator()
421 {
422 return collator;
423 }
424
425 /**
426 * Sets the collator used to sort properties and property categories.
427 * @param collator the collator used to sort properties and property categories.
428 */
429 public void setCollator(Collator collator)
430 {
431 this.collator = collator;
432 }
433
434 /**
435 * Extracts the viewer from the workbench part.
436 */
437 protected StructuredViewer getViewer()
438 {
439 if (workbenchPart instanceof IViewerProvider)
440 {
441 IViewerProvider viewerProvider = (IViewerProvider)workbenchPart;
442 Viewer viewer = viewerProvider.getViewer();
443 if (viewer instanceof StructuredViewer)
444 {
445 return (StructuredViewer)viewer;
446 }
447 }
448
449 return null;
450 }
451
452 /**
453 * Returns the property sheet page of the workbench page's active property sheet.
454 */
455 protected ExtendedPropertySheetPage getActivePropertySheetPage()
456 {
457 IWorkbenchPart activePart = workbenchPart.getSite().getPage().getActivePart();
458 if (activePart instanceof PropertySheet)
459 {
460 PropertySheet propertySheet = (PropertySheet)activePart;
461 IPage currentPage = propertySheet.getCurrentPage();
462 if (currentPage instanceof ExtendedPropertySheetPage)
463 {
464 ExtendedPropertySheetPage propertySheetPage = (ExtendedPropertySheetPage)currentPage;
465 return propertySheetPage;
466 }
467 }
468
469 return null;
470 }
471
472 /**
473 * Returns the tree of the active property sheet page.
474 */
475 protected Tree getActivePropertySheetTree()
476 {
477 ExtendedPropertySheetPage propertySheetPage = getActivePropertySheetPage();
478 if (propertySheetPage != null)
479 {
480 Control control = propertySheetPage.getControl();
481 if (control instanceof Tree)
482 {
483 Tree tree = (Tree)control;
484 return tree;
485 }
486 }
487
488 return null;
489 }
490
491 public boolean isEditable()
492 {
493 // Editing is always supported.
494 // Replace is selectively disabled when a particular selection is not editable.
495 return true;
496 }
497
498 public boolean canPerformFind()
499 {
500 // As long as there is a viewer that has appropriate label and content providers, we can support find.
501 StructuredViewer viewer = getViewer();
502 return viewer != null && viewer.getLabelProvider() instanceof ILabelProvider && viewer.getContentProvider() instanceof IStructuredContentProvider;
503 }
504
505 /**
506 * Called by {@link #beginSession()} to populate the initial {@link #selectionText}.
507 */
508 protected void initialize(IWorkbenchPart workbenchPart)
509 {
510 // This method is called by the find and replace action before it opens the find and replace dialog.
511 // It has the opportunity to see the state before the find and replace dialog takes focus away.
512 // In particular, it can see the selected text in an active cell editor in the properties view.
513 StructuredViewer viewer = getViewer();
514 Tree propertySheetTree = getActivePropertySheetTree();
515 if (propertySheetTree != null)
516 {
517 // If there is an active property sheet with a tree, iterate over the selected tree items.
518 for (TreeItem treeItem : propertySheetTree.getSelection())
519 {
520 // Determine if there is an EMF property descriptor associated with it.
521 Collection<? extends PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(treeItem).keySet();
522 for (PropertyDescriptor propertyDescriptor : propertyDescriptors)
523 {
524 // If so, extract the object and look for it in the data.
525 Object object = propertyDescriptor.getObject();
526 for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
527 {
528 if (data.object == object)
529 {
530 // Look for the feature in the data items.
531 Object feature = getFeature(propertyDescriptor);
532 for (Data.Item item : data.items)
533 {
534 Object itemFeature = item.getFeature();
535 if (itemFeature == feature)
536 {
537 // If there is a focus text control, it must be the cell editor of this property.
538 Control control = workbenchPart.getSite().getShell().getDisplay().getFocusControl();
539 if (control instanceof Text)
540 {
541 // Extract the selected text, if any...
542 Text text = (Text)control;
543 selectionText = text.getSelectionText();
544 if (selectionText.length() > 0)
545 {
546 // Use this item's selected text as our initial selection.
547 Point selection = text.getSelection();
548 setSelection(true, viewer, item, selection.x, Pattern.compile(Pattern.quote(selectionText)));
549
550 // Then we're done.
551 return;
552 }
553 }
554
555 // Use this overall item as our initial selection.
556 setSelection(true, viewer, item, 0, Pattern.compile(Pattern.quote(item.value)));
557 return;
558 }
559 }
560
561 // Once we've passed the object of interest, there is nothing left to do.
562 break;
563 }
564 }
565 }
566 }
567 }
568 else
569 {
570 // Otherwise, use the first item selected in the viewer as our initial selection.
571 List<?> list = ((IStructuredSelection)viewer.getSelection()).toList();
572 for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
573 {
574 if (list.contains(data.object))
575 {
576 Data.Item item = data.items.get(0);
577 setSelection(true, viewer, item, 0, Pattern.compile(Pattern.quote(item.value)));
578 return;
579 }
580 }
581 }
582 }
583
584 public void beginSession()
585 {
586 initialize(workbenchPart);
587
588 // When the session start, we add our search-type control.
589 addSearchTypeControl();
590 }
591
592 /**
593 * Used to access the private fields of {@org.eclipse.ui.texteditor.FindReplaceDialog}.
594 */
595 private static Object getFieldValue(Dialog dialog, Field field)
596 {
597 try
598 {
599 return field.get(dialog);
600 }
601 catch (Exception exception)
602 {
603 return null;
604 }
605 }
606
607 /**
608 * Modifies the {@org.eclipse.ui.texteditor.FindReplaceDialog} to add our {@link SearchType search type controls}.
609 */
610 protected void addSearchTypeControl()
611 {
612 // Look through all child shells...
613 Shell workbenchShell = workbenchPart.getSite().getShell();
614 Shell[] shells = workbenchShell.getShells();
615 for (final Shell shell : shells)
616 {
617 // If this is a shell for the find and replace dialog...
618 Object data = shell.getData();
619 if (data instanceof Dialog && "org.eclipse.ui.texteditor.FindReplaceDialog".equals(data.getClass().getName()))
620 {
621 // Find the last checkbox in the dialog.
622 final Dialog dialog = (Dialog)data;
623 Object checkBox = getFieldValue(dialog, F_IS_REGEX_CHECK_BOX_FIELD);
624 if (checkBox instanceof Button)
625 {
626 // It should have grid data.
627 Button checkBoxButton = (Button)checkBox;
628 Object layoutData = checkBoxButton.getLayoutData();
629 if (layoutData instanceof GridData)
630 {
631 // Change it's span and alignment to make room for our additional control.
632 final GridData checkBoxGridData = (GridData)layoutData;
633 if (checkBoxGridData.horizontalSpan == 2)
634 {
635 checkBoxGridData.verticalAlignment = SWT.TOP;
636 checkBoxGridData.horizontalSpan = 1;
637 }
638
639 // Keep state in a section of our plugin's dialog settings.
640 IDialogSettings pluginDialogSettings = plugin.getDialogSettings();
641 final IDialogSettings dialogSettings = pluginDialogSettings.getSection("org.eclipse.ui.texteditor.FindReplaceDialog") == null
642 ? pluginDialogSettings.addNewSection("org.eclipse.ui.texteditor.FindReplaceDialog") : pluginDialogSettings.getSection("org.eclipse.ui.texteditor.FindReplaceDialog");
643
644 // Create a search-type combo in the same group as the checkbox.
645 final Composite group = checkBoxButton.getParent();
646 final Combo combo = new Combo(group, SWT.READ_ONLY | SWT.DROP_DOWN);
647 combo.setItems(SearchType.getLabels());
648 GridData gridData = new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1);
649 combo.setLayoutData(gridData);
650
651 // The initial choice is remembered from the dialog settings.
652 searchType = SearchType.getSearchType(dialogSettings.get("search-type"));
653 combo.select(searchType.ordinal());
654
655 // Listen for changes in the choice.
656 combo.addSelectionListener(new SelectionAdapter()
657 {
658 @Override
659 public void widgetSelected(SelectionEvent e)
660 {
661 // Not only remember the choice, but record it in the dialog settings.
662 searchType = SearchType.values()[combo.getSelectionIndex()];
663 dialogSettings.put("search-type", searchType.key());
664 }
665 });
666
667 String oldLabel = null;
668 Button selectedRangeButton = null;
669 Object selectedRange = getFieldValue(dialog, F_SELECTED_RANGE_RADIO_BUTTON_FIELD);
670 if (selectedRange instanceof Button)
671 {
672 selectedRangeButton = (Button)selectedRange;
673 String label = selectedRangeButton.getText();
674 if (label.endsWith("lines"))
675 {
676 oldLabel = label;
677 selectedRangeButton.setText(label.substring(0, label.length() - 5) + " elements");
678 }
679 }
680
681 // Relayout the shell.
682 shell.layout(true, true);
683
684 // If we've never checked that the default size of the dialog is big enough to fit our controls,
685 // do it this time.
686 if (!dialogSettings.getBoolean("resized"))
687 {
688 // Determine the bottom right corner location of the combo in absolute coordinates.
689 Rectangle comboBounds = combo.getBounds();
690 Point comboBottomRightLocation = group.toDisplay(comboBounds.x + comboBounds.width, comboBounds.y + comboBounds.height);
691
692 // Determine the bottom right corner location of the containing group in absolute coordinates.
693 Rectangle groupBounds = group.getBounds();
694 Point groupBottomRightLocation = group.getParent().toDisplay(groupBounds.x + groupBounds.width, groupBounds.y + groupBounds.height);
695
696 // Determine how much too small each dimension might be.
697 // If there is less that 8 pixes of padding in either direction...
698 int widthDelta = groupBottomRightLocation.x - comboBottomRightLocation.x;
699 int heightDelta = groupBottomRightLocation.y - comboBottomRightLocation.y;
700 if (widthDelta < 8 || heightDelta < 8)
701 {
702 // Increase the shell size so that the search-type combo fits nicely.
703 Point shellSize = shell.getSize();
704
705 if (widthDelta < 8)
706 {
707 shellSize.x -= widthDelta - 8;
708 }
709
710 if (heightDelta < 8)
711 {
712 shellSize.y -= heightDelta - 8;
713 }
714
715 shell.setSize(shellSize);
716 }
717
718 // Only do this once in this workspace.
719 dialogSettings.put("resized", true);
720 }
721
722 // Setup the task that needs to be done to undo what we've done here.
723 final String finalOldLabel = oldLabel;
724 final Button finalSelectRangeButton = selectedRangeButton;
725 sessionCleanup = new Runnable()
726 {
727 public void run()
728 {
729 // Restore the grid data and dispose our control.
730 checkBoxGridData.horizontalSpan = 2;
731 checkBoxGridData.verticalAlignment = SWT.CENTER;
732 combo.dispose();
733
734 // Clean up the label change that we did.
735 if (finalOldLabel != null)
736 {
737 finalSelectRangeButton.setText(finalOldLabel);
738 }
739
740 group.getDisplay().asyncExec(new Runnable()
741 {
742 public void run()
743 {
744 // Defer the layout so that when the editor is switched to another EMF editor that supports find and replace,
745 // we don't see a lot of flickering.
746 if (!group.isDisposed() && !shell.isDisposed())
747 {
748 shell.layout(true, true);
749 }
750 }
751 });
752
753 if (filterChangeCleanup != null)
754 {
755 filterChangeCleanup.run();
756 }
757
758 if (categoriesChangeCleanup != null)
759 {
760 categoriesChangeCleanup.run();
761 }
762
763 sessionCleanup = null;
764 }
765 };
766
767 disposeCleanup = new Runnable()
768 {
769 public void run()
770 {
771 // It may be the case that the properties view has focus and the editor being closed is the last one.
772 // The find-and-replace target is not updated in this case.
773 // So set it to null to ensure that the target is updated.
774 //
775 if (F_TARGET_FIELD != null)
776 {
777 Object fieldValue = getFieldValue(dialog, F_TARGET_FIELD);
778 if (fieldValue == FindAndReplaceTarget.this)
779 {
780 try
781 {
782 Method method = dialog.getClass().getMethod("updateTarget", IFindReplaceTarget.class, boolean.class, boolean.class);
783 method.setAccessible(true);
784 method.invoke(dialog, null, false, false);
785 }
786 catch (Exception exception)
787 {
788 // Ignore.
789 }
790 }
791 }
792 else
793 {
794 Object fieldValue = getFieldValue(dialog, FIND_REPLACE_LOGIC_FIELD);
795 try
796 {
797 Object target = FIND_REPLACE_LOGIC_FIELD.getType().getMethod("getTarget").invoke(fieldValue);
798 if (target == FindAndReplaceTarget.this)
799 {
800 fieldValue.getClass().getMethod("updateTarget", IFindReplaceTarget.class, boolean.class).invoke(fieldValue, null, false);
801 }
802 }
803 catch (Exception exception)
804 {
805 // Ignore.
806 }
807
808 }
809 disposeCleanup = null;
810 }
811 };
812 }
813 }
814 }
815 }
816 }
817
818 private void dispose()
819 {
820 if (disposeCleanup != null)
821 {
822 disposeCleanup.run();
823 }
824 }
825
826 public void endSession()
827 {
828 // When the session ends, we clean up or search-type control.
829 if (sessionCleanup != null)
830 {
831 sessionCleanup.run();
832 }
833
834 // Also do the clean that's done when the find and replace dialog loses focus.
835 setScope(null);
836 }
837
838 public Point getLineSelection()
839 {
840 // This method is used only to compute region to pass to setScope.
841 // So instead of computing something useless we use this opportunity to remember the viewer's selection.
842 StructuredViewer viewer = getViewer();
843 selectionScope = ((IStructuredSelection)viewer.getSelection()).toList();
844 return new Point(0, 0);
845 }
846
847 public IRegion getScope()
848 {
849 // This method is kind of useless, we remember our scope when the getLineSelection is called.
850 return new Region(0, 0);
851 }
852
853 public void setScope(IRegion scope)
854 {
855 // When the properties view is activated, it's sometimes given focus.
856 // In that case we restore the focus to the dialog, but we need to given the scope changes that are caused by the transient focus changes.
857 if (suspendScopeChanges)
858 {
859 return;
860 }
861
862 StructuredViewer viewer = getViewer();
863 if (scope == null)
864 {
865 // Remember the objects that need label updating.
866 Object[] selectionScopeObjectsToUpdate = selectionScopeObjects == null ? null : selectionScopeObjects.toArray();
867 Object selectionToUpdate = selectedItem != null && selectedItem.itemPropertyDescriptor == null ? selectedItem.data.object : null;
868
869 // The scope is set to null when the dialog loses focus.
870 // We should forget about most of our state at this point.
871 selectionText = null;
872 selectedItem = null;
873 findReplaceable = false;
874 selectionScopeObjects = null;
875
876 propertiesCleanup();
877
878 // Update update the selection scope objects.
879 if (selectionScopeObjectsToUpdate != null)
880 {
881 viewer.update(selectionScopeObjectsToUpdate, null);
882 }
883
884 // Update the selection object.
885 if (selectionToUpdate != null)
886 {
887 viewer.update(selectionToUpdate, null);
888 }
889 }
890 else
891 {
892 // Record the objects in the selection scope.
893 // These will be painted in a special way in the first to highlight them.
894 selectionScopeObjects = new HashSet<Object>();
895
896 int depth = -1;
897 for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
898 {
899 // If we hit the next object at the same depend, reset the depth.
900 if (data.depth == depth)
901 {
902 depth = -1;
903 }
904
905 // If the object is directly in scope.
906 if (selectionScope.contains(data.object))
907 {
908 // Remember the depth if we haven't remember one already.
909 if (depth == -1)
910 {
911 depth = data.depth;
912 }
913 }
914
915 // If the object is a selected object or nested under a selected object, include it.
916 if (depth != -1)
917 {
918 selectionScopeObjects.add(data.object);
919 }
920 }
921
922 // Hook up our decorating label provider for the current viewer.
923 hookLabelProvider();
924
925 // Eliminate the selection.
926 viewer.setSelection(StructuredSelection.EMPTY);
927 }
928 }
929
930 /**
931 * Handles the cleanup of the properties view.
932 * @see #propertiesCleanup
933 */
934 protected void propertiesCleanup()
935 {
936 // Clean up the stuff we did to the properties view.
937 if (propertiesCleanup != null)
938 {
939 propertiesCleanup.run();
940 }
941 }
942
943 public void setScopeHighlightColor(Color color)
944 {
945 // This is never called by the find and replace dialog.
946 }
947
948 public String getSelectionText()
949 {
950 // This method is called for three different reasons.
951 // 1 - For the initial text in the find field.
952 // 2 - For enabling the replace button.
953 // 3 - For recording a "selection" history; goodness knows what that's for though!
954 //
955 // If we're updating the button state, the selection text is used to enable/disable the replace button state.
956 // We want it enabled only if we've selected an editable property.
957 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
958 if ("updateButtonState".equals(stackTrace[2].getMethodName())
959 && (selectedItem == null || selectedItem.itemPropertyDescriptor == null || !selectedItem.itemPropertyDescriptor.canSetProperty(selectedItem.data.object)))
960 {
961 return "";
962 }
963
964 // We use this only to initialize the text selection from a cell editor.
965 // Once we've done a find, we clean this field.
966 if (selectionText != null)
967 {
968 return selectionText;
969 }
970
971 // If there is a selected item, return its value.
972 if (selectedItem != null)
973 {
974 return selectedItem.value;
975 }
976
977 // Otherwise we have no selection; we must return a non-null value.
978 return "";
979 }
980
981 public Point getSelection()
982 {
983 if (pendingReplacements >= 0)
984 {
985 return new Point(pendingReplacements, 0);
986 }
987
988 // This method is super important for determining the point from which the next find processing will proceed.
989 // If there is a selected item, we should proceed from the end of the current match.
990 if (selectedItem != null)
991 {
992 Matcher matcher = selectedItemPattern.matcher(selectedItem.value);
993 int size = 0;
994 if (selectedItem.value.length() >= selectedItemStart && matcher.find(selectedItemStart))
995 {
996 size = matcher.group().length();
997 }
998
999 Point point = new Point(selectedItem.index + selectedItemStart, size);
1000 return point;
1001 }
1002
1003 // If there is an active property sheet tree.
1004 StructuredViewer viewer = getViewer();
1005 Tree propertySheetTree = getActivePropertySheetTree();
1006 if (propertySheetTree != null)
1007 {
1008 // Look through the selection.
1009 for (final TreeItem treeItem : propertySheetTree.getSelection())
1010 {
1011 // If it has and EMF property descriptor
1012 Collection<? extends PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(treeItem).keySet();
1013 for (PropertyDescriptor propertyDescriptor : propertyDescriptors)
1014 {
1015 // Determine it's wrapped object and look for it in the induced text data.
1016 Object object = propertyDescriptor.getObject();
1017 for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
1018 {
1019 // If we find it...
1020 if (data.object == object)
1021 {
1022 // Determine which feature is the selected feature.
1023 Object feature = getFeature(propertyDescriptor);
1024
1025 // Collection all features before the selected feature.
1026 List<Object> features = new ArrayList<Object>();
1027 LOOP: for (final TreeItem otherTreeIem : propertySheetTree.getItems())
1028 {
1029 Collection<? extends PropertyDescriptor> otherPropertyDescriptors = getPropertyDescriptors(otherTreeIem).keySet();
1030 for (PropertyDescriptor otherPropertyDescriptor : otherPropertyDescriptors)
1031 {
1032 Object otherFeature = getFeature(otherPropertyDescriptor);
1033 features.add(otherFeature);
1034 if (otherFeature == feature)
1035 {
1036 break LOOP;
1037 }
1038 }
1039 }
1040
1041 // Consider all the items.
1042 Data.Item candidate = null;
1043 for (Data.Item item : data.items)
1044 {
1045 // If we find an exact match, return the information for it immediately, otherwise consider it a candidate.
1046 Object itemFeature = item.getFeature();
1047 if (itemFeature == feature)
1048 {
1049 return new Point(item.index, 0);
1050 }
1051 else if (features.contains(itemFeature))
1052 {
1053 candidate = item;
1054 }
1055 }
1056
1057 // If there is a candidate, return the information for it.
1058 if (candidate != null)
1059 {
1060 return new Point(candidate.index, 0);
1061 }
1062
1063 // If we find nothing, there's no point in looking anywhere else.
1064 break;
1065 }
1066 }
1067 }
1068 }
1069 }
1070
1071 // Otherwise find the first item of an object in the selection.
1072 List<?> list = ((IStructuredSelection)viewer.getSelection()).toList();
1073 for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
1074 {
1075 if (list.contains(data.object))
1076 {
1077 return new Point(data.items.get(0).index, 0);
1078 }
1079 }
1080
1081 // Start at the beginning.
1082 return new Point(0, 0);
1083 }
1084
1085 public void setSelection(int offset, int length)
1086 {
1087 // This method is always called right before setScope.
1088 // The information it provides is not useful and can be ignored.
1089 }
1090
1091 public int findAndSelect(int offset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord)
1092 {
1093 // This is never called, but we forward it sensibly anyway.
1094 return findAndSelect(offset, findString, searchForward, caseSensitive, wholeWord, false);
1095 }
1096
1097 public int findAndSelect(int offset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord, boolean regExSearch)
1098 {
1099 // Clear out the text used to populate the search text field once we've done a search.
1100 selectionText = null;
1101
1102 // Compile the raw pattern early so it can throw an exception if it's not well formed.
1103 // The information in that exception is displayed to the user.
1104 if (regExSearch)
1105 {
1106 Pattern.compile(findString);
1107 }
1108
1109 // A pattern will be constructed depending on the search parameters.
1110 String impliedPattern = findString;
1111
1112 // If we're not doing a regular expression search, quote the pattern.
1113 if (!regExSearch)
1114 {
1115 impliedPattern = Pattern.quote(impliedPattern);
1116 }
1117
1118 // If we want case-insensitive matching, encode that in the pattern.
1119 if (!caseSensitive)
1120 {
1121 impliedPattern = "(?i)" + impliedPattern;
1122 }
1123
1124 // If we want whole word matching, add the word break delimiters to the pattern.
1125 if (wholeWord)
1126 {
1127 impliedPattern = "\\b" + impliedPattern + "\\b";
1128 }
1129
1130 // This should always compile correctly.
1131 Pattern pattern = Pattern.compile(impliedPattern);
1132
1133 // If there are pending replacements, don't bother searching.
1134 if (pendingReplacements >= 0)
1135 {
1136 selectedItemPattern = pattern;
1137 return --pendingReplacements;
1138 }
1139
1140 StructuredViewer viewer = getViewer();
1141
1142 // Iterate over the induced text, keeping track of a candidates for the case of backward searching.
1143 Data.Item candidate = null;
1144 int candidateStart = -1;
1145 LOOP: for (FindAndReplaceTarget.Data data : new TextData(viewer, collator))
1146 {
1147 // If we have no restricted scope or the we and the object is in that scope...
1148 if (selectionScopeObjects == null || selectionScopeObjects.contains(data.object))
1149 {
1150 // Iterate over the items.
1151 for (Data.Item item : data.items)
1152 {
1153 // If we're searching forward and the item is at or above the offset or the end of the string is above the offset...
1154 // Otherwise if were's searching backward and the offset is -1, because we're wrapped, or the item is before the offset...
1155 if (searchForward ? item.index >= offset || item.index + item.value.length() > offset : offset == -1 || item.index < offset)
1156 {
1157 // If we've just done a replace, we make sure that the next find will find something that can be replaced, i.e., a modifiable attribute.
1158 // Otherwise we make sure that the item is included by the search type.
1159 if (findReplaceable ? !SearchType.MODIFIABLE_ATTRIBUTE.isIncluded(item) : searchType != null && !searchType.isIncluded(item))
1160 {
1161 continue;
1162 }
1163
1164 // When searching forward, we need to make sure that we begin the pattern match where it skips the stuff before the current offset.
1165 int begin = 0;
1166 if (searchForward && item.index < offset)
1167 {
1168 begin = offset - item.index;
1169 }
1170
1171 // Look for a match from the starting point.
1172 Matcher matcher = pattern.matcher(item.value);
1173 if (matcher.find(begin))
1174 {
1175 // Determine the offset of the match.
1176 int start = matcher.start();
1177
1178 if (searchForward)
1179 {
1180 // If we're searching forward, so record and mark this selection point.
1181 setSelection(false, viewer, item, start, pattern);
1182
1183 // Mark the fact that we've done a find but not a replace yet.
1184 findReplaceable = false;
1185
1186 // Return the appropriate absolute index where we matched.
1187 return item.index + start;
1188 }
1189 // Otherwise, if we're searching backward all the way to the end, or the match is not past the target offset...
1190 else if (offset == -1 || item.index + start <= offset)
1191 {
1192 // This is definitely a candidate.
1193 candidate = item;
1194 candidateStart = start;
1195
1196 // But keep searching for a better candidate later in the string.
1197 while (matcher.find())
1198 {
1199 // Repeat the same logic.
1200 start = matcher.start();
1201 if (offset == -1 || item.index + start <= offset)
1202 {
1203 candidate = item;
1204 candidateStart = start;
1205 }
1206 }
1207 }
1208 }
1209 }
1210 // If we're searching backward and we've gone as far as we need to go...
1211 else if (!searchForward && item.index > offset)
1212 {
1213 // Break from the loop.
1214 break LOOP;
1215 }
1216 }
1217 }
1218 }
1219
1220 // If there is a candidate (which is only possible if we're searching backwards...
1221 if (candidate != null)
1222 {
1223 // Record and mark this selection point.
1224 setSelection(false, viewer, candidate, candidateStart, pattern);
1225
1226 // Mark the fact that we've done a find but not a replace yet.
1227 findReplaceable = false;
1228
1229 // Return the appropriate absolute index where we matched.
1230 return candidate.index + candidateStart;
1231 }
1232
1233 // There is no match.
1234 return -1;
1235 }
1236
1237 /**
1238 * This records a match either initially or as a result of a find.
1239 */
1240 protected void setSelection(boolean preserve, StructuredViewer viewer, Data.Item item, final int start, Pattern pattern)
1241 {
1242 Object selectedObjectToUpdate = selectedItem != null && selectedItem.itemPropertyDescriptor == null ? selectedItem.data.object : null;
1243
1244 // Remember the information about the item, pattern, and offset within the item of the match.
1245 selectedItem = item;
1246 selectedItemPattern = pattern;
1247 selectedItemStart = start;
1248
1249 if (selectedObjectToUpdate != null)
1250 {
1251 viewer.update(selectedObjectToUpdate, null);
1252 }
1253
1254 // There is no special tree item anymore.
1255 specialTreeItem = null;
1256
1257 // If we haven't already done so, hook up the special label provider for providing selection feedback.
1258 hookLabelProvider();
1259
1260 // Clean any previous stuff we did to decorate the properties view.
1261 propertiesCleanup();
1262
1263 // In replace all mode, we don't want to provide any further feedback.
1264 if (replaceAllCommand == null)
1265 {
1266 // Select the item in the viewer, unless we're preserving the selection, i.e., during the initial feedback.
1267 ISelection selection = new StructuredSelection(new TreePath(item.data.getPath()));
1268 if (!preserve)
1269 {
1270 viewer.setSelection(selection, true);
1271 selection = viewer.getSelection();
1272
1273 // If there is an active property page, update its selection immediately.
1274 ExtendedPropertySheetPage activePropertySheetPage = getActivePropertySheetPage();
1275 if (activePropertySheetPage != null)
1276 {
1277 activePropertySheetPage.selectionChanged(workbenchPart, selection);
1278 }
1279 }
1280
1281 // Make the properties view visible, creating it if necessary.
1282 IWorkbenchPartSite site = workbenchPart.getSite();
1283 IWorkbenchPage page = site.getPage();
1284 IViewPart viewPart = page.findView("org.eclipse.ui.views.PropertySheet");
1285
1286 // Sometimes showing the properties view gives it focus, e.g., when the editor is maximized.
1287 Display display = site.getShell().getDisplay();
1288 Control oldFocusControl = display.getFocusControl();
1289 try
1290 {
1291 // Ignore scope changes while showing the properties view.
1292 suspendScopeChanges = true;
1293 if (item.itemPropertyDescriptor != null)
1294 {
1295 viewPart = page.showView("org.eclipse.ui.views.PropertySheet", null, IWorkbenchPage.VIEW_VISIBLE);
1296 if (viewPart == null)
1297 {
1298 viewPart = page.showView("org.eclipse.ui.views.PropertySheet", null, IWorkbenchPage.VIEW_CREATE);
1299 }
1300 }
1301
1302 // Restore the focus.
1303 Control newFocusControl = display.getFocusControl();
1304 if (oldFocusControl != newFocusControl)
1305 {
1306 oldFocusControl.setFocus();
1307 }
1308 }
1309 catch (PartInitException exception)
1310 {
1311 plugin.getLog().log(new Status(IStatus.WARNING, plugin.getBundle().getSymbolicName(), 0, exception.getLocalizedMessage(), null));
1312 }
1313 finally
1314 {
1315 suspendScopeChanges = false;
1316 }
1317
1318 // If it is a property sheet, as expected...
1319 if (viewPart instanceof PropertySheet)
1320 {
1321 // And the current page is a property sheet page as expected...
1322 final PropertySheet propertySheet = (PropertySheet)viewPart;
1323 IPage currentPage = propertySheet.getCurrentPage();
1324 if (currentPage instanceof ExtendedPropertySheetPage)
1325 {
1326 // And the control is a tree...
1327 Control control = currentPage.getControl();
1328 if (control instanceof Tree)
1329 {
1330 final Tree tree = (Tree)control;
1331
1332 if (item.itemPropertyDescriptor != null)
1333 {
1334 // If the property has filter flags...
1335 String[] filterFlags = item.itemPropertyDescriptor.getFilterFlags(item.data.object);
1336 if (filterFlags != null)
1337 {
1338 for (String filterFlag : filterFlags)
1339 {
1340 // If the filter is one for expert property...
1341 if ("org.eclipse.ui.views.properties.expert".equals(filterFlag))
1342 {
1343 final IAction action = ((ExtendedPropertySheetPage)currentPage).getFilterAction();
1344 if (!action.isChecked())
1345 {
1346 // Run the action to show advanced properties, and remember that.
1347 action.setChecked(true);
1348 action.run();
1349 filterChangeCleanup = new Runnable()
1350 {
1351 public void run()
1352 {
1353 action.setChecked(false);
1354 action.run();
1355 filterChangeCleanup = null;
1356 }
1357 };
1358 }
1359 }
1360 }
1361 }
1362
1363 // Remember the categories action that we need to ensure is checked because we search in an order that assumes this.
1364 final IAction categoriesAction = ((ExtendedPropertySheetPage)currentPage).getCategoriesAction();
1365 if (!categoriesAction.isChecked())
1366 {
1367 categoriesAction.setChecked(true);
1368 categoriesAction.run();
1369 categoriesChangeCleanup = new Runnable()
1370 {
1371 public void run()
1372 {
1373 categoriesAction.setChecked(false);
1374 categoriesAction.run();
1375 categoriesChangeCleanup = null;
1376 }
1377 };
1378 }
1379
1380 // Walk the tree items.
1381 for (TreeItem rootTreeItem : tree.getItems())
1382 {
1383 // If there is an EMF property descriptor with a feature for the selected item...
1384 Map<? extends PropertyDescriptor, TreeItem> propertyDescriptors = getPropertyDescriptors(rootTreeItem);
1385 for (Map.Entry<? extends PropertyDescriptor, TreeItem> entry : propertyDescriptors.entrySet())
1386 {
1387 PropertyDescriptor propertyDescriptor = entry.getKey();
1388 final TreeItem propertyDescriptorTreeItem = entry.getValue();
1389 if (propertyDescriptor.getFeature() == item.getFeature())
1390 {
1391 // Consider the label shown in the tree versus the value of the selected item...
1392 String treeItemText = propertyDescriptorTreeItem.getText(1);
1393 String itemValue = item.value;
1394
1395 // We might need to replace the tree item's text with a special representation...
1396 specialStart = -1;
1397
1398 // If they are're identical....
1399 if (!treeItemText.equals(itemValue))
1400 {
1401 // Find the match, which really must be there, do we can determine the length of the match.
1402 Matcher matcher = pattern.matcher(itemValue);
1403 if (matcher.find(start))
1404 {
1405 // Remember this special item, because we'll want to update it after we do a replace to show the replaced text.
1406 specialTreeItem = propertyDescriptorTreeItem;
1407
1408 // If the end of the match is after the end of the tree item's text, or the strings up until the end of the match are not
1409 // identical...
1410 int end = matcher.end();
1411 if (treeItemText.length() < end || !treeItemText.substring(0, end).equals(itemValue.substring(0, end)))
1412 {
1413 // Consider the starting point of the match, and work our way backward for 20 characters or until the preceding control
1414 // character.
1415 int begin = matcher.start();
1416 specialStart = 2;
1417 while (begin >= 0 && specialStart < 20 && !Character.isISOControl(itemValue.charAt(begin)))
1418 {
1419 ++specialStart;
1420 --begin;
1421 }
1422
1423 // Work our way forward until the end of the string or until we hit a control character.
1424 int itemValueLength = itemValue.length();
1425 while (end < itemValueLength && !Character.isISOControl(itemValue.charAt(end)))
1426 {
1427 ++end;
1428 }
1429
1430 // Create a special string with ellipses at both ends.
1431 String specialText = "..." + itemValue.substring(begin + 1, end) + "...";
1432
1433 // But that back into the item.
1434 propertyDescriptorTreeItem.setText(1, specialText);
1435
1436 // Get the tree to redraw itself.
1437 tree.redraw();
1438 }
1439 }
1440 }
1441
1442 // Create a paint listener to select the match.
1443 final Listener paintItemListener = new Listener()
1444 {
1445 private void paintItem(Event event, TreeItem item, int matchStart)
1446 {
1447 String text = item.getText(1);
1448 Matcher matcher = selectedItemPattern.matcher(text);
1449 if (matchStart < text.length() && matcher.find(matchStart))
1450 {
1451 // Compute the offset of the start of the matching, relative to the start of the text.
1452 int start = matcher.start();
1453 int x = event.gc.textExtent(text.substring(0, start)).x + item.getTextBounds(1).x - propertyDescriptorTreeItem.getBounds(1).x;
1454
1455 // Compute the offset at the end of the match, taking into account the width of the matching text.
1456 int width = event.gc.textExtent(matcher.group()).x;
1457 event.gc.drawRectangle(event.x + x + 1, event.y, width + 1, event.height - 1);
1458 }
1459 else if (text.endsWith("..."))
1460 {
1461 int x = event.gc.textExtent(text.substring(0, text.length() - 3)).x + propertyDescriptorTreeItem.getTextBounds(1).x
1462 - propertyDescriptorTreeItem.getBounds(1).x;
1463 int width = event.gc.textExtent("...").x;
1464 event.gc.drawRectangle(event.x + x + 1, event.y, width + 1, event.height - 1);
1465 }
1466 }
1467
1468 public void handleEvent(Event event)
1469 {
1470 // If we're painting or special item...
1471 TreeItem item = (TreeItem)event.item;
1472 if (item == propertyDescriptorTreeItem && event.index == 1)
1473 {
1474 paintItem(event, item, specialStart == -1 ? start : specialStart);
1475 }
1476 }
1477 };
1478
1479 // Add the listener.
1480 tree.addListener(SWT.PaintItem, paintItemListener);
1481
1482 // Set up the runnable to clean up what we've done here.
1483 final ExtendedPropertySheetPage propertySheetPage = (ExtendedPropertySheetPage)currentPage;
1484 propertiesCleanup = new Runnable()
1485 {
1486 public void run()
1487 {
1488 // Remove the listener.
1489 tree.removeListener(SWT.PaintItem, paintItemListener);
1490
1491 // Refresh the view.
1492 propertySheetPage.refreshLabels();
1493
1494 propertiesCleanup = null;
1495 }
1496 };
1497
1498 // Select the item, and force a repaint.
1499 tree.setSelection(propertyDescriptorTreeItem);
1500 tree.redraw();
1501
1502 // We're done.
1503 return;
1504 }
1505 }
1506 }
1507 }
1508
1509 // If we didn't find it at all, clear out the selection.
1510 tree.setSelection(new TreeItem [0]);
1511 }
1512 }
1513 }
1514 }
1515 }
1516
1517 /**
1518 * The styled text decorator used to show highlight box around the matching text in structured viewer's label.
1519 */
1520 protected final class StyledLabelDecorator implements IStyledLabelDecorator
1521 {
1522 private final ILabelProvider labelProvider;
1523
1524 // Use the color from the theme that the editor uses to highlight the scope.
1525 final Color color = workbenchPart.getSite().getWorkbenchWindow().getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry().get("org.eclipse.ui.editors.findScope");
1526
1527 final Styler scopeStyler = new Styler()
1528 {
1529 @Override
1530 public void applyStyles(TextStyle textStyle)
1531 {
1532 textStyle.background = color;
1533 }
1534 };
1535
1536 private final Styler tinyFontStyler;
1537
1538 private StyledLabelDecorator(ILabelProvider labelProvider, Styler tinyFontStyler)
1539 {
1540 this.labelProvider = labelProvider;
1541 this.tinyFontStyler = tinyFontStyler;
1542 }
1543
1544 public void removeListener(ILabelProviderListener listener)
1545 {
1546 labelProvider.removeListener(listener);
1547 }
1548
1549 public boolean isLabelProperty(Object element, String property)
1550 {
1551 return labelProvider.isLabelProperty(element, property);
1552 }
1553
1554 public void dispose()
1555 {
1556 labelProvider.dispose();
1557 }
1558
1559 public void addListener(ILabelProviderListener listener)
1560 {
1561 labelProvider.addListener(listener);
1562 }
1563
1564 public String decorateText(String text, Object element)
1565 {
1566 if (labelProvider instanceof ILabelDecorator)
1567 {
1568 ILabelDecorator labelDecorator = (ILabelDecorator)labelProvider;
1569 return labelDecorator.decorateText(text, element);
1570 }
1571
1572 return text;
1573 }
1574
1575 public Image decorateImage(Image image, Object element)
1576 {
1577 if (labelProvider instanceof ILabelDecorator)
1578 {
1579 ILabelDecorator labelDecorator = (ILabelDecorator)labelProvider;
1580 return labelDecorator.decorateImage(image, element);
1581 }
1582
1583 return image;
1584 }
1585
1586 public StyledString decorateStyledText(StyledString styledString, Object element)
1587 {
1588 if (labelProvider instanceof IStyledLabelDecorator)
1589 {
1590 IStyledLabelDecorator styledLabelDecorator = (IStyledLabelDecorator)labelProvider;
1591 styledString = styledLabelDecorator.decorateStyledText(styledString, element);
1592 }
1593
1594 // If we have a selected item, it's the item for the label, and this element is that selected element's object...
1595 if (selectedItem != null && selectedItem.itemPropertyDescriptor == null && element == selectedItem.data.object)
1596 {
1597 // Convert the styled string to just a string.
1598 String string = styledString.getString();
1599
1600 // Find the pattern match within that string.
1601 Matcher matcher = selectedItemPattern.matcher(string);
1602 if (matcher.find(selectedItemStart))
1603 {
1604 // Create a new styles string.
1605 StyledString result = new StyledString();
1606
1607 // Recompose the string with the match styled to show a selection box.
1608 String group = matcher.group();
1609 int start = matcher.start();
1610 int end = matcher.end();
1611 result.append(string.substring(0, start));
1612 Styler tinyPadding = new Styler()
1613 {
1614 @Override
1615 public void applyStyles(TextStyle textStyle)
1616 {
1617 MATCH_STYLER.applyStyles(textStyle);
1618 tinyFontStyler.applyStyles(textStyle);
1619 }
1620 };
1621 result.append(" ", tinyPadding);
1622 result.append(group, MATCH_STYLER);
1623 result.append(" ", tinyPadding);
1624 result.append(string.substring(end));
1625 result.append(" ", tinyFontStyler);
1626 return result;
1627 }
1628 }
1629
1630 // If we have scope objects and the element is one of those...
1631 if (selectionScopeObjects != null && selectionScopeObjects.contains(element))
1632 {
1633 // Mark the entire string with the scope styling.
1634 StyledString result = new StyledString();
1635 result.append(styledString.getString(), scopeStyler);
1636 result.append(" ", tinyFontStyler);
1637 return result;
1638 }
1639
1640 // Otherwise just pass through the string with a tiny bit of extra white space at the end.
1641 styledString.append(" ", tinyFontStyler);
1642 return styledString;
1643 }
1644 }
1645
1646 /**
1647 * We use this special class so we can detect if the label provider is already hooked up.
1648 */
1649 protected static class DecoratingLabelProvider extends DelegatingStyledCellLabelProvider.FontAndColorProvider implements IStyledLabelProvider
1650 {
1651 public DecoratingLabelProvider(IStyledLabelProvider styledLabelProvider)
1652 {
1653 super(styledLabelProvider);
1654 }
1655
1656 @Override
1657 public StyledString getStyledText(Object element)
1658 {
1659 return super.getStyledText(element);
1660 }
1661 }
1662
1663 /**
1664 * This sets up a special label provider in the viewer to be able to highlight the scope and show the selected match.
1665 */
1666 protected void hookLabelProvider()
1667 {
1668 final StructuredViewer viewer = getViewer();
1669
1670 // Create a very tiny font that can be used to make very tiny spaces.
1671 Font font = viewer.getControl().getFont();
1672 Font tinyFont = TINY_FONT.get(font);
1673 if (tinyFont == null)
1674 {
1675 FontData[] fontData = font.getFontData();
1676 for (FontData data : fontData)
1677 {
1678 data.setHeight(data.getHeight() / 4);
1679 }
1680 tinyFont = new Font(font.getDevice(), fontData);
1681 TINY_FONT.put(font, tinyFont);
1682 }
1683
1684 // If the label provider is already hooked up...
1685 final ILabelProvider labelProvider = (ILabelProvider)viewer.getLabelProvider();
1686 if (labelProvider instanceof DecoratingLabelProvider)
1687 {
1688 // Update the selection scope objects.
1689 if (selectionScopeObjects != null)
1690 {
1691 viewer.update(selectionScopeObjects.toArray(), null);
1692 }
1693
1694 // Update the selected object if it's for a label.
1695 if (selectedItem != null && selectedItem.itemPropertyDescriptor == null)
1696 {
1697 viewer.update(selectedItem.data.object, null);
1698 }
1699 }
1700 else
1701 {
1702 // Create a styler for creating very small spaces.
1703 final Font finalTinyFont = tinyFont;
1704 Styler tinyFontStyler = new Styler()
1705 {
1706 @Override
1707 public void applyStyles(TextStyle textStyle)
1708 {
1709 textStyle.font = finalTinyFont;
1710 }
1711 };
1712 // Create a styled label provider that can decorate the text.
1713 IStyledLabelProvider styledProvider = new DecoratingColumLabelProvider.StyledLabelProvider(labelProvider, new StyledLabelDecorator(labelProvider, tinyFontStyler))
1714 {
1715 {
1716 if (labelProvider instanceof CellLabelProvider)
1717 {
1718 cellLabelProvider = (CellLabelProvider)labelProvider;
1719 }
1720 }
1721 };
1722
1723 // Hook up the label provider to be the one used by the view.
1724 ILabelProvider delegatingLabelProvider = new DecoratingLabelProvider(styledProvider);
1725 viewer.setLabelProvider(delegatingLabelProvider);
1726 }
1727 }
1728
1729 public void replaceSelection(String text)
1730 {
1731 // This is never called, but delegate it appropriately nevertheless.
1732 replaceSelection(text, false);
1733 }
1734
1735 public void replaceSelection(String text, boolean regExReplace)
1736 {
1737 // If we're in replace all mode.
1738 if (replaceAllCommand != null)
1739 {
1740 // And this is the first call to replace selection...
1741 if (pendingReplacements == Integer.MAX_VALUE - 1)
1742 {
1743 // Determine all the replacements that are applicable.
1744 pendingReplacements = replaceSelectionAll(text, regExReplace) - 1;
1745 }
1746
1747 // Both find and replace will ignore the next pendingReplacements number of calls.
1748 return;
1749 }
1750
1751 // If the selected item can't be modified...
1752 if (!SearchType.MODIFIABLE_ATTRIBUTE.isIncluded(selectedItem))
1753 {
1754 return;
1755 }
1756
1757 // If the pattern doesn't match...
1758 Matcher matcher = selectedItemPattern.matcher(selectedItem.value);
1759 if (!matcher.find(selectedItemStart))
1760 {
1761 return;
1762 }
1763
1764 // Build up the replacement.
1765 StringBuffer result = new StringBuffer();
1766
1767 // Remember the start of the match...
1768 int start = matcher.start();
1769
1770 // Escape the $ if we're not doing a regular expression replacement.
1771 String replacement = regExReplace ? text : text.replace("$", "\\$");
1772
1773 // Append the replacement
1774 matcher.appendReplacement(result, replacement);
1775
1776 // Remember exactly what we've replaced the pattern with.
1777 String actualReplacement = result.substring(start);
1778
1779 // Complete the composition.
1780 matcher.appendTail(result);
1781
1782 // We must have an editing domain and the selected item's feature must be a modifiable attribute.
1783 EditingDomain domain = ((IEditingDomainProvider)workbenchPart).getEditingDomain();
1784 EAttribute eAttribute = (EAttribute)selectedItem.getFeature();
1785
1786 // Try to convert the value modified string to a value; this can fail.
1787 Object value;
1788 try
1789 {
1790 value = EcoreUtil.createFromString(eAttribute.getEAttributeType(), result.toString());
1791 }
1792 catch (RuntimeException exception)
1793 {
1794 return;
1795 }
1796
1797 // If there is a special item in the properties view, we want to update the text to show the replacement.
1798 String replacementSpecialText = null;
1799 if (specialTreeItem != null && !specialTreeItem.isDisposed())
1800 {
1801 String specialText = specialTreeItem.getText(1);
1802 Matcher specialMatcher = selectedItemPattern.matcher(specialText);
1803 if (specialMatcher.find(specialStart))
1804 {
1805 StringBuffer specialResult = new StringBuffer();
1806 specialMatcher.appendReplacement(specialResult, replacement);
1807 specialMatcher.appendTail(specialResult);
1808 replacementSpecialText = specialResult.toString();
1809 }
1810 }
1811
1812 // Remember the replacement as the pattern so that views showing the matching selection continue to show the matching replacement.
1813 selectedItemPattern = Pattern.compile(Pattern.quote(actualReplacement));
1814
1815 Command setCommand;
1816 if (eAttribute.isMany())
1817 {
1818 Object propertyValue = selectedItem.itemPropertyDescriptor.getPropertyValue(selectedItem.data.object);
1819 if (propertyValue instanceof IItemPropertySource)
1820 {
1821 propertyValue = ((IItemPropertySource)propertyValue).getEditableValue(selectedItem.data.object);
1822 }
1823
1824 // Compute the new overall value for the list.
1825 List<Object> values = new ArrayList<Object>((List<?>)propertyValue);
1826 values.set(selectedItem.itemIndex, value);
1827
1828 // Create a command to set the overall list value.
1829 setCommand = SetCommand.create(domain, selectedItem.data.object, eAttribute, values);
1830 }
1831 else
1832 {
1833 // Create a command to set the value.
1834 setCommand = SetCommand.create(domain, selectedItem.data.object, eAttribute, value);
1835 }
1836
1837 // If this is not in replace all mode, we need to be careful that command execution will cause notification that will try to select the affected
1838 // objects.
1839 // This messes up or attempts to track the selection progress in the case of replace/find.
1840 CompoundCommand wrapper = new CompoundCommand(CompoundCommand.MERGE_COMMAND_ALL)
1841 {
1842 boolean isFirst = true;
1843
1844 @Override
1845 public Collection<?> getAffectedObjects()
1846 {
1847 // The first time this is called, it returns the empty list, so that no selection takes place.
1848 if (isFirst)
1849 {
1850 isFirst = false;
1851 return Collections.emptyList();
1852 }
1853
1854 return super.getAffectedObjects();
1855 }
1856 };
1857
1858 // Put the set command in the wrapper and execute the wrapper.
1859 wrapper.append(setCommand);
1860 domain.getCommandStack().execute(wrapper);
1861
1862 // We need to wait for async executed updates to finish.
1863 Display display = getViewer().getControl().getShell().getDisplay();
1864 final boolean[] run = new boolean []{ true };
1865 display.asyncExec(new Runnable()
1866 {
1867 public void run()
1868 {
1869 run[0] = false;
1870 }
1871 });
1872
1873 // Process the event queue until our runnable has run, at which point other runnables queued before ours will also have been completed.
1874 while (run[0] && display.readAndDispatch())
1875 {
1876 display.sleep();
1877 }
1878
1879 // If we have a special item.
1880 if (specialTreeItem != null)
1881 {
1882 // And it's not disposed yet.
1883 if (!specialTreeItem.isDisposed() && replacementSpecialText != null)
1884 {
1885 // Update it to the replacement text, and force it to repaint to highlight the replacement.
1886 specialTreeItem.setText(1, replacementSpecialText);
1887 specialTreeItem.getParent().redraw();
1888 }
1889
1890 // We can forget about it now.
1891 specialTreeItem = null;
1892 }
1893
1894 // It's important to relocate our selected item, because the replacement could have updated text that appears earlier in our induced text view.
1895 // This would mess up the current selected item's index.
1896 for (FindAndReplaceTarget.Data data : new TextData(getViewer(), collator))
1897 {
1898 if (data.object == selectedItem.data.object)
1899 {
1900 for (Data.Item item : data.items)
1901 {
1902 if (selectedItem.itemPropertyDescriptor == item.itemPropertyDescriptor && selectedItem.itemIndex == item.itemIndex)
1903 {
1904 selectedItem = item;
1905 }
1906 }
1907 }
1908 }
1909
1910 // We want the next find (especially for find/replace) to find only modifiable selections.
1911 findReplaceable = true;
1912 }
1913
1914 /**
1915 * Use to help process all matches to be replaced.
1916 * @see #replaceSelection(String, boolean)
1917 */
1918 protected int replaceSelectionAll(String text, boolean regExReplace)
1919 {
1920 // Escape the $ if we're not doing a regular expression replacement.
1921 String replacement = regExReplace ? text : text.replace("$", "\\$");
1922
1923 // We must have an editing domain.
1924 EditingDomain domain = ((IEditingDomainProvider)workbenchPart).getEditingDomain();
1925
1926 int total = 0;
1927 for (Data data : new TextData(getViewer(), collator))
1928 {
1929 // We must defer creation of the set command for a multi-valued feature until after all its items are processed.
1930 EAttribute currentListAttribute = null;
1931 List<Object> currentListValue = null;
1932
1933 for (Data.Item item : data.items)
1934 {
1935 // If the selected item can't be modified...
1936 if (!SearchType.MODIFIABLE_ATTRIBUTE.isIncluded(item))
1937 {
1938 continue;
1939 }
1940
1941 // If the pattern doesn't match...
1942 Matcher matcher = selectedItemPattern.matcher(item.value);
1943 if (!matcher.find())
1944 {
1945 continue;
1946 }
1947
1948 // Build up the replacement.
1949 StringBuffer result = new StringBuffer();
1950
1951 // Keep track of the number of matches.
1952 int count = 0;
1953 do
1954 {
1955 // Append the replacement
1956 matcher.appendReplacement(result, replacement);
1957 ++count;
1958 }
1959 while (matcher.find());
1960
1961 // Complete the composition.
1962 matcher.appendTail(result);
1963
1964 // The feature must be an attribute.
1965 EAttribute eAttribute = (EAttribute)item.getFeature();
1966
1967 // If we've deferred a multi-valued feature change, and this is a different feature
1968 if (currentListAttribute != null && eAttribute != currentListAttribute)
1969 {
1970 Command setCommand = SetCommand.create(domain, data.object, currentListAttribute, currentListValue);
1971 replaceAllCommand.append(setCommand);
1972
1973 currentListAttribute = null;
1974 currentListValue = null;
1975 }
1976
1977 // Try to convert the modified string to a value; this can fail.
1978 Object value;
1979 try
1980 {
1981 value = EcoreUtil.createFromString(eAttribute.getEAttributeType(), result.toString());
1982 }
1983 catch (RuntimeException exception)
1984 {
1985 continue;
1986 }
1987
1988 total += count;
1989
1990 if (eAttribute.isMany())
1991 {
1992 if (currentListValue == null)
1993 {
1994 currentListAttribute = eAttribute;
1995
1996 Object propertyValue = item.itemPropertyDescriptor.getPropertyValue(data.object);
1997 if (propertyValue instanceof IItemPropertySource)
1998 {
1999 propertyValue = ((IItemPropertySource)propertyValue).getEditableValue(data.object);
2000 }
2001
2002 // Compute the new overall value for the list.
2003 currentListValue = new ArrayList<Object>((List<?>)propertyValue);
2004 }
2005
2006 currentListValue.set(item.itemIndex, value);
2007 }
2008 else
2009 {
2010 // Create a command to set the value.
2011 Command setCommand = SetCommand.create(domain, data.object, eAttribute, value);
2012 replaceAllCommand.append(setCommand);
2013 }
2014 }
2015
2016 // If we've deferred a multi-valued feature change and it's not been processed in the above loop.
2017 if (currentListAttribute != null)
2018 {
2019 Command setCommand = SetCommand.create(domain, data.object, currentListAttribute, currentListValue);
2020 replaceAllCommand.append(setCommand);
2021 }
2022 }
2023
2024 return total;
2025 }
2026
2027 public void setReplaceAllMode(boolean replaceAll)
2028 {
2029 if (replaceAll)
2030 {
2031 // We want the next find to find only modifiable selections.
2032 findReplaceable = true;
2033
2034 // We want all the commands to be batched into a single undoable command.
2035 replaceAllCommand = new CompoundCommand(CompoundCommand.MERGE_COMMAND_ALL, "Replace All")
2036 {
2037 };
2038 pendingReplacements = Integer.MAX_VALUE;
2039 }
2040 else
2041 {
2042 try
2043 {
2044 // We must have an editing domain.
2045 EditingDomain domain = ((IEditingDomainProvider)workbenchPart).getEditingDomain();
2046 domain.getCommandStack().execute(replaceAllCommand);
2047 }
2048 finally
2049 {
2050 // We're done now.
2051 findReplaceable = false;
2052 replaceAllCommand = null;
2053 pendingReplacements = -1;
2054 }
2055 }
2056 }
2057
2058 /**
2059 * Exacts the textual representation of the attribute-based property descriptor.
2060 * Returns <code>null</code> if the property is not attribute-based, or if the value is not representable as text.
2061 */
2062 protected static List<String> getText(IItemPropertyDescriptor itemPropertyDescriptor, Object object)
2063 {
2064 if (itemPropertyDescriptor instanceof ItemPropertyDescriptorDecorator)
2065 {
2066 ItemPropertyDescriptorDecorator itemPropertyDescriptorDecorator = (ItemPropertyDescriptorDecorator)itemPropertyDescriptor;
2067 return getText(itemPropertyDescriptorDecorator.getDecoratedItemPropertyDescriptor(), itemPropertyDescriptorDecorator.getDecoratedObject());
2068 }
2069
2070 List<String> result = new ArrayList<String>();
2071
2072 // Extract the property value and unwrap it if necessary.
2073 Object propertyValue = itemPropertyDescriptor.getPropertyValue(object);
2074 if (propertyValue instanceof IItemPropertySource)
2075 {
2076 propertyValue = ((IItemPropertySource)propertyValue).getEditableValue(object);
2077 }
2078
2079 // If the feature is an attribute...
2080 Object feature = itemPropertyDescriptor.getFeature(object);
2081 if (feature instanceof EAttribute)
2082 {
2083 // If the attribute's type is serializeable...
2084 EAttribute eAttribute = (EAttribute)feature;
2085 EDataType eDataType = eAttribute.getEAttributeType();
2086 if (eDataType.isSerializable())
2087 {
2088 // If there is a value.
2089 if (propertyValue != null)
2090 {
2091 boolean useLabel = false;
2092 // Always create a list.
2093 if (eAttribute.isMany() && propertyValue instanceof List<?>)
2094 {
2095 // Add the textual representation of each value.
2096 for (Object item : (List<?>)propertyValue)
2097 {
2098 try
2099 {
2100 result.add(EcoreUtil.convertToString(eDataType, item));
2101 }
2102 catch (Exception exception)
2103 {
2104 useLabel = true;
2105 break;
2106 }
2107 }
2108 }
2109 else
2110 {
2111 // Add the textual representation of the one value.
2112 try
2113 {
2114 result.add(EcoreUtil.convertToString(eDataType, propertyValue));
2115 }
2116 catch (RuntimeException exception)
2117 {
2118 useLabel = true;
2119 }
2120 }
2121
2122 if (!useLabel)
2123 {
2124 // return result;
2125 }
2126 }
2127 }
2128 }
2129
2130 // Use the label as displayed in the properties view's value column.
2131 IItemLabelProvider labelProvider = itemPropertyDescriptor.getLabelProvider(object);
2132 if (labelProvider != null && propertyValue != null)
2133 {
2134 // Make sure it's not duplicated text.
2135 String text = labelProvider.getText(propertyValue);
2136 for (String otherText : result)
2137 {
2138 if (otherText.contains(text))
2139 {
2140 return result;
2141 }
2142 }
2143 result.add(text);
2144 }
2145
2146 return result;
2147 }
2148
2149 /**
2150 * Returns the EMF property descriptors, mapped to the corresponding the tree item.
2151 * It will walked nested properties and property categories.
2152 */
2153 protected static Map<? extends PropertyDescriptor, TreeItem> getPropertyDescriptors(TreeItem treeItem)
2154 {
2155 Map<PropertyDescriptor, TreeItem> result = new LinkedHashMap<PropertyDescriptor, TreeItem>();
2156 Object data = treeItem.getData();
2157 if (data instanceof ExtendedPropertySheetEntry)
2158 {
2159 ExtendedPropertySheetEntry propertySheetEntry = (ExtendedPropertySheetEntry)data;
2160 IPropertyDescriptor descriptor = propertySheetEntry.getDescriptor();
2161 if (descriptor instanceof PropertyDescriptor)
2162 {
2163 PropertyDescriptor propertyDescriptor = (PropertyDescriptor)descriptor;
2164 result.put(propertyDescriptor, treeItem);
2165 if (treeItem.getItemCount() != 0)
2166 {
2167 // Force the content provider to create the child items without actually expanding the tree.
2168 Event event = new Event();
2169 event.item = treeItem;
2170 treeItem.getParent().notifyListeners(SWT.Expand, event);
2171
2172 for (TreeItem childItem : treeItem.getItems())
2173 {
2174 result.putAll(getPropertyDescriptors(childItem));
2175 }
2176 }
2177 }
2178 }
2179 else
2180 {
2181 for (TreeItem childTreeItem : treeItem.getItems())
2182 {
2183 result.putAll(getPropertyDescriptors(childTreeItem));
2184 }
2185 }
2186 return result;
2187 }
2188
2189 /**
2190 * Returns the feature of item property descriptor of the EMF property descriptor.
2191 */
2192 protected static Object getFeature(PropertyDescriptor propertyDescriptor)
2193 {
2194 Object object = propertyDescriptor.getObject();
2195 IItemPropertyDescriptor itemPropertyDescriptor = propertyDescriptor.getItemPropertyDescriptor();
2196 return itemPropertyDescriptor.getFeature(object);
2197 }
2198
2199 /**
2200 * This represents an element associated with each object in a tree.
2201 * @see TextData
2202 */
2203 protected static class Data
2204 {
2205 /**
2206 * The object in the tree.
2207 */
2208 public Object object;
2209
2210 /**
2211 * The depth of the object in the tree.
2212 */
2213 public int depth;
2214
2215 /**
2216 * The parent data in the tree.
2217 */
2218 public Data parent;
2219
2220 /**
2221 * The items associated with the object.
2222 */
2223 public List<Data.Item> items;
2224
2225 public Data(int depth, Object object, List<Data.Item> items)
2226 {
2227 this.depth = depth;
2228 this.object = object;
2229 this.items = items;
2230 }
2231
2232 public Object[] getPath()
2233 {
2234 List<Object> path = new ArrayList<Object>();
2235 for (Data data = this; data != null; data = data.parent)
2236 {
2237 path.add(0, data.object);
2238 }
2239
2240 return path.toArray();
2241 }
2242
2243 /**
2244 * This represents an item associated with each data item.
2245 */
2246 protected static class Item
2247 {
2248 /**
2249 * The containing data of this item.
2250 */
2251 public FindAndReplaceTarget.Data data;
2252
2253 /**
2254 * The index of this item in the overall {@link TextData induced} textual representation.
2255 */
2256 public int index;
2257
2258 /**
2259 * The property descriptor associated with this item.
2260 * The <code>null</value> represents the label value of the data object.
2261 */
2262 public IItemPropertyDescriptor itemPropertyDescriptor;
2263
2264 /**
2265 * Each value in a multi-valued feature is represented as an item.
2266 * This is the index of that item in its list.
2267 */
2268 public int itemIndex;
2269
2270 /**
2271 * The textual value of the item.
2272 */
2273 public String value;
2274
2275 public Item(FindAndReplaceTarget.Data data, int index, IItemPropertyDescriptor itemPropertyDescriptor, int itemIndex, String value)
2276 {
2277 this.data = data;
2278 this.index = index;
2279 this.itemPropertyDescriptor = itemPropertyDescriptor;
2280 this.itemIndex = itemIndex;
2281 this.value = value;
2282 }
2283
2284 public Object getFeature()
2285 {
2286 if (itemPropertyDescriptor != null)
2287 {
2288 return itemPropertyDescriptor.getFeature(data.object);
2289 }
2290
2291 return null;
2292 }
2293 }
2294 }
2295
2296 /**
2297 * This supports iterating over an induced textual representation of a structured viewer's structure.
2298 */
2299 protected static class TextData implements Iterable<FindAndReplaceTarget.Data>
2300 {
2301 private final StructuredViewer viewer;
2302
2303 private final Collator collator;
2304
2305 private final ILabelProvider labelProvider;
2306
2307 private final IPropertySourceProvider propertySourceProvider;
2308
2309 public TextData(StructuredViewer viewer, Collator collator)
2310 {
2311 this.viewer = viewer;
2312 this.collator = collator;
2313 labelProvider = (ILabelProvider)viewer.getLabelProvider();
2314 IContentProvider contentProvider = viewer.getContentProvider();
2315 propertySourceProvider = contentProvider instanceof IPropertySourceProvider ? (IPropertySourceProvider)contentProvider : null;
2316 }
2317
2318 public Iterator<FindAndReplaceTarget.Data> iterator()
2319 {
2320 // This is an iterator that delegates to an iterator that walks the structure of the viewer.
2321 final StructuredViewerTreeIterator structuredViewerTreeIterator = StructuredViewerTreeIterator.create(viewer);
2322 return new Iterator<FindAndReplaceTarget.Data>()
2323 {
2324 private List<Data> parents = new ArrayList<Data>();
2325
2326 // This keeps track of the textual index as we iterate.
2327 private int index;
2328
2329 public boolean hasNext()
2330 {
2331 return structuredViewerTreeIterator.hasNext();
2332 }
2333
2334 public FindAndReplaceTarget.Data next()
2335 {
2336 // Keep track of the depth before calling next.
2337 int depth = structuredViewerTreeIterator.size();
2338 Object object = structuredViewerTreeIterator.next();
2339
2340 // Create a list of items for this object and use that to create a new data representation.
2341 List<Data.Item> items = new ArrayList<Data.Item>();
2342 FindAndReplaceTarget.Data data = new Data(depth - 1, object, items);
2343
2344 if (parents.size() < depth)
2345 {
2346 parents.add(data);
2347 }
2348 else
2349 {
2350 parents.set(depth - 1, data);
2351 }
2352
2353 if (depth > 1)
2354 {
2355 data.parent = parents.get(depth - 2);
2356 }
2357
2358 // Add an item for the label.
2359 String label = labelProvider.getText(object);
2360 items.add(new Data.Item(data, index, null, 0, label));
2361 index += label.length();
2362
2363 // If we have a source provider...
2364 if (propertySourceProvider != null)
2365 {
2366 // And we have an EMF property source for the object...
2367 IPropertySource propertySource = propertySourceProvider.getPropertySource(object);
2368 if (propertySource instanceof PropertySource)
2369 {
2370 // Extract the EMF property source so we can iterate directly over the EMF property descriptors.
2371 PropertySource emfPropertySource = (PropertySource)propertySource;
2372 IItemPropertySource itemPropertySource = emfPropertySource.getItemPropertySource();
2373 visit(items, data, itemPropertySource, object);
2374 }
2375 }
2376
2377 return data;
2378 }
2379
2380 private void visit(List<Data.Item> items, FindAndReplaceTarget.Data data, IItemPropertySource itemPropertySource, Object object)
2381 {
2382 for (IItemPropertyDescriptor itemPropertyDescriptor : sort(itemPropertySource.getPropertyDescriptors(object), object))
2383 {
2384 // Extract the textual values of the property, if there are any.
2385 List<String> text = getText(itemPropertyDescriptor, object);
2386 if (text != null)
2387 {
2388 // Create an item for each value.
2389 for (int i = 0, size = text.size(); i < size; ++i)
2390 {
2391 String value = text.get(i);
2392 items.add(new Data.Item(data, index, itemPropertyDescriptor, i, value));
2393 index += value.length();
2394 }
2395 }
2396
2397 Object propertyValue = itemPropertyDescriptor.getPropertyValue(object);
2398 if (propertyValue instanceof IItemPropertySource)
2399 {
2400 IItemPropertySource childPropertySource = (IItemPropertySource)propertyValue;
2401 visit(items, data, childPropertySource, propertyValue);
2402 }
2403 }
2404 }
2405
2406 public void remove()
2407 {
2408 throw new UnsupportedOperationException("remove");
2409 }
2410 };
2411 }
2412
2413 protected List<? extends IItemPropertyDescriptor> sort(List<IItemPropertyDescriptor> propertyDescriptors, Object object)
2414 {
2415 Map<String, Map<String, IItemPropertyDescriptor>> categorizedPropertyDescriptors = collator == null
2416 ? new LinkedHashMap<String, Map<String, IItemPropertyDescriptor>>() : new TreeMap<String, Map<String, IItemPropertyDescriptor>>(collator);
2417 for (IItemPropertyDescriptor itemPropertyDescriptor : propertyDescriptors)
2418 {
2419 String category = itemPropertyDescriptor.getCategory(object);
2420 if (category == null)
2421 {
2422 category = EMFEditUIPlugin.INSTANCE.getString("_UI_Misc_property_category");
2423 }
2424 Map<String, IItemPropertyDescriptor> sortedItemPropertyDescriptors = categorizedPropertyDescriptors.get(category);
2425 if (sortedItemPropertyDescriptors == null)
2426 {
2427 sortedItemPropertyDescriptors = collator == null
2428 ? new LinkedHashMap<String, IItemPropertyDescriptor>() : new TreeMap<String, IItemPropertyDescriptor>(Collator.getInstance());
2429 categorizedPropertyDescriptors.put(category, sortedItemPropertyDescriptors);
2430 }
2431 sortedItemPropertyDescriptors.put(itemPropertyDescriptor.getDisplayName(object), itemPropertyDescriptor);
2432 }
2433
2434 List<IItemPropertyDescriptor> result = new ArrayList<IItemPropertyDescriptor>(propertyDescriptors.size());
2435 for (Map<String, IItemPropertyDescriptor> sortedItemPropertyDescriptors : categorizedPropertyDescriptors.values())
2436 {
2437 result.addAll(sortedItemPropertyDescriptors.values());
2438 }
2439
2440 return result;
2441 }
2442 }
2443
2444 /**
2445 * This enumerates the types of searches that are possible for an EMF-based structured editor.
2446 * <ul>
2447 * <li>Labels and properties - Searches the labels in the structure viewer as well as the values of all properties in the properties view.</li>
2448 * <li>Labels - Searches the only the labels in the structure viewer.</li>
2449 * <li>Properties - Searches the only the properties in the properties view.</li>
2450 * <li>Modifiable attributes - Searches the only the properties in the properties view that correspond to modified attributes of the model.</li>
2451 * </ul>
2452 */
2453 protected enum SearchType
2454 {
2455 LABEL_AND_PROPERTY()
2456 {
2457 @Override
2458 public boolean isIncluded(Data.Item item)
2459 {
2460 return item != null;
2461 }
2462
2463 @Override
2464 public String key()
2465 {
2466 return "label+property";
2467 }
2468
2469 @Override
2470 public String label()
2471 {
2472 return EMFEditUIPlugin.INSTANCE.getString("_UI_LabelAndProperties_label");
2473 }
2474 },
2475 LABEL()
2476 {
2477 @Override
2478 public boolean isIncluded(Data.Item item)
2479 {
2480 return item != null && item.itemPropertyDescriptor == null;
2481 }
2482
2483 @Override
2484 public String key()
2485 {
2486 return "label";
2487 }
2488
2489 @Override
2490 public String label()
2491 {
2492 return EMFEditUIPlugin.INSTANCE.getString("_UI_Labels_label");
2493 }
2494 },
2495 PROPERTY()
2496 {
2497 @Override
2498 public boolean isIncluded(Data.Item item)
2499 {
2500 return item != null && item.itemPropertyDescriptor != null;
2501 }
2502
2503 @Override
2504 public String key()
2505 {
2506 return "property";
2507 }
2508
2509 @Override
2510 public String label()
2511 {
2512 return EMFEditUIPlugin.INSTANCE.getString("_UI_Properties_label");
2513 }
2514 },
2515 MODIFIABLE_ATTRIBUTE
2516 {
2517 @Override
2518 public boolean isIncluded(Data.Item item)
2519 {
2520 return item != null && item.itemPropertyDescriptor != null && item.getFeature() instanceof EAttribute && item.itemPropertyDescriptor.canSetProperty(item.data.object);
2521 }
2522
2523 @Override
2524 public String key()
2525 {
2526 return "modifiable-attribute";
2527 }
2528
2529 @Override
2530 public String label()
2531 {
2532 return EMFEditUIPlugin.INSTANCE.getString("_UI_ModifiableAttributes_label");
2533 }
2534 };
2535
2536 public abstract boolean isIncluded(Data.Item item);
2537
2538 public abstract String key();
2539
2540 public abstract String label();
2541
2542 public static FindAndReplaceTarget.SearchType getSearchType(String key)
2543 {
2544 for (FindAndReplaceTarget.SearchType searchType : SearchType.values())
2545 {
2546 if (searchType.key().equals(key))
2547 {
2548 return searchType;
2549 }
2550 }
2551
2552 return LABEL_AND_PROPERTY;
2553 }
2554
2555 public static String[] getLabels()
2556 {
2557 FindAndReplaceTarget.SearchType[] values = SearchType.values();
2558 String[] labels = new String [values.length];
2559 for (int i = 0; i < values.length; ++i)
2560 {
2561 labels[i] = values[i].label();
2562 }
2563
2564 return labels;
2565 }
2566 }
2567 }