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