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