Final fix for Bug384878
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.ui / src / org / eclipse / linuxtools / tmf / ui / project / wizards / ImportTraceWizardPage.java
CommitLineData
12c155f5 1/*******************************************************************************
b544077e 2 * Copyright (c) 2009, 2010, 2011, 2012 Ericsson
013a5f1c 3 *
12c155f5
FC
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
013a5f1c 8 *
12c155f5
FC
9 * Contributors:
10 * Francois Chouinard - Initial API and implementation
11 * Francois Chouinard - Got rid of dependency on internal platform class
12 * Francois Chouinard - Complete re-design
13 *******************************************************************************/
14
15package org.eclipse.linuxtools.tmf.ui.project.wizards;
16
17import java.io.File;
18import java.io.IOException;
19import java.lang.reflect.InvocationTargetException;
20import java.util.ArrayList;
21import java.util.Collections;
3afaa476 22import java.util.Comparator;
12c155f5
FC
23import java.util.HashMap;
24import java.util.Iterator;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.Map;
5a5c2fc7 28import java.util.Map.Entry;
12c155f5
FC
29
30import org.eclipse.core.resources.IContainer;
31import org.eclipse.core.resources.IFolder;
32import org.eclipse.core.resources.IProject;
33import org.eclipse.core.resources.IResource;
34import org.eclipse.core.resources.ResourcesPlugin;
35import org.eclipse.core.runtime.CoreException;
36import org.eclipse.core.runtime.IConfigurationElement;
37import org.eclipse.core.runtime.IPath;
38import org.eclipse.core.runtime.IStatus;
39import org.eclipse.core.runtime.Path;
40import org.eclipse.core.runtime.Platform;
41import org.eclipse.jface.dialogs.ErrorDialog;
42import org.eclipse.jface.dialogs.MessageDialog;
43import org.eclipse.jface.viewers.CheckStateChangedEvent;
44import org.eclipse.jface.viewers.CheckboxTreeViewer;
45import org.eclipse.jface.viewers.ICheckStateListener;
46import org.eclipse.jface.viewers.IStructuredSelection;
47import org.eclipse.jface.viewers.ITreeContentProvider;
8fd82db5 48import org.eclipse.linuxtools.internal.tmf.ui.Activator;
d34665f9
FC
49import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace;
50import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition;
51import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace;
52import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition;
e12ecd30 53import org.eclipse.linuxtools.tmf.core.TmfCommonConstants;
d34665f9 54import org.eclipse.linuxtools.tmf.core.TmfProjectNature;
6c13869b 55import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
828e5592 56import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry;
12c155f5
FC
57import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement;
58import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceFolder;
bfc779a0 59import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType;
12c155f5
FC
60import org.eclipse.swt.SWT;
61import org.eclipse.swt.custom.BusyIndicator;
62import org.eclipse.swt.events.FocusEvent;
63import org.eclipse.swt.events.FocusListener;
64import org.eclipse.swt.events.KeyEvent;
65import org.eclipse.swt.events.KeyListener;
66import org.eclipse.swt.events.SelectionAdapter;
67import org.eclipse.swt.events.SelectionEvent;
68import org.eclipse.swt.events.SelectionListener;
69import org.eclipse.swt.layout.GridData;
70import org.eclipse.swt.layout.GridLayout;
71import org.eclipse.swt.widgets.Button;
72import org.eclipse.swt.widgets.Combo;
73import org.eclipse.swt.widgets.Composite;
74import org.eclipse.swt.widgets.DirectoryDialog;
75import org.eclipse.swt.widgets.Event;
76import org.eclipse.swt.widgets.Group;
77import org.eclipse.swt.widgets.Label;
12c155f5
FC
78import org.eclipse.ui.IWorkbench;
79import org.eclipse.ui.dialogs.FileSystemElement;
80import org.eclipse.ui.dialogs.WizardResourceImportPage;
81import org.eclipse.ui.model.WorkbenchContentProvider;
82import org.eclipse.ui.model.WorkbenchLabelProvider;
83import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
84import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
85import org.eclipse.ui.wizards.datatransfer.ImportOperation;
86
87/**
12c155f5
FC
88 * A variant of the standard resource import wizard with the following changes:
89 * <ul>
90 * <li>A folder/file combined checkbox tree viewer to select traces
91 * <li>Cherry-picking of traces in the file structure without re-creating the file hierarchy
92 * <li>A trace types dropbox for optional characterization
93 * </ul>
94 * For our purpose, a trace can either be a single file or a whole directory sub-tree, whichever is reached first from
95 * the root directory.
96 * <p>
013a5f1c 97 *
b544077e
BH
98 * @version 1.0
99 * @author Francois Chouinard
12c155f5 100 */
013a5f1c 101public class ImportTraceWizardPage extends WizardResourceImportPage {
12c155f5
FC
102
103 // ------------------------------------------------------------------------
104 // Constants
105 // ------------------------------------------------------------------------
106
107 static private final String IMPORT_WIZARD_PAGE = "ImportTraceWizardPage"; //$NON-NLS-1$
4bf17f4a 108 private static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$
109 private static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$
110 private static final String DEFAULT_TRACE_ICON_PATH = "icons/elcl16/trace.gif"; //$NON-NLS-1$
12c155f5
FC
111
112 // ------------------------------------------------------------------------
113 // Attributes
114 // ------------------------------------------------------------------------
115
116 // Folder navigation start point (saved between invocations)
117 private static String fRootDirectory = null;
118
119 // Navigation folder content viewer and selector
120 private CheckboxTreeViewer fFolderViewer;
121
122 // Parent tracing project
123 private IProject fProject;
124
125 // Target import directory ('Traces' folder)
126 private IFolder fTargetFolder;
127
12c155f5
FC
128 // ------------------------------------------------------------------------
129 // Constructors
130 // ------------------------------------------------------------------------
131
b544077e
BH
132 /**
133 * Constructor.
134 * Creates the trace wizard page.
013a5f1c 135 *
b544077e
BH
136 * @param name The name of the page.
137 * @param selection The current selection
138 */
12c155f5
FC
139 protected ImportTraceWizardPage(String name, IStructuredSelection selection) {
140 super(name, selection);
141 }
142
b544077e
BH
143 /**
144 * Constructor
145 * @param workbench The workbench reference.
146 * @param selection The current selection
147 */
12c155f5
FC
148 public ImportTraceWizardPage(IWorkbench workbench, IStructuredSelection selection) {
149 this(IMPORT_WIZARD_PAGE, selection);
150 setTitle(Messages.ImportTraceWizard_FileSystemTitle);
151 setDescription(Messages.ImportTraceWizard_ImportTrace);
152
153 // Locate the target trace folder
154 IFolder traceFolder = null;
155 Object element = selection.getFirstElement();
156
157 if (element instanceof TmfTraceFolder) {
158 TmfTraceFolder tmfTraceFolder = (TmfTraceFolder) element;
159 fProject = tmfTraceFolder.getProject().getResource();
160 traceFolder = tmfTraceFolder.getResource();
161 } else if (element instanceof IProject) {
162 IProject project = (IProject) element;
163 try {
164 if (project.hasNature(TmfProjectNature.ID)) {
165 traceFolder = (IFolder) project.findMember(TmfTraceFolder.TRACE_FOLDER_NAME);
166 }
167 } catch (CoreException e) {
168 }
169 }
170
171 // Set the target trace folder
172 if (traceFolder != null) {
173 fTargetFolder = traceFolder;
174 String path = traceFolder.getFullPath().toOSString();
175 setContainerFieldValue(path);
176 }
177 }
178
179 // ------------------------------------------------------------------------
180 // WizardResourceImportPage
181 // ------------------------------------------------------------------------
b544077e
BH
182 /*
183 * (non-Javadoc)
184 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createControl(org.eclipse.swt.widgets.Composite)
185 */
12c155f5
FC
186 @Override
187 public void createControl(Composite parent) {
188 super.createControl(parent);
189 // Restore last directory if applicable
190 if (fRootDirectory != null) {
191 directoryNameField.setText(fRootDirectory);
192 updateFromSourceField();
193 }
194 }
195
b544077e
BH
196 /*
197 * (non-Javadoc)
198 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createSourceGroup(org.eclipse.swt.widgets.Composite)
199 */
12c155f5
FC
200 @Override
201 protected void createSourceGroup(Composite parent) {
202 createDirectorySelectionGroup(parent);
203 createFileSelectionGroup(parent);
204 createTraceTypeGroup(parent);
205 validateSourceGroup();
206 }
207
b544077e
BH
208 /*
209 * (non-Javadoc)
210 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createFileSelectionGroup(org.eclipse.swt.widgets.Composite)
211 */
12c155f5
FC
212 @Override
213 protected void createFileSelectionGroup(Composite parent) {
214
215 // This Composite is only used for widget alignment purposes
216 Composite composite = new Composite(parent, SWT.NONE);
217 composite.setFont(parent.getFont());
218 GridLayout layout = new GridLayout();
219 composite.setLayout(layout);
220 composite.setLayoutData(new GridData(GridData.FILL_BOTH));
221
222 final int PREFERRED_LIST_HEIGHT = 150;
223
224 fFolderViewer = new CheckboxTreeViewer(composite, SWT.BORDER);
225 GridData data = new GridData(GridData.FILL_BOTH);
226 data.heightHint = PREFERRED_LIST_HEIGHT;
227 fFolderViewer.getTree().setLayoutData(data);
228 fFolderViewer.getTree().setFont(parent.getFont());
229
230 fFolderViewer.setContentProvider(getFileProvider());
231 fFolderViewer.setLabelProvider(new WorkbenchLabelProvider());
232 fFolderViewer.addCheckStateListener(new ICheckStateListener() {
233 @Override
234 public void checkStateChanged(CheckStateChangedEvent event) {
235 Object elem = event.getElement();
236 if (elem instanceof FileSystemElement) {
237 FileSystemElement element = (FileSystemElement) elem;
238 if (fFolderViewer.getGrayed(element)) {
239 fFolderViewer.setSubtreeChecked(element, false);
240 fFolderViewer.setGrayed(element, false);
241 } else if (event.getChecked()) {
242 fFolderViewer.setSubtreeChecked(event.getElement(), true);
243 } else {
244 fFolderViewer.setParentsGrayed(element, true);
245 if (!element.isDirectory()) {
246 fFolderViewer.setGrayed(element, false);
247 }
248 }
249 updateWidgetEnablements();
250 }
251 }
252 });
253 }
254
b544077e
BH
255 /*
256 * (non-Javadoc)
257 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFolderProvider()
258 */
12c155f5
FC
259 @Override
260 protected ITreeContentProvider getFolderProvider() {
261 return null;
262 }
263
b544077e
BH
264 /*
265 * (non-Javadoc)
266 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFileProvider()
267 */
12c155f5
FC
268 @Override
269 protected ITreeContentProvider getFileProvider() {
270 return new WorkbenchContentProvider() {
271 @Override
272 public Object[] getChildren(Object o) {
273 if (o instanceof FileSystemElement) {
274 FileSystemElement element = (FileSystemElement) o;
275 populateChildren(element);
276 // For our purpose, we need folders + files
277 Object[] folders = element.getFolders().getChildren();
278 Object[] files = element.getFiles().getChildren();
279
280 List<Object> result = new LinkedList<Object>();
013a5f1c 281 for (Object folder : folders) {
12c155f5 282 result.add(folder);
013a5f1c
AM
283 }
284 for (Object file : files) {
12c155f5 285 result.add(file);
013a5f1c 286 }
12c155f5
FC
287
288 return result.toArray();
289 }
290 return new Object[0];
291 }
292 };
293 }
294
abbdd66a 295 private static void populateChildren(FileSystemElement parent) {
12c155f5
FC
296 // Do not re-populate if the job was done already...
297 FileSystemStructureProvider provider = FileSystemStructureProvider.INSTANCE;
298 if (parent.getFolders().size() == 0 && parent.getFiles().size() == 0) {
299 Object fileSystemObject = parent.getFileSystemObject();
300 List<?> children = provider.getChildren(fileSystemObject);
301 if (children != null) {
302 Iterator<?> iterator = children.iterator();
303 while (iterator.hasNext()) {
304 Object child = iterator.next();
305 String label = provider.getLabel(child);
306 FileSystemElement element = new FileSystemElement(label, parent, provider.isFolder(child));
307 element.setFileSystemObject(child);
308 }
309 }
310 }
311 }
013a5f1c 312
b544077e
BH
313 /*
314 * (non-Javadoc)
315 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getSelectedResources()
316 */
12c155f5
FC
317 @Override
318 protected List<FileSystemElement> getSelectedResources() {
319 List<FileSystemElement> resources = new ArrayList<FileSystemElement>();
320 Object[] checkedItems = fFolderViewer.getCheckedElements();
321 for (Object item : checkedItems) {
322 if (item instanceof FileSystemElement && !fFolderViewer.getGrayed(item)) {
323 resources.add((FileSystemElement) item);
324 }
325 }
326 return resources;
327 }
328
329 // ------------------------------------------------------------------------
330 // Directory Selection Group (forked WizardFileSystemResourceImportPage1)
331 // ------------------------------------------------------------------------
332
b544077e
BH
333 /**
334 * The directory name field
335 */
12c155f5 336 protected Combo directoryNameField;
b544077e
BH
337 /**
338 * The directory browse button.
339 */
12c155f5
FC
340 protected Button directoryBrowseButton;
341 private boolean entryChanged = false;
342
b544077e
BH
343 /**
344 * creates the directory selection group.
345 * @param parent the parent composite
346 */
12c155f5
FC
347 protected void createDirectorySelectionGroup(Composite parent) {
348
349 Composite directoryContainerGroup = new Composite(parent, SWT.NONE);
350 GridLayout layout = new GridLayout();
351 layout.numColumns = 3;
352 directoryContainerGroup.setLayout(layout);
353 directoryContainerGroup.setFont(parent.getFont());
354 directoryContainerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
355
356 // Label ("Trace directory:")
357 Label groupLabel = new Label(directoryContainerGroup, SWT.NONE);
358 groupLabel.setText(Messages.ImportTraceWizard_DirectoryLocation);
359 groupLabel.setFont(parent.getFont());
360
361 // Directory name entry field
362 directoryNameField = new Combo(directoryContainerGroup, SWT.BORDER);
363 GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
364 data.widthHint = SIZING_TEXT_FIELD_WIDTH;
365 directoryNameField.setLayoutData(data);
366 directoryNameField.setFont(parent.getFont());
367
368 directoryNameField.addSelectionListener(new SelectionAdapter() {
369 @Override
370 public void widgetSelected(SelectionEvent e) {
371 updateFromSourceField();
372 }
373 });
374
375 directoryNameField.addKeyListener(new KeyListener() {
376 @Override
377 public void keyPressed(KeyEvent e) {
378 // If there has been a key pressed then mark as dirty
379 entryChanged = true;
380 if (e.character == SWT.CR) { // Windows...
381 entryChanged = false;
382 updateFromSourceField();
383 }
384 }
385
386 @Override
387 public void keyReleased(KeyEvent e) {
388 }
389 });
390
391 directoryNameField.addFocusListener(new FocusListener() {
392 @Override
393 public void focusGained(FocusEvent e) {
394 // Do nothing when getting focus
395 }
396
397 @Override
398 public void focusLost(FocusEvent e) {
399 // Clear the flag to prevent constant update
400 if (entryChanged) {
401 entryChanged = false;
402 updateFromSourceField();
403 }
404 }
405 });
406
407 // Browse button
408 directoryBrowseButton = new Button(directoryContainerGroup, SWT.PUSH);
409 directoryBrowseButton.setText(Messages.ImportTraceWizard_BrowseButton);
410 directoryBrowseButton.addListener(SWT.Selection, this);
411 directoryBrowseButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
412 directoryBrowseButton.setFont(parent.getFont());
413 setButtonLayoutData(directoryBrowseButton);
414 }
415
416 // ------------------------------------------------------------------------
417 // Browse for the source directory
418 // ------------------------------------------------------------------------
419
b544077e
BH
420 /*
421 * (non-Javadoc)
422 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#handleEvent(org.eclipse.swt.widgets.Event)
423 */
12c155f5
FC
424 @Override
425 public void handleEvent(Event event) {
426 if (event.widget == directoryBrowseButton) {
427 handleSourceDirectoryBrowseButtonPressed();
428 }
429 super.handleEvent(event);
430 }
431
b544077e
BH
432 /**
433 * Handle the button pressed event
434 */
12c155f5
FC
435 protected void handleSourceDirectoryBrowseButtonPressed() {
436 String currentSource = directoryNameField.getText();
437 DirectoryDialog dialog = new DirectoryDialog(directoryNameField.getShell(), SWT.SAVE | SWT.SHEET);
438 dialog.setText(Messages.ImportTraceWizard_SelectTraceDirectoryTitle);
439 dialog.setMessage(Messages.ImportTraceWizard_SelectTraceDirectoryMessage);
440 dialog.setFilterPath(getSourceDirectoryName(currentSource));
441
442 String selectedDirectory = dialog.open();
443 if (selectedDirectory != null) {
444 // Just quit if the directory is not valid
445 if ((getSourceDirectory(selectedDirectory) == null) || selectedDirectory.equals(currentSource)) {
446 return;
447 }
448 // If it is valid then proceed to populate
449 setErrorMessage(null);
450 setSourceName(selectedDirectory);
451 }
452 }
453
454 private File getSourceDirectory() {
455 return getSourceDirectory(directoryNameField.getText());
456 }
457
abbdd66a 458 private static File getSourceDirectory(String path) {
12c155f5
FC
459 File sourceDirectory = new File(getSourceDirectoryName(path));
460 if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
461 return null;
462 }
463
464 return sourceDirectory;
465 }
466
abbdd66a 467 private static String getSourceDirectoryName(String sourceName) {
12c155f5
FC
468 IPath result = new Path(sourceName.trim());
469 if (result.getDevice() != null && result.segmentCount() == 0) {
470 result = result.addTrailingSeparator();
471 } else {
472 result = result.removeTrailingSeparator();
473 }
474 return result.toOSString();
475 }
476
477 private String getSourceDirectoryName() {
478 return getSourceDirectoryName(directoryNameField.getText());
479 }
480
481 private void updateFromSourceField() {
482 setSourceName(directoryNameField.getText());
483 updateWidgetEnablements();
484 }
485
486 private void setSourceName(String path) {
487 if (path.length() > 0) {
488 String[] currentItems = directoryNameField.getItems();
489 int selectionIndex = -1;
490 for (int i = 0; i < currentItems.length; i++) {
491 if (currentItems[i].equals(path)) {
492 selectionIndex = i;
493 }
494 }
495 if (selectionIndex < 0) {
496 int oldLength = currentItems.length;
497 String[] newItems = new String[oldLength + 1];
498 System.arraycopy(currentItems, 0, newItems, 0, oldLength);
499 newItems[oldLength] = path;
500 directoryNameField.setItems(newItems);
501 selectionIndex = oldLength;
502 }
503 directoryNameField.select(selectionIndex);
504 }
505 resetSelection();
506 }
507
508 // ------------------------------------------------------------------------
509 // File Selection Group (forked WizardFileSystemResourceImportPage1)
510 // ------------------------------------------------------------------------
511
512 private void resetSelection() {
513 FileSystemElement root = getFileSystemTree();
514 populateListViewer(root);
515 }
516
517 private void populateListViewer(final Object treeElement) {
518 fFolderViewer.setInput(treeElement);
519 }
520
521 private FileSystemElement getFileSystemTree() {
522 File sourceDirectory = getSourceDirectory();
523 if (sourceDirectory == null) {
524 return null;
525 }
526 return selectFiles(sourceDirectory, FileSystemStructureProvider.INSTANCE);
527 }
528
c50b1d3b 529 private FileSystemElement selectFiles(final Object rootFileSystemObject, final IImportStructureProvider structureProvider) {
12c155f5
FC
530 final FileSystemElement[] results = new FileSystemElement[1];
531 BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
532 @Override
533 public void run() {
534 // Create the root element from the supplied file system object
535 results[0] = createRootElement(rootFileSystemObject, structureProvider);
536 }
537 });
538 return results[0];
539 }
540
abbdd66a
AM
541 private static FileSystemElement createRootElement(Object fileSystemObject,
542 IImportStructureProvider provider) {
12c155f5
FC
543
544 boolean isContainer = provider.isFolder(fileSystemObject);
545 String elementLabel = provider.getLabel(fileSystemObject);
546
547 FileSystemElement dummyParent = new FileSystemElement("", null, true); //$NON-NLS-1$
548 FileSystemElement element = new FileSystemElement(elementLabel, dummyParent, isContainer);
549 element.setFileSystemObject(fileSystemObject);
550
551 // Get the first level
552 populateChildren(element);
553
554 return dummyParent;
555 }
556
557 // ------------------------------------------------------------------------
558 // Trace Type Group
559 // ------------------------------------------------------------------------
560
561 private Combo fTraceTypes;
562
563 private final void createTraceTypeGroup(Composite parent) {
564 Composite composite = new Composite(parent, SWT.NONE);
565 GridLayout layout = new GridLayout();
566 layout.numColumns = 3;
567 layout.makeColumnsEqualWidth = false;
568 composite.setLayout(layout);
569 composite.setFont(parent.getFont());
570 GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false);
571 composite.setLayoutData(buttonData);
572
573 // Trace type label ("Trace Type:")
574 Label typeLabel = new Label(composite, SWT.NONE);
575 typeLabel.setText(Messages.ImportTraceWizard_TraceType);
576 typeLabel.setFont(parent.getFont());
577
578 // Trace type combo
579 fTraceTypes = new Combo(composite, SWT.BORDER);
580 GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
581 fTraceTypes.setLayoutData(data);
582 fTraceTypes.setFont(parent.getFont());
583
584 String[] availableTraceTypes = getAvailableTraceTypes();
585 fTraceTypes.setItems(availableTraceTypes);
586
587 fTraceTypes.addSelectionListener(new SelectionListener() {
588 @Override
589 public void widgetSelected(SelectionEvent e) {
590 validateSourceGroup();
591 }
592
593 @Override
594 public void widgetDefaultSelected(SelectionEvent e) {
595 }
596 });
597 }
598
c50b1d3b 599 // The mapping of available trace type IDs to their corresponding configuration element
013a5f1c
AM
600 private final Map<String, IConfigurationElement> fTraceTypeAttributes = new HashMap<String, IConfigurationElement>();
601 private final Map<String, IConfigurationElement> fTraceCategories = new HashMap<String, IConfigurationElement>();
c50b1d3b
FC
602 private final Map<String, IConfigurationElement> fTraceAttributes = new HashMap<String, IConfigurationElement>();
603
12c155f5 604 private String[] getAvailableTraceTypes() {
c50b1d3b
FC
605
606 // Populate the Categories and Trace Types
4bf17f4a 607 IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(TmfTraceType.TMF_TRACE_TYPE_ID);
12c155f5 608 for (IConfigurationElement ce : config) {
4bf17f4a 609 String elementName = ce.getName();
610 if (elementName.equals(TmfTraceType.TYPE_ELEM)) {
611 String traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
c50b1d3b 612 fTraceTypeAttributes.put(traceTypeId, ce);
4bf17f4a 613 } else if (elementName.equals(TmfTraceType.CATEGORY_ELEM)) {
614 String categoryId = ce.getAttribute(TmfTraceType.ID_ATTR);
c50b1d3b
FC
615 fTraceCategories.put(categoryId, ce);
616 }
617 }
618
619 // Generate the list of Category:TraceType to populate the ComboBox
620 List<String> traceTypes = new ArrayList<String>();
621 for (String typeId : fTraceTypeAttributes.keySet()) {
622 IConfigurationElement ce = fTraceTypeAttributes.get(typeId);
4bf17f4a 623 String traceTypeName = getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR); //$NON-NLS-1$
12c155f5
FC
624 fTraceAttributes.put(traceTypeName, ce);
625 traceTypes.add(traceTypeName);
626 }
627 Collections.sort(traceTypes);
628
4bf17f4a 629 // add the custom trace types
630 for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
631 String traceTypeName = CUSTOM_TXT_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
632 traceTypes.add(traceTypeName);
633 }
634 for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
635 String traceTypeName = CUSTOM_XML_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
636 traceTypes.add(traceTypeName);
637 }
12c155f5
FC
638
639 // Format result
beae214a 640 return traceTypes.toArray(new String[traceTypes.size()]);
12c155f5
FC
641 }
642
c50b1d3b 643 private String getCategory(IConfigurationElement ce) {
4bf17f4a 644 String categoryId = ce.getAttribute(TmfTraceType.CATEGORY_ATTR);
c50b1d3b
FC
645 if (categoryId != null) {
646 IConfigurationElement category = fTraceCategories.get(categoryId);
1cceddbe 647 if (category != null && !category.getName().equals("")) { //$NON-NLS-1$
4bf17f4a 648 return category.getAttribute(TmfTraceType.NAME_ATTR);
c50b1d3b
FC
649 }
650 }
651 return "[no category]"; //$NON-NLS-1$
652 }
653
12c155f5
FC
654 // ------------------------------------------------------------------------
655 // Options
656 // ------------------------------------------------------------------------
657
658 private Button overwriteExistingResourcesCheckbox;
659 private Button createLinksInWorkspaceButton;
660
b544077e
BH
661 /*
662 * (non-Javadoc)
663 * @see org.eclipse.ui.dialogs.WizardDataTransferPage#createOptionsGroupButtons(org.eclipse.swt.widgets.Group)
664 */
12c155f5
FC
665 @Override
666 protected void createOptionsGroupButtons(Group optionsGroup) {
667
668 // Overwrite checkbox
669 overwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
670 overwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
671 overwriteExistingResourcesCheckbox.setText(Messages.ImportTraceWizard_OverwriteExistingTrace);
672 overwriteExistingResourcesCheckbox.setSelection(false);
673
674 // Create links checkbox
675 createLinksInWorkspaceButton = new Button(optionsGroup, SWT.CHECK);
676 createLinksInWorkspaceButton.setFont(optionsGroup.getFont());
677 createLinksInWorkspaceButton.setText(Messages.ImportTraceWizard_CreateLinksInWorkspace);
678 createLinksInWorkspaceButton.setSelection(true);
679
680 createLinksInWorkspaceButton.addSelectionListener(new SelectionAdapter() {
681 @Override
682 public void widgetSelected(SelectionEvent e) {
683 updateWidgetEnablements();
684 }
685 });
686
687 updateWidgetEnablements();
688 }
689
690 // ------------------------------------------------------------------------
691 // Determine if the finish button can be enabled
692 // ------------------------------------------------------------------------
693
b544077e
BH
694 /*
695 * (non-Javadoc)
696 * @see org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
697 */
12c155f5
FC
698 @Override
699 public boolean validateSourceGroup() {
700
701 File sourceDirectory = getSourceDirectory();
702 if (sourceDirectory == null) {
703 setMessage(Messages.ImportTraceWizard_SelectTraceSourceEmpty);
704 return false;
705 }
706
707 if (sourceConflictsWithDestination(new Path(sourceDirectory.getPath()))) {
708 setMessage(null);
709 setErrorMessage(getSourceConflictMessage());
710 return false;
711 }
712
713 List<FileSystemElement> resourcesToImport = getSelectedResources();
714 if (resourcesToImport.size() == 0) {
715 setMessage(null);
716 setErrorMessage(Messages.ImportTraceWizard_SelectTraceNoneSelected);
717 return false;
718 }
719
720 IContainer container = getSpecifiedContainer();
721 if (container != null && container.isVirtual()) {
8fd82db5 722 if (Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, ResourcesPlugin.PREF_DISABLE_LINKING, false, null)) {
12c155f5
FC
723 setMessage(null);
724 setErrorMessage(Messages.ImportTraceWizard_CannotImportFilesUnderAVirtualFolder);
725 return false;
726 }
9fa32496 727 if (createLinksInWorkspaceButton == null || !createLinksInWorkspaceButton.getSelection()) {
12c155f5
FC
728 setMessage(null);
729 setErrorMessage(Messages.ImportTraceWizard_HaveToCreateLinksUnderAVirtualFolder);
730 return false;
731 }
732 }
733
734 // Perform trace validation
735 String traceTypeName = fTraceTypes.getText();
4bf17f4a 736 if (traceTypeName != null && !"".equals(traceTypeName) && //$NON-NLS-1$
737 !traceTypeName.startsWith(CUSTOM_TXT_CATEGORY) && !traceTypeName.startsWith(CUSTOM_XML_CATEGORY)) {
738
12c155f5
FC
739 List<File> traces = isolateTraces();
740 for (File trace : traces) {
12c155f5
FC
741 ITmfTrace<?> tmfTrace = null;
742 try {
4bf17f4a 743 IConfigurationElement ce = fTraceAttributes.get(traceTypeName);
744 tmfTrace = (ITmfTrace<?>) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR);
f9a8715c 745 if (tmfTrace != null && !tmfTrace.validate(fProject, trace.getAbsolutePath())) {
12c155f5
FC
746 setMessage(null);
747 setErrorMessage(Messages.ImportTraceWizard_TraceValidationFailed);
f9a8715c 748 tmfTrace.dispose();
12c155f5
FC
749 return false;
750 }
12c155f5
FC
751 } catch (CoreException e) {
752 } finally {
013a5f1c 753 if (tmfTrace != null) {
12c155f5 754 tmfTrace.dispose();
013a5f1c 755 }
12c155f5
FC
756 }
757 }
758 }
759
760 setErrorMessage(null);
761 return true;
762 }
763
764 private List<File> isolateTraces() {
765
766 List<File> traces = new ArrayList<File>();
767
768 // Get the selection
769 List<FileSystemElement> selectedResources = getSelectedResources();
770 Iterator<FileSystemElement> resources = selectedResources.iterator();
771
772 // Get the sorted list of unique entries
773 Map<String, File> fileSystemObjects = new HashMap<String, File>();
774 while (resources.hasNext()) {
775 File resource = (File) resources.next().getFileSystemObject();
776 String key = resource.getAbsolutePath();
777 fileSystemObjects.put(key, resource);
778 }
779 List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
780 Collections.sort(files);
781
782 // After sorting, traces correspond to the unique prefixes
783 String prefix = null;
784 for (int i = 0; i < files.size(); i++) {
785 File file = fileSystemObjects.get(files.get(i));
786 String name = file.getAbsolutePath();
787 if (prefix == null || !name.startsWith(prefix)) {
788 prefix = name; // new prefix
789 traces.add(file);
790 }
791 }
792
793 return traces;
794 }
795
796 // ------------------------------------------------------------------------
797 // Import the trace(s)
798 // ------------------------------------------------------------------------
799
b544077e
BH
800 /**
801 * Finish the import.
802 * @return <code>true</code> if successful else false
803 */
12c155f5
FC
804 public boolean finish() {
805 // Ensure source is valid
806 File sourceDir = new File(getSourceDirectoryName());
807 if (!sourceDir.isDirectory()) {
808 setErrorMessage(Messages.ImportTraceWizard_InvalidTraceDirectory);
809 return false;
810 }
811
812 String sourceDirPath;
813 try {
814 sourceDirPath = sourceDir.getCanonicalPath();
815 } catch (IOException e) {
816 MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
817 Messages.ImportTraceWizard_InvalidTraceDirectory);
818 return false;
819 }
820
821 // Save directory for next import operation
822 fRootDirectory = getSourceDirectoryName();
823
824 List<FileSystemElement> selectedResources = getSelectedResources();
825 Iterator<FileSystemElement> resources = selectedResources.iterator();
826
827 // Use a map to end up with unique resources (getSelectedResources() can return duplicates)
828 Map<String, File> fileSystemObjects = new HashMap<String, File>();
829 while (resources.hasNext()) {
830 File file = (File) resources.next().getFileSystemObject();
831 String key = file.getAbsolutePath();
832 fileSystemObjects.put(key, file);
833 }
834
835 if (fileSystemObjects.size() > 0) {
836 boolean ok = importResources(sourceDirPath, fileSystemObjects);
4bf17f4a 837 String traceBundle = null;
838 String traceTypeId = null;
839 String traceIcon = null;
12c155f5 840 String traceType = fTraceTypes.getText();
0b38509f 841 boolean traceTypeOK = false;
4bf17f4a 842 if (traceType.startsWith(CUSTOM_TXT_CATEGORY)) {
4bf17f4a 843 for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
844 if (traceType.equals(CUSTOM_TXT_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
0b38509f 845 traceTypeOK = true;
8fd82db5 846 traceBundle = Activator.getDefault().getBundle().getSymbolicName();
4bf17f4a 847 traceTypeId = CustomTxtTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
848 traceIcon = DEFAULT_TRACE_ICON_PATH;
849 break;
850 }
851 }
852 } else if (traceType.startsWith(CUSTOM_XML_CATEGORY)) {
853 for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
854 if (traceType.equals(CUSTOM_XML_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
0b38509f 855 traceTypeOK = true;
8fd82db5 856 traceBundle = Activator.getDefault().getBundle().getSymbolicName();
4bf17f4a 857 traceTypeId = CustomXmlTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
858 traceIcon = DEFAULT_TRACE_ICON_PATH;
859 break;
860 }
861 }
862 } else {
863 IConfigurationElement ce = fTraceAttributes.get(traceType);
864 if (ce != null) {
0b38509f 865 traceTypeOK = true;
4bf17f4a 866 traceBundle = ce.getContributor().getName();
867 traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
868 traceIcon = ce.getAttribute(TmfTraceType.ICON_ATTR);
4bf17f4a 869 }
870 }
0b38509f 871 if (ok && traceTypeOK && !traceType.equals("")) { //$NON-NLS-1$
12c155f5
FC
872 // Tag the selected traces with their type
873 List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
3afaa476
FC
874 Collections.sort(files, new Comparator<String>() {
875 @Override
876 public int compare(String o1, String o2) {
877 String v1 = o1 + File.separatorChar;
878 String v2 = o2 + File.separatorChar;
879 return v1.compareTo(v2);
880 }
881 });
12c155f5
FC
882 // After sorting, traces correspond to the unique prefixes
883 String prefix = null;
884 for (int i = 0; i < files.size(); i++) {
885 File file = fileSystemObjects.get(files.get(i));
16ef583c 886 String name = file.getAbsolutePath() + File.separatorChar;
29c0da0f 887 if (fTargetFolder != null && (prefix == null || !name.startsWith(prefix))) {
12c155f5
FC
888 prefix = name; // new prefix
889 IResource resource = fTargetFolder.findMember(file.getName());
890 if (resource != null) {
891 try {
892 // Set the trace properties for this resource
e12ecd30
BH
893 resource.setPersistentProperty(TmfCommonConstants.TRACEBUNDLE, traceBundle);
894 resource.setPersistentProperty(TmfCommonConstants.TRACETYPE, traceTypeId);
895 resource.setPersistentProperty(TmfCommonConstants.TRACEICON, traceIcon);
828e5592
PT
896 for (TmfTraceElement traceElement : TmfProjectRegistry.getProject(resource.getProject()).getTracesFolder().getTraces()) {
897 if (traceElement.getName().equals(resource.getName())) {
898 traceElement.refreshTraceType();
899 break;
900 }
901 }
12c155f5 902 } catch (CoreException e) {
8fd82db5 903 Activator.getDefault().logError("Error importing trace resource " + resource.getName(), e); //$NON-NLS-1$
12c155f5
FC
904 }
905 }
906 }
907 }
908 }
909 return ok;
910 }
911
912 MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
913 Messages.ImportTraceWizard_SelectTraceNoneSelected);
914 return false;
915 }
916
917 private boolean importResources(String rootDirectory, Map<String, File> fileSystemObjects) {
918
919 // Determine the sorted canonical list of items to import
920 List<File> fileList = new ArrayList<File>();
5a5c2fc7
FC
921 for (Entry<String, File> entry : fileSystemObjects.entrySet()) {
922 fileList.add(entry.getValue());
12c155f5 923 }
3afaa476
FC
924 Collections.sort(fileList, new Comparator<File>() {
925 @Override
926 public int compare(File o1, File o2) {
927 String v1 = o1.getAbsolutePath() + File.separatorChar;
928 String v2 = o2.getAbsolutePath() + File.separatorChar;
929 return v1.compareTo(v2);
930 }
931 });
5a5c2fc7 932
12c155f5
FC
933 // Perform a distinct import operation for everything that has the same prefix
934 // (distinct prefixes correspond to traces - we don't want to re-create parent structures)
935 boolean ok = true;
936 boolean isLinked = createLinksInWorkspaceButton.getSelection();
937 for (int i = 0; i < fileList.size(); i++) {
938 File resource = fileList.get(i);
939 File parentFolder = new File(resource.getParent());
940
941 List<File> subList = new ArrayList<File>();
942 subList.add(resource);
943 if (resource.isDirectory()) {
16ef583c 944 String prefix = resource.getAbsolutePath() + File.separatorChar;
12c155f5 945 boolean hasSamePrefix = true;
16ef583c 946 for (int j = i + 1; j < fileList.size() && hasSamePrefix; j++) {
12c155f5
FC
947 File res = fileList.get(j);
948 hasSamePrefix = res.getAbsolutePath().startsWith(prefix);
949 if (hasSamePrefix) {
950 // Import children individually if not linked
951 if (!isLinked) {
952 subList.add(res);
953 }
954 i = j;
955 }
956 }
957 }
958
959 // Perform the import operation for this subset
960 FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE;
c50b1d3b
FC
961 ImportOperation operation = new ImportOperation(getContainerFullPath(), parentFolder, fileSystemStructureProvider, this,
962 subList);
12c155f5
FC
963 operation.setContext(getShell());
964 ok = executeImportOperation(operation);
965 }
966
967 return ok;
968 }
969
970 private boolean executeImportOperation(ImportOperation op) {
971 initializeOperation(op);
972
973 try {
974 getContainer().run(true, true, op);
975 } catch (InterruptedException e) {
976 return false;
977 } catch (InvocationTargetException e) {
978 displayErrorDialog(e.getTargetException());
979 return false;
980 }
981
982 IStatus status = op.getStatus();
983 if (!status.isOK()) {
984 ErrorDialog.openError(getContainer().getShell(), Messages.ImportTraceWizard_ImportProblem, null, status);
985 return false;
986 }
987
988 return true;
989 }
990
991 private void initializeOperation(ImportOperation op) {
992 op.setCreateContainerStructure(false);
993 op.setOverwriteResources(overwriteExistingResourcesCheckbox.getSelection());
994 op.setCreateLinks(createLinksInWorkspaceButton.getSelection());
995 op.setVirtualFolders(false);
996 }
997
998}
This page took 0.073166 seconds and 5 git commands to generate.