From be222f56a3ba9b24e29a53c38a6d43db300bf880 Mon Sep 17 00:00:00 2001 From: Patrick Tasse Date: Tue, 2 Oct 2012 17:02:07 -0400 Subject: [PATCH] Convert Windows line delimiters to Unix. Change-Id: Idb33e8cc17d49436d2ed3edd49869cf965c86d13 --- .../lttng2/kernel/core/Attributes.java | 4 +- .../core/stateprovider/CtfKernelHandler.java | 88 +- .../internal/lttng2/kernel/ui/Messages.java | 80 +- .../lttng2/kernel/ui/messages.properties | 46 +- .../ui/viewers/events/LTTng2EventsTable.java | 178 +- .../kernel/ui/views/common/EventIterator.java | 294 +- .../views/controlflow/ControlFlowEntry.java | 428 +-- .../views/controlflow/ControlFlowEvent.java | 102 +- .../ControlFlowPresentationProvider.java | 308 +- .../ui/views/controlflow/ControlFlowView.java | 1608 ++++---- .../ui/views/resources/ResourcesEntry.java | 382 +- .../ui/views/resources/ResourcesEvent.java | 158 +- .../ResourcesPresentationProvider.java | 446 +-- .../ui/views/resources/ResourcesView.java | 1398 +++---- .../linuxtools/internal/tmf/core/Tracer.java | 370 +- .../tmf/core/filter/ITmfFilter.java | 66 +- .../core/filter/model/ITmfFilterTreeNode.java | 254 +- .../core/filter/model/TmfFilterAndNode.java | 180 +- .../filter/model/TmfFilterCompareNode.java | 444 +-- .../filter/model/TmfFilterContainsNode.java | 280 +- .../filter/model/TmfFilterEqualsNode.java | 284 +- .../filter/model/TmfFilterEventTypeNode.java | 266 +- .../filter/model/TmfFilterMatchesNode.java | 292 +- .../tmf/core/filter/model/TmfFilterNode.java | 214 +- .../core/filter/model/TmfFilterOrNode.java | 176 +- .../core/filter/model/TmfFilterRootNode.java | 124 +- .../core/filter/model/TmfFilterTreeNode.java | 428 +-- .../filter/xml/TmfFilterContentHandler.java | 372 +- .../core/filter/xml/TmfFilterXMLParser.java | 140 +- .../core/filter/xml/TmfFilterXMLWriter.java | 324 +- .../tmf/core/io/BufferedRandomAccessFile.java | 452 +-- .../core/signal/TmfTraceSelectedSignal.java | 102 +- .../test/stub/adaption/TsfImplProvider.java | 110 +- .../timegraph/test/stub/model/EventImpl.java | 170 +- .../timegraph/test/stub/model/TraceImpl.java | 230 +- .../stub/model/TraceModelImplFactory.java | 464 +-- org.eclipse.linuxtools.tmf.ui/plugin.xml | 2432 ++++++------ .../linuxtools/internal/tmf/ui/Messages.java | 528 +-- .../internal/tmf/ui/TmfUiTracer.java | 328 +- .../ManageCustomParsersCommandHandler.java | 60 +- .../ui/dialogs/ManageCustomParsersDialog.java | 566 +-- .../editors/handlers/AddBookmarkHandler.java | 86 +- .../internal/tmf/ui/messages.properties | 516 +-- .../tmf/ui/parsers/custom/CustomEvent.java | 272 +- .../ui/parsers/custom/CustomEventContent.java | 82 +- .../ui/parsers/custom/CustomEventType.java | 48 +- .../ui/parsers/custom/CustomEventsTable.java | 120 +- .../parsers/custom/CustomTraceDefinition.java | 116 +- .../tmf/ui/parsers/custom/CustomTxtEvent.java | 194 +- .../ui/parsers/custom/CustomTxtEventType.java | 42 +- .../tmf/ui/parsers/custom/CustomTxtTrace.java | 696 ++-- .../parsers/custom/CustomTxtTraceContext.java | 172 +- .../custom/CustomTxtTraceDefinition.java | 1344 +++---- .../tmf/ui/parsers/custom/CustomXmlEvent.java | 166 +- .../ui/parsers/custom/CustomXmlEventType.java | 42 +- .../tmf/ui/parsers/custom/CustomXmlTrace.java | 872 ++--- .../parsers/custom/CustomXmlTraceContext.java | 96 +- .../custom/CustomXmlTraceDefinition.java | 1160 +++--- .../CustomTxtParserInputWizardPage.java | 3124 +++++++-------- .../CustomTxtParserOutputWizardPage.java | 594 +-- .../wizards/CustomTxtParserWizard.java | 106 +- .../CustomXmlParserInputWizardPage.java | 3382 ++++++++--------- .../CustomXmlParserOutputWizardPage.java | 596 +-- .../wizards/CustomXmlParserWizard.java | 106 +- .../tmf/ui/signal/TmfTraceClosedSignal.java | 82 +- .../tmf/ui/signal/TmfTraceOpenedSignal.java | 110 +- .../signal/TmfTraceParserUpdatedSignal.java | 82 +- .../tmf/ui/editors/ITmfTraceEditor.java | 78 +- .../linuxtools/tmf/ui/editors/TmfEditor.java | 124 +- .../tmf/ui/editors/TmfEditorInput.java | 280 +- .../tmf/ui/editors/TmfEventsEditor.java | 1118 +++--- .../ui/editors/TmfMultiPageEditorPart.java | 124 +- .../ui/project/model/TmfExperimentFolder.java | 58 +- .../tmf/ui/signal/TmfTraceClosedSignal.java | 108 +- .../tmf/ui/signal/TmfTraceOpenedSignal.java | 166 +- .../signal/TmfTraceParserUpdatedSignal.java | 106 +- .../events/ITmfEventsFilterListener.java | 92 +- .../events/ITmfEventsFilterProvider.java | 78 +- .../tmf/ui/views/colors/ColorSetting.java | 428 +-- .../ui/views/colors/ColorSettingsManager.java | 306 +- .../tmf/ui/views/colors/ColorSettingsXML.java | 448 +-- .../tmf/ui/views/colors/ColorsView.java | 1166 +++--- .../views/colors/IColorSettingsListener.java | 60 +- .../tmf/ui/views/filter/FilterDialog.java | 166 +- .../tmf/ui/views/filter/FilterManager.java | 156 +- .../filter/FilterTreeContentProvider.java | 190 +- .../views/filter/FilterTreeLabelProvider.java | 300 +- .../tmf/ui/views/filter/FilterView.java | 612 +-- .../tmf/ui/views/filter/FilterViewer.java | 2210 +++++------ .../timechart/TimeChartAnalysisEntry.java | 546 +-- .../timechart/TimeChartAnalysisProvider.java | 208 +- .../TimeChartDecorationProvider.java | 276 +- .../ui/views/timechart/TimeChartEvent.java | 750 ++-- .../tmf/ui/views/timechart/TimeChartView.java | 1400 +++---- .../widgets/rawviewer/TmfRawEventViewer.java | 2068 +++++----- .../ITimeGraphPresentationProvider.java | 258 +- .../timegraph/ITimeGraphRangeListener.java | 62 +- .../ITimeGraphSelectionListener.java | 62 +- .../timegraph/ITimeGraphTimeListener.java | 62 +- .../timegraph/ITimeGraphTreeListener.java | 72 +- .../ui/widgets/timegraph/TimeGraphCombo.java | 1448 +++---- .../TimeGraphPresentationProvider.java | 264 +- .../timegraph/TimeGraphRangeUpdateEvent.java | 142 +- .../timegraph/TimeGraphSelectionEvent.java | 116 +- .../widgets/timegraph/TimeGraphTimeEvent.java | 112 +- .../TimeGraphTreeExpansionEvent.java | 114 +- .../ui/widgets/timegraph/TimeGraphViewer.java | 2680 ++++++------- .../timegraph/dialogs/TimeGraphLegend.java | 356 +- .../widgets/timegraph/model/ITimeEvent.java | 98 +- .../timegraph/model/ITimeGraphEntry.java | 200 +- .../ui/widgets/timegraph/model/TimeEvent.java | 112 +- .../timegraph/widgets/ITimeDataProvider.java | 278 +- .../widgets/TimeGraphBaseControl.java | 214 +- .../widgets/TimeGraphColorScheme.java | 860 ++--- .../timegraph/widgets/TimeGraphItem.java | 114 +- .../timegraph/widgets/TimeGraphSelection.java | 192 +- .../ui/widgets/timegraph/widgets/Utils.java | 1264 +++--- .../ui/widgets/virtualtable/ColumnData.java | 92 +- 118 files changed, 26108 insertions(+), 26068 deletions(-) diff --git a/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/Attributes.java b/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/Attributes.java index 2867c22b56..d02918608a 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/Attributes.java +++ b/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/Attributes.java @@ -34,11 +34,11 @@ public abstract class Attributes { /* Sub-attributes of the CPU nodes */ public static final String CURRENT_THREAD = "Current_thread"; - public static final String STATUS = "Status"; + public static final String STATUS = "Status"; /* Sub-attributes of the Thread nodes */ public static final String PPID = "PPID"; - //public static final String STATUS = "Status" + //public static final String STATUS = "Status" public static final String EXEC_NAME = "Exec_name"; public static final String SYSTEM_CALL = "System_call"; diff --git a/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/stateprovider/CtfKernelHandler.java b/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/stateprovider/CtfKernelHandler.java index c805a5d995..8911c963f8 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/stateprovider/CtfKernelHandler.java +++ b/org.eclipse.linuxtools.lttng2.kernel.core/src/org/eclipse/linuxtools/internal/lttng2/kernel/core/stateprovider/CtfKernelHandler.java @@ -165,11 +165,11 @@ class CtfKernelHandler implements Runnable { quark = ss.getQuarkRelativeAndAdd(currentThreadNode, Attributes.STATUS); value = TmfStateValue.newValueInt(StateValues.PROCESS_STATUS_INTERRUPTED); ss.modifyAttribute(ts, value, quark); - - /* Change the status of the CPU to interrupted */ - quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.STATUS); - value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IRQ); - ss.modifyAttribute(ts, value, quark); + + /* Change the status of the CPU to interrupted */ + quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.STATUS); + value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IRQ); + ss.modifyAttribute(ts, value, quark); } break; @@ -185,9 +185,9 @@ class CtfKernelHandler implements Runnable { /* Set the previous process back to running */ setProcessToRunning(ts, currentThreadNode); - - /* Set the CPU status back to running or "idle" */ - cpuExitInterrupt(ts, currentCPUNode, currentThreadNode); + + /* Set the CPU status back to running or "idle" */ + cpuExitInterrupt(ts, currentCPUNode, currentThreadNode); } break; @@ -206,11 +206,11 @@ class CtfKernelHandler implements Runnable { quark = ss.getQuarkRelativeAndAdd(currentThreadNode, Attributes.STATUS); value = TmfStateValue.newValueInt(StateValues.PROCESS_STATUS_INTERRUPTED); ss.modifyAttribute(ts, value, quark); - - /* Change the status of the CPU to interrupted */ - quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.STATUS); - value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_SOFTIRQ); - ss.modifyAttribute(ts, value, quark); + + /* Change the status of the CPU to interrupted */ + quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.STATUS); + value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_SOFTIRQ); + ss.modifyAttribute(ts, value, quark); } break; @@ -226,9 +226,9 @@ class CtfKernelHandler implements Runnable { /* Set the previous process back to running */ setProcessToRunning(ts, currentThreadNode); - - /* Set the CPU status back to "busy" or "idle" */ - cpuExitInterrupt(ts, currentCPUNode, currentThreadNode); + + /* Set the CPU status back to "busy" or "idle" */ + cpuExitInterrupt(ts, currentCPUNode, currentThreadNode); } break; @@ -291,7 +291,7 @@ class CtfKernelHandler implements Runnable { quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.CURRENT_THREAD); value = TmfStateValue.newValueInt(nextTid); ss.modifyAttribute(ts, value, quark); - + /* Set the status of the CPU itself */ if (nextTid > 0) { /* Check if the entering process is in kernel or user mode */ @@ -300,12 +300,12 @@ class CtfKernelHandler implements Runnable { value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_RUN_USERMODE); } else { value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_RUN_SYSCALL); - } - } else { - value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IDLE); + } + } else { + value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IDLE); } quark = ss.getQuarkRelativeAndAdd(currentCPUNode, Attributes.STATUS); - ss.modifyAttribute(ts, value, quark); + ss.modifyAttribute(ts, value, quark); } break; @@ -543,22 +543,22 @@ class CtfKernelHandler implements Runnable { quark = ss.getQuarkRelativeAndAdd(currentThreadNode, Attributes.STATUS); ss.modifyAttribute(ts, value, quark); } - - /** - * Similar logic as above, but to set the CPU's status when it's coming out - * of an interruption. - * @throws AttributeNotFoundException - * @throws StateValueTypeException - * @throws TimeRangeException - */ - private void cpuExitInterrupt(long ts, int currentCpuNode, int currentThreadNode) - throws StateValueTypeException, AttributeNotFoundException, - TimeRangeException { - int quark; - ITmfStateValue value; - - quark = ss.getQuarkRelativeAndAdd(currentCpuNode, Attributes.CURRENT_THREAD); - if (ss.queryOngoingState(quark).unboxInt() > 0) { + + /** + * Similar logic as above, but to set the CPU's status when it's coming out + * of an interruption. + * @throws AttributeNotFoundException + * @throws StateValueTypeException + * @throws TimeRangeException + */ + private void cpuExitInterrupt(long ts, int currentCpuNode, int currentThreadNode) + throws StateValueTypeException, AttributeNotFoundException, + TimeRangeException { + int quark; + ITmfStateValue value; + + quark = ss.getQuarkRelativeAndAdd(currentCpuNode, Attributes.CURRENT_THREAD); + if (ss.queryOngoingState(quark).unboxInt() > 0) { /* There was a process on the CPU */ quark = ss.getQuarkRelative(currentThreadNode, Attributes.SYSTEM_CALL); if (ss.queryOngoingState(quark).isNull()) { @@ -568,11 +568,11 @@ class CtfKernelHandler implements Runnable { /* That process was in a system call */ value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_RUN_SYSCALL); } - } else { - /* There was no real process scheduled, CPU was idle */ - value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IDLE); - } - quark = ss.getQuarkRelativeAndAdd(currentCpuNode, Attributes.STATUS); - ss.modifyAttribute(ts, value, quark); - } + } else { + /* There was no real process scheduled, CPU was idle */ + value = TmfStateValue.newValueInt(StateValues.CPU_STATUS_IDLE); + } + quark = ss.getQuarkRelativeAndAdd(currentCpuNode, Attributes.STATUS); + ss.modifyAttribute(ts, value, quark); + } } diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/Messages.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/Messages.java index 6fa7d7867d..09fc768d74 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/Messages.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/Messages.java @@ -1,40 +1,40 @@ -package org.eclipse.linuxtools.internal.lttng2.kernel.ui; - -import org.eclipse.osgi.util.NLS; - -@SuppressWarnings("javadoc") -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.lttng2.kernel.ui.messages"; //$NON-NLS-1$ - - public static String ControlFlowView_birthTimeColumn; - public static String ControlFlowView_tidColumn; - public static String ControlFlowView_ptidColumn; - public static String ControlFlowView_processColumn; - public static String ControlFlowView_traceColumn; - - public static String ControlFlowView_stateTypeName; - public static String ControlFlowView_nextProcessActionNameText; - public static String ControlFlowView_nextProcessActionToolTipText; - public static String ControlFlowView_previousProcessActionNameText; - public static String ControlFlowView_previousProcessActionToolTipText; - - public static String ControlFlowView_attributeSyscallName; - public static String ControlFlowView_attributeCpuName; - - public static String ResourcesView_stateTypeName; - public static String ResourcesView_nextResourceActionNameText; - public static String ResourcesView_nextResourceActionToolTipText; - public static String ResourcesView_previousResourceActionNameText; - public static String ResourcesView_previousResourceActionToolTipText; - public static String ResourcesView_attributeCpuName; - public static String ResourcesView_attributeIrqName; - public static String ResourcesView_attributeSoftIrqName; - - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - } -} +package org.eclipse.linuxtools.internal.lttng2.kernel.ui; + +import org.eclipse.osgi.util.NLS; + +@SuppressWarnings("javadoc") +public class Messages extends NLS { + private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.lttng2.kernel.ui.messages"; //$NON-NLS-1$ + + public static String ControlFlowView_birthTimeColumn; + public static String ControlFlowView_tidColumn; + public static String ControlFlowView_ptidColumn; + public static String ControlFlowView_processColumn; + public static String ControlFlowView_traceColumn; + + public static String ControlFlowView_stateTypeName; + public static String ControlFlowView_nextProcessActionNameText; + public static String ControlFlowView_nextProcessActionToolTipText; + public static String ControlFlowView_previousProcessActionNameText; + public static String ControlFlowView_previousProcessActionToolTipText; + + public static String ControlFlowView_attributeSyscallName; + public static String ControlFlowView_attributeCpuName; + + public static String ResourcesView_stateTypeName; + public static String ResourcesView_nextResourceActionNameText; + public static String ResourcesView_nextResourceActionToolTipText; + public static String ResourcesView_previousResourceActionNameText; + public static String ResourcesView_previousResourceActionToolTipText; + public static String ResourcesView_attributeCpuName; + public static String ResourcesView_attributeIrqName; + public static String ResourcesView_attributeSoftIrqName; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/messages.properties b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/messages.properties index 27ff12516c..ea6c7755d7 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/messages.properties +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/messages.properties @@ -1,23 +1,23 @@ -ControlFlowView_birthTimeColumn=Birth time -ControlFlowView_tidColumn=TID -ControlFlowView_ptidColumn=PTID -ControlFlowView_processColumn=Process -ControlFlowView_traceColumn=Trace - -ControlFlowView_stateTypeName=Process -ControlFlowView_nextProcessActionNameText=Next Process -ControlFlowView_nextProcessActionToolTipText=Select Next Process -ControlFlowView_previousProcessActionNameText=Previous Process -ControlFlowView_previousProcessActionToolTipText=Select Previous Process - -ControlFlowView_attributeSyscallName=System Call -ControlFlowView_attributeCpuName=CPU - -ResourcesView_stateTypeName=Resource -ResourcesView_nextResourceActionNameText=Next Resource -ResourcesView_nextResourceActionToolTipText=Select Next Resource -ResourcesView_previousResourceActionNameText=Previous Resource -ResourcesView_previousResourceActionToolTipText=Select Previous Resource -ResourcesView_attributeCpuName=CPU -ResourcesView_attributeIrqName=IRQ -ResourcesView_attributeSoftIrqName=SOFT IRQ +ControlFlowView_birthTimeColumn=Birth time +ControlFlowView_tidColumn=TID +ControlFlowView_ptidColumn=PTID +ControlFlowView_processColumn=Process +ControlFlowView_traceColumn=Trace + +ControlFlowView_stateTypeName=Process +ControlFlowView_nextProcessActionNameText=Next Process +ControlFlowView_nextProcessActionToolTipText=Select Next Process +ControlFlowView_previousProcessActionNameText=Previous Process +ControlFlowView_previousProcessActionToolTipText=Select Previous Process + +ControlFlowView_attributeSyscallName=System Call +ControlFlowView_attributeCpuName=CPU + +ResourcesView_stateTypeName=Resource +ResourcesView_nextResourceActionNameText=Next Resource +ResourcesView_nextResourceActionToolTipText=Select Next Resource +ResourcesView_previousResourceActionNameText=Previous Resource +ResourcesView_previousResourceActionToolTipText=Select Previous Resource +ResourcesView_attributeCpuName=CPU +ResourcesView_attributeIrqName=IRQ +ResourcesView_attributeSoftIrqName=SOFT IRQ diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/viewers/events/LTTng2EventsTable.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/viewers/events/LTTng2EventsTable.java index 7a413ad5fb..f0d1671b54 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/viewers/events/LTTng2EventsTable.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/viewers/events/LTTng2EventsTable.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Francois Chouinard - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.viewers.events; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; -import org.eclipse.linuxtools.tmf.core.event.TmfEventField; -import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; -import org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; - -/** - * Events table specific for LTTng 2.0 kernel traces - */ -public class LTTng2EventsTable extends TmfEventsTable { - - // ------------------------------------------------------------------------ - // Table data - // ------------------------------------------------------------------------ - - // Table column names - static private final String TIMESTAMP_COLUMN = Messages.EventsTable_timestampColumn; - static private final String CHANNEL_COLUMN = Messages.EventsTable_channelColumn; - static private final String TYPE_COLUMN = Messages.EventsTable_typeColumn; - static private final String CONTENT_COLUMN = Messages.EventsTable_contentColumn; - static private final String[] COLUMN_NAMES = new String[] { - TIMESTAMP_COLUMN, - CHANNEL_COLUMN, - TYPE_COLUMN, - CONTENT_COLUMN - }; - - static private final ColumnData[] COLUMN_DATA = new ColumnData[] { - new ColumnData(COLUMN_NAMES[0], 150, SWT.LEFT), - new ColumnData(COLUMN_NAMES[1], 120, SWT.LEFT), - new ColumnData(COLUMN_NAMES[2], 200, SWT.LEFT), - new ColumnData(COLUMN_NAMES[3], 100, SWT.LEFT) - }; - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Constructor - * - * @param parent - * The parent composite - * @param cacheSize - * The size of the rows cache - */ - public LTTng2EventsTable(Composite parent, int cacheSize) { - super(parent, cacheSize, COLUMN_DATA); - fTable.getColumns()[0].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_TIMESTAMP); - fTable.getColumns()[1].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_REFERENCE); - fTable.getColumns()[2].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_TYPE); - fTable.getColumns()[3].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_CONTENT); - } - - /** - * @param event - * @return - */ - @Override - protected ITmfEventField[] extractItemFields(ITmfEvent event) { - ITmfEventField[] fields = new TmfEventField[0]; - if (event != null) { - fields = new TmfEventField[] { - new TmfEventField(ITmfEvent.EVENT_FIELD_TIMESTAMP, event.getTimestamp().toString()), - new TmfEventField(ITmfEvent.EVENT_FIELD_REFERENCE, event.getReference()), - new TmfEventField(ITmfEvent.EVENT_FIELD_TYPE, event.getType().getName()), - new TmfEventField(ITmfEvent.EVENT_FIELD_CONTENT, event.getContent().toString()) - }; - } - return fields; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Francois Chouinard - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.viewers.events; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; +import org.eclipse.linuxtools.tmf.core.event.TmfEventField; +import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; +import org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; + +/** + * Events table specific for LTTng 2.0 kernel traces + */ +public class LTTng2EventsTable extends TmfEventsTable { + + // ------------------------------------------------------------------------ + // Table data + // ------------------------------------------------------------------------ + + // Table column names + static private final String TIMESTAMP_COLUMN = Messages.EventsTable_timestampColumn; + static private final String CHANNEL_COLUMN = Messages.EventsTable_channelColumn; + static private final String TYPE_COLUMN = Messages.EventsTable_typeColumn; + static private final String CONTENT_COLUMN = Messages.EventsTable_contentColumn; + static private final String[] COLUMN_NAMES = new String[] { + TIMESTAMP_COLUMN, + CHANNEL_COLUMN, + TYPE_COLUMN, + CONTENT_COLUMN + }; + + static private final ColumnData[] COLUMN_DATA = new ColumnData[] { + new ColumnData(COLUMN_NAMES[0], 150, SWT.LEFT), + new ColumnData(COLUMN_NAMES[1], 120, SWT.LEFT), + new ColumnData(COLUMN_NAMES[2], 200, SWT.LEFT), + new ColumnData(COLUMN_NAMES[3], 100, SWT.LEFT) + }; + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Constructor + * + * @param parent + * The parent composite + * @param cacheSize + * The size of the rows cache + */ + public LTTng2EventsTable(Composite parent, int cacheSize) { + super(parent, cacheSize, COLUMN_DATA); + fTable.getColumns()[0].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_TIMESTAMP); + fTable.getColumns()[1].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_REFERENCE); + fTable.getColumns()[2].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_TYPE); + fTable.getColumns()[3].setData(Key.FIELD_ID, ITmfEvent.EVENT_FIELD_CONTENT); + } + + /** + * @param event + * @return + */ + @Override + protected ITmfEventField[] extractItemFields(ITmfEvent event) { + ITmfEventField[] fields = new TmfEventField[0]; + if (event != null) { + fields = new TmfEventField[] { + new TmfEventField(ITmfEvent.EVENT_FIELD_TIMESTAMP, event.getTimestamp().toString()), + new TmfEventField(ITmfEvent.EVENT_FIELD_REFERENCE, event.getReference()), + new TmfEventField(ITmfEvent.EVENT_FIELD_TYPE, event.getType().getName()), + new TmfEventField(ITmfEvent.EVENT_FIELD_CONTENT, event.getContent().toString()) + }; + } + return fields; + } + +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/common/EventIterator.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/common/EventIterator.java index d1acc54c55..35d9d50ca5 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/common/EventIterator.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/common/EventIterator.java @@ -1,147 +1,147 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common; - -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; - -/** - * An iterator for time events - */ -public class EventIterator implements Iterator { - - private final long fStartTime; - private final long fEndTime; - private List fEventList; - private List fZoomedEventList; - private long fZoomedStartTime; - private long fZoomedEndTime; - private int fIndex = 0; - private int fZoomedIndex= 0; - private ITimeEvent fNext = null; - private ITimeEvent fZoomedNext = null; - - /** - * Basic constructor, with start time and end times equal to the lowest and - * highest values possible, respectively. - * - * @param eventList - * The list on which this iterator will iterate - * @param zoomedEventList - * The "zoomed" list - */ - public EventIterator(List eventList, List zoomedEventList) { - this(eventList, zoomedEventList, Long.MIN_VALUE, Long.MAX_VALUE); - } - - /** - * Complete constructor, where we specify start and end times. - * - * @param eventList - * The list on which this iterator will iterate - * @param zoomedEventList - * The "zoomed" list - * @param startTime - * The start time - * @param endTime - * The end time - */ - public EventIterator(List eventList, - List zoomedEventList, long startTime, long endTime) { - fEventList = eventList; - fZoomedEventList = zoomedEventList; - if (zoomedEventList != null && zoomedEventList.size() > 0) { - fZoomedStartTime = zoomedEventList.get(0).getTime(); - ITimeEvent lastEvent = zoomedEventList.get(zoomedEventList.size() - 1); - fZoomedEndTime = lastEvent.getTime() + lastEvent.getDuration(); - } else { - fZoomedStartTime = Long.MAX_VALUE; - fZoomedEndTime = Long.MIN_VALUE; - } - fStartTime = startTime; - fEndTime = endTime; - } - - @Override - public boolean hasNext() { - if (fNext == null && fEventList != null) { - while (fIndex < fEventList.size()) { - ITimeEvent event = fEventList.get(fIndex++); - if (event.getTime() + event.getDuration() >= fStartTime && event.getTime() <= fEndTime) { - fNext = event; - break; - } - } - if (fNext == null) { - fEventList = null; - } - } - - if (fZoomedNext == null && fZoomedEventList != null) { - while (fZoomedIndex < fZoomedEventList.size()) { - ITimeEvent event = fZoomedEventList.get(fZoomedIndex++); - if (event.getTime() + event.getDuration() >= fStartTime && event.getTime() <= fEndTime) { - fZoomedNext = event; - break; - } - } - if (fZoomedNext == null) { - fZoomedEventList = null; - } - } - - return fNext != null || fZoomedNext != null; - } - - @Override - public ITimeEvent next() { - if (hasNext()) { - if (fZoomedNext != null && (fNext == null || fZoomedNext.getTime() <= fNext.getTime())) { - if (fNext != null && fNext.getTime() == fZoomedNext.getTime()) { - long duration = fNext.getTime() + fNext.getDuration() - fZoomedEndTime; - if (duration > 0) { - fNext = new TimeEvent(fNext.getEntry(), fZoomedEndTime, duration); - } else { - fNext = null; - } - } - ITimeEvent event = fZoomedNext; - fZoomedNext = null; - return event; - } - if (fNext.getTime() < fZoomedEndTime && fNext.getTime() + fNext.getDuration() > fZoomedStartTime) { - ITimeEvent event = new TimeEvent(fNext.getEntry(), fNext.getTime(), fZoomedStartTime - fNext.getTime()); - long duration = fNext.getTime() + fNext.getDuration() - fZoomedEndTime; - if (duration > 0) { - fNext = new TimeEvent(fNext.getEntry(), fZoomedEndTime, duration); - } else { - fNext = null; - } - return event; - } - ITimeEvent event = fNext; - fNext = null; - return event; - } - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; + +/** + * An iterator for time events + */ +public class EventIterator implements Iterator { + + private final long fStartTime; + private final long fEndTime; + private List fEventList; + private List fZoomedEventList; + private long fZoomedStartTime; + private long fZoomedEndTime; + private int fIndex = 0; + private int fZoomedIndex= 0; + private ITimeEvent fNext = null; + private ITimeEvent fZoomedNext = null; + + /** + * Basic constructor, with start time and end times equal to the lowest and + * highest values possible, respectively. + * + * @param eventList + * The list on which this iterator will iterate + * @param zoomedEventList + * The "zoomed" list + */ + public EventIterator(List eventList, List zoomedEventList) { + this(eventList, zoomedEventList, Long.MIN_VALUE, Long.MAX_VALUE); + } + + /** + * Complete constructor, where we specify start and end times. + * + * @param eventList + * The list on which this iterator will iterate + * @param zoomedEventList + * The "zoomed" list + * @param startTime + * The start time + * @param endTime + * The end time + */ + public EventIterator(List eventList, + List zoomedEventList, long startTime, long endTime) { + fEventList = eventList; + fZoomedEventList = zoomedEventList; + if (zoomedEventList != null && zoomedEventList.size() > 0) { + fZoomedStartTime = zoomedEventList.get(0).getTime(); + ITimeEvent lastEvent = zoomedEventList.get(zoomedEventList.size() - 1); + fZoomedEndTime = lastEvent.getTime() + lastEvent.getDuration(); + } else { + fZoomedStartTime = Long.MAX_VALUE; + fZoomedEndTime = Long.MIN_VALUE; + } + fStartTime = startTime; + fEndTime = endTime; + } + + @Override + public boolean hasNext() { + if (fNext == null && fEventList != null) { + while (fIndex < fEventList.size()) { + ITimeEvent event = fEventList.get(fIndex++); + if (event.getTime() + event.getDuration() >= fStartTime && event.getTime() <= fEndTime) { + fNext = event; + break; + } + } + if (fNext == null) { + fEventList = null; + } + } + + if (fZoomedNext == null && fZoomedEventList != null) { + while (fZoomedIndex < fZoomedEventList.size()) { + ITimeEvent event = fZoomedEventList.get(fZoomedIndex++); + if (event.getTime() + event.getDuration() >= fStartTime && event.getTime() <= fEndTime) { + fZoomedNext = event; + break; + } + } + if (fZoomedNext == null) { + fZoomedEventList = null; + } + } + + return fNext != null || fZoomedNext != null; + } + + @Override + public ITimeEvent next() { + if (hasNext()) { + if (fZoomedNext != null && (fNext == null || fZoomedNext.getTime() <= fNext.getTime())) { + if (fNext != null && fNext.getTime() == fZoomedNext.getTime()) { + long duration = fNext.getTime() + fNext.getDuration() - fZoomedEndTime; + if (duration > 0) { + fNext = new TimeEvent(fNext.getEntry(), fZoomedEndTime, duration); + } else { + fNext = null; + } + } + ITimeEvent event = fZoomedNext; + fZoomedNext = null; + return event; + } + if (fNext.getTime() < fZoomedEndTime && fNext.getTime() + fNext.getDuration() > fZoomedStartTime) { + ITimeEvent event = new TimeEvent(fNext.getEntry(), fNext.getTime(), fZoomedStartTime - fNext.getTime()); + long duration = fNext.getTime() + fNext.getDuration() - fZoomedEndTime; + if (duration > 0) { + fNext = new TimeEvent(fNext.getEntry(), fZoomedEndTime, duration); + } else { + fNext = null; + } + return event; + } + ITimeEvent event = fNext; + fNext = null; + return event; + } + throw new NoSuchElementException(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEntry.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEntry.java index 0bf076993d..97b6ef03e7 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEntry.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEntry.java @@ -1,214 +1,214 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common.EventIterator; -import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * An entry in the Control Flow view - */ -public class ControlFlowEntry implements ITimeGraphEntry { - private final int fThreadQuark; - private final CtfKernelTrace fTrace; - private ControlFlowEntry fParent = null; - private final ArrayList fChildren = new ArrayList(); - private final String fName; - private final int fThreadId; - private final int fParentThreadId; - private long fBirthTime = -1; - private long fStartTime = -1; - private long fEndTime = -1; - private List fEventList = new ArrayList(); - private List fZoomedEventList = null; - - /** - * Constructor - * - * @param threadQuark - * The attribute quark matching the thread - * @param trace - * The trace on which we are working - * @param execName - * The exec_name of this entry - * @param threadId - * The TID of the thread - * @param parentThreadId - * the Parent_TID of this thread - * @param birthTime - * The birth time of this entry (this allows separating different - * process that could have the same TID) - * @param startTime - * The start time of this process's lifetime - * @param endTime - * The end time of this process - */ - public ControlFlowEntry(int threadQuark, CtfKernelTrace trace, String execName, int threadId, int parentThreadId, long birthTime, long startTime, long endTime) { - fThreadQuark = threadQuark; - fTrace = trace; - fName = execName; - fThreadId = threadId; - fParentThreadId = parentThreadId; - fBirthTime = birthTime; - fStartTime = startTime; - fEndTime = endTime; - } - - @Override - public ITimeGraphEntry getParent() { - return fParent; - } - - @Override - public boolean hasChildren() { - return fChildren != null && fChildren.size() > 0; - } - - @Override - public ControlFlowEntry[] getChildren() { - return fChildren.toArray(new ControlFlowEntry[0]); - } - - @Override - public String getName() { - return fName; - } - - @Override - public long getStartTime() { - return fStartTime; - } - - @Override - public long getEndTime() { - return fEndTime; - } - - @Override - public boolean hasTimeEvents() { - return true; - } - - @Override - public Iterator getTimeEventsIterator() { - return new EventIterator(fEventList, fZoomedEventList); - } - - @Override - public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { - return new EventIterator(fEventList, fZoomedEventList, startTime, stopTime); - } - - /** - * Get the quark of the attribute matching this thread's TID - * - * @return The quark - */ - public int getThreadQuark() { - return fThreadQuark; - } - - /** - * Get the CTF trace object - * - * @return The trace - */ - public CtfKernelTrace getTrace() { - return fTrace; - } - - /** - * Get this entry's thread ID - * - * @return The TID - */ - public int getThreadId() { - return fThreadId; - } - - /** - * Get this thread's parent TID - * - * @return The "PTID" - */ - public int getParentThreadId() { - return fParentThreadId; - } - - /** - * Get the birth time of this entry/process - * - * @return The birth time - */ - public long getBirthTime() { - return fBirthTime; - } - - /** - * Add an event to this process's timeline - * - * @param event - * The time event - */ - public void addEvent(ITimeEvent event) { - long start = event.getTime(); - long end = start + event.getDuration(); - synchronized (fEventList) { - fEventList.add(event); - if (fStartTime == -1 || start < fStartTime) { - fStartTime = start; - } - if (fEndTime == -1 || end > fEndTime) { - fEndTime = end; - } - } - } - - /** - * Set the general event list of this entry - * - * @param eventList - * The list of time events - */ - public void setEventList(List eventList) { - fEventList = eventList; - } - - /** - * Set the zoomed event list of this entry - * - * @param eventList - * The list of time events - */ - public void setZoomedEventList(List eventList) { - fZoomedEventList = eventList; - } - - /** - * Add a child entry to this one (to show relationships between processes as - * a tree) - * - * @param child - * The child entry - */ - public void addChild(ControlFlowEntry child) { - child.fParent = this; - fChildren.add(child); - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common.EventIterator; +import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * An entry in the Control Flow view + */ +public class ControlFlowEntry implements ITimeGraphEntry { + private final int fThreadQuark; + private final CtfKernelTrace fTrace; + private ControlFlowEntry fParent = null; + private final ArrayList fChildren = new ArrayList(); + private final String fName; + private final int fThreadId; + private final int fParentThreadId; + private long fBirthTime = -1; + private long fStartTime = -1; + private long fEndTime = -1; + private List fEventList = new ArrayList(); + private List fZoomedEventList = null; + + /** + * Constructor + * + * @param threadQuark + * The attribute quark matching the thread + * @param trace + * The trace on which we are working + * @param execName + * The exec_name of this entry + * @param threadId + * The TID of the thread + * @param parentThreadId + * the Parent_TID of this thread + * @param birthTime + * The birth time of this entry (this allows separating different + * process that could have the same TID) + * @param startTime + * The start time of this process's lifetime + * @param endTime + * The end time of this process + */ + public ControlFlowEntry(int threadQuark, CtfKernelTrace trace, String execName, int threadId, int parentThreadId, long birthTime, long startTime, long endTime) { + fThreadQuark = threadQuark; + fTrace = trace; + fName = execName; + fThreadId = threadId; + fParentThreadId = parentThreadId; + fBirthTime = birthTime; + fStartTime = startTime; + fEndTime = endTime; + } + + @Override + public ITimeGraphEntry getParent() { + return fParent; + } + + @Override + public boolean hasChildren() { + return fChildren != null && fChildren.size() > 0; + } + + @Override + public ControlFlowEntry[] getChildren() { + return fChildren.toArray(new ControlFlowEntry[0]); + } + + @Override + public String getName() { + return fName; + } + + @Override + public long getStartTime() { + return fStartTime; + } + + @Override + public long getEndTime() { + return fEndTime; + } + + @Override + public boolean hasTimeEvents() { + return true; + } + + @Override + public Iterator getTimeEventsIterator() { + return new EventIterator(fEventList, fZoomedEventList); + } + + @Override + public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { + return new EventIterator(fEventList, fZoomedEventList, startTime, stopTime); + } + + /** + * Get the quark of the attribute matching this thread's TID + * + * @return The quark + */ + public int getThreadQuark() { + return fThreadQuark; + } + + /** + * Get the CTF trace object + * + * @return The trace + */ + public CtfKernelTrace getTrace() { + return fTrace; + } + + /** + * Get this entry's thread ID + * + * @return The TID + */ + public int getThreadId() { + return fThreadId; + } + + /** + * Get this thread's parent TID + * + * @return The "PTID" + */ + public int getParentThreadId() { + return fParentThreadId; + } + + /** + * Get the birth time of this entry/process + * + * @return The birth time + */ + public long getBirthTime() { + return fBirthTime; + } + + /** + * Add an event to this process's timeline + * + * @param event + * The time event + */ + public void addEvent(ITimeEvent event) { + long start = event.getTime(); + long end = start + event.getDuration(); + synchronized (fEventList) { + fEventList.add(event); + if (fStartTime == -1 || start < fStartTime) { + fStartTime = start; + } + if (fEndTime == -1 || end > fEndTime) { + fEndTime = end; + } + } + } + + /** + * Set the general event list of this entry + * + * @param eventList + * The list of time events + */ + public void setEventList(List eventList) { + fEventList = eventList; + } + + /** + * Set the zoomed event list of this entry + * + * @param eventList + * The list of time events + */ + public void setZoomedEventList(List eventList) { + fZoomedEventList = eventList; + } + + /** + * Add a child entry to this one (to show relationships between processes as + * a tree) + * + * @param child + * The child entry + */ + public void addChild(ControlFlowEntry child) { + child.fParent = this; + fChildren.add(child); + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEvent.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEvent.java index 52d6f6784d..5651b1ca5a 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEvent.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowEvent.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; - -/** - * Time Event specific to the control flow view - */ -public class ControlFlowEvent extends TimeEvent { - - private final int fStatus; - - /** - * Constructor - * - * @param entry - * The entry to which this time event is assigned - * @param time - * The timestamp of this event - * @param duration - * The duration of this event - * @param status - * The status assigned to the event - */ - public ControlFlowEvent(ITimeGraphEntry entry, long time, long duration, - int status) { - super(entry, time, duration); - fStatus = status; - } - - /** - * Get this event's status - * - * @return The integer matching this status - */ - public int getStatus() { - return fStatus; - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; + +/** + * Time Event specific to the control flow view + */ +public class ControlFlowEvent extends TimeEvent { + + private final int fStatus; + + /** + * Constructor + * + * @param entry + * The entry to which this time event is assigned + * @param time + * The timestamp of this event + * @param duration + * The duration of this event + * @param status + * The status assigned to the event + */ + public ControlFlowEvent(ITimeGraphEntry entry, long time, long duration, + int status) { + super(entry, time, duration); + fStatus = status; + } + + /** + * Get this event's status + * + * @return The integer matching this status + */ + public int getStatus() { + return fStatus; + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowPresentationProvider.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowPresentationProvider.java index 7e2e9e5551..89d02b5623 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowPresentationProvider.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowPresentationProvider.java @@ -1,154 +1,154 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; -import org.eclipse.linuxtools.internal.lttng2.kernel.core.StateValues; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; -import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; -import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; -import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; -import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; -import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.swt.graphics.RGB; - -/** - * Presentation provider for the control flow view - */ -public class ControlFlowPresentationProvider extends TimeGraphPresentationProvider { - - private enum State { - UNKNOWN (new RGB(100, 100, 100)), - WAIT (new RGB(200, 200, 0)), - USERMODE (new RGB(0, 200, 0)), - SYSCALL (new RGB(0, 0, 200)), - INTERRUPTED (new RGB(200, 100, 100)); - - public final RGB rgb; - - private State (RGB rgb) { - this.rgb = rgb; - } - } - - @Override - public String getStateTypeName() { - return Messages.ControlFlowView_stateTypeName; - } - - @Override - public StateItem[] getStateTable() { - StateItem[] stateTable = new StateItem[State.values().length]; - for (int i = 0; i < stateTable.length; i++) { - State state = State.values()[i]; - stateTable[i] = new StateItem(state.rgb, state.toString()); - } - return stateTable; - } - - @Override - public int getStateTableIndex(ITimeEvent event) { - if (event instanceof ControlFlowEvent) { - int status = ((ControlFlowEvent) event).getStatus(); - if (status == StateValues.PROCESS_STATUS_WAIT) { - return State.WAIT.ordinal(); - } else if (status == StateValues.PROCESS_STATUS_RUN_USERMODE) { - return State.USERMODE.ordinal(); - } else if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { - return State.SYSCALL.ordinal(); - } else if (status == StateValues.PROCESS_STATUS_INTERRUPTED) { - return State.INTERRUPTED.ordinal(); - } - } - return State.UNKNOWN.ordinal(); - } - - @Override - public String getEventName(ITimeEvent event) { - if (event instanceof ControlFlowEvent) { - int status = ((ControlFlowEvent) event).getStatus(); - if (status == StateValues.PROCESS_STATUS_WAIT) { - return State.WAIT.toString(); - } else if (status == StateValues.PROCESS_STATUS_RUN_USERMODE) { - return State.USERMODE.toString(); - } else if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { - return State.SYSCALL.toString(); - } else if (status == StateValues.PROCESS_STATUS_INTERRUPTED) { - return State.INTERRUPTED.toString(); - } - } - return State.UNKNOWN.toString(); - } - - @Override - public Map getEventHoverToolTipInfo(ITimeEvent event) { - Map retMap = new LinkedHashMap(); - if (event instanceof ControlFlowEvent) { - ControlFlowEntry entry = (ControlFlowEntry) event.getEntry(); - IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); - int tid = entry.getThreadId(); - - try { - //Find every CPU first, then get the current thread - int cpusQuark = ssq.getQuarkAbsolute(Attributes.CPUS); - List cpuQuarks = ssq.getSubAttributes(cpusQuark, false); - for (Integer cpuQuark : cpuQuarks) { - int currentThreadQuark = ssq.getQuarkRelative(cpuQuark, Attributes.CURRENT_THREAD); - ITmfStateInterval interval = ssq.querySingleState(event.getTime(), currentThreadQuark); - if (!interval.getStateValue().isNull()) { - ITmfStateValue state = interval.getStateValue(); - int currentThreadId = state.unboxInt(); - if (tid == currentThreadId) { - retMap.put(Messages.ControlFlowView_attributeCpuName, ssq.getAttributeName(cpuQuark)); - break; - } - } - } - - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - int status = ((ControlFlowEvent) event).getStatus(); - if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { - try { - int syscallQuark = ssq.getQuarkRelative(entry.getThreadQuark(), Attributes.SYSTEM_CALL); - ITmfStateInterval value = ssq.querySingleState(event.getTime(), syscallQuark); - if (!value.getStateValue().isNull()) { - ITmfStateValue state = value.getStateValue(); - retMap.put(Messages.ControlFlowView_attributeSyscallName, state.toString()); - } - - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } - } - } - - return retMap; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; +import org.eclipse.linuxtools.internal.lttng2.kernel.core.StateValues; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; +import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; +import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; +import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; +import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; +import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.swt.graphics.RGB; + +/** + * Presentation provider for the control flow view + */ +public class ControlFlowPresentationProvider extends TimeGraphPresentationProvider { + + private enum State { + UNKNOWN (new RGB(100, 100, 100)), + WAIT (new RGB(200, 200, 0)), + USERMODE (new RGB(0, 200, 0)), + SYSCALL (new RGB(0, 0, 200)), + INTERRUPTED (new RGB(200, 100, 100)); + + public final RGB rgb; + + private State (RGB rgb) { + this.rgb = rgb; + } + } + + @Override + public String getStateTypeName() { + return Messages.ControlFlowView_stateTypeName; + } + + @Override + public StateItem[] getStateTable() { + StateItem[] stateTable = new StateItem[State.values().length]; + for (int i = 0; i < stateTable.length; i++) { + State state = State.values()[i]; + stateTable[i] = new StateItem(state.rgb, state.toString()); + } + return stateTable; + } + + @Override + public int getStateTableIndex(ITimeEvent event) { + if (event instanceof ControlFlowEvent) { + int status = ((ControlFlowEvent) event).getStatus(); + if (status == StateValues.PROCESS_STATUS_WAIT) { + return State.WAIT.ordinal(); + } else if (status == StateValues.PROCESS_STATUS_RUN_USERMODE) { + return State.USERMODE.ordinal(); + } else if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { + return State.SYSCALL.ordinal(); + } else if (status == StateValues.PROCESS_STATUS_INTERRUPTED) { + return State.INTERRUPTED.ordinal(); + } + } + return State.UNKNOWN.ordinal(); + } + + @Override + public String getEventName(ITimeEvent event) { + if (event instanceof ControlFlowEvent) { + int status = ((ControlFlowEvent) event).getStatus(); + if (status == StateValues.PROCESS_STATUS_WAIT) { + return State.WAIT.toString(); + } else if (status == StateValues.PROCESS_STATUS_RUN_USERMODE) { + return State.USERMODE.toString(); + } else if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { + return State.SYSCALL.toString(); + } else if (status == StateValues.PROCESS_STATUS_INTERRUPTED) { + return State.INTERRUPTED.toString(); + } + } + return State.UNKNOWN.toString(); + } + + @Override + public Map getEventHoverToolTipInfo(ITimeEvent event) { + Map retMap = new LinkedHashMap(); + if (event instanceof ControlFlowEvent) { + ControlFlowEntry entry = (ControlFlowEntry) event.getEntry(); + IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); + int tid = entry.getThreadId(); + + try { + //Find every CPU first, then get the current thread + int cpusQuark = ssq.getQuarkAbsolute(Attributes.CPUS); + List cpuQuarks = ssq.getSubAttributes(cpusQuark, false); + for (Integer cpuQuark : cpuQuarks) { + int currentThreadQuark = ssq.getQuarkRelative(cpuQuark, Attributes.CURRENT_THREAD); + ITmfStateInterval interval = ssq.querySingleState(event.getTime(), currentThreadQuark); + if (!interval.getStateValue().isNull()) { + ITmfStateValue state = interval.getStateValue(); + int currentThreadId = state.unboxInt(); + if (tid == currentThreadId) { + retMap.put(Messages.ControlFlowView_attributeCpuName, ssq.getAttributeName(cpuQuark)); + break; + } + } + } + + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + int status = ((ControlFlowEvent) event).getStatus(); + if (status == StateValues.PROCESS_STATUS_RUN_SYSCALL) { + try { + int syscallQuark = ssq.getQuarkRelative(entry.getThreadQuark(), Attributes.SYSTEM_CALL); + ITmfStateInterval value = ssq.querySingleState(event.getTime(), syscallQuark); + if (!value.getStateValue().isNull()) { + ITmfStateValue state = value.getStateValue(); + retMap.put(Messages.ControlFlowView_attributeSyscallName, state.toString()); + } + + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } + } + } + + return retMap; + } + +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowView.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowView.java index 03d2c4f94d..93a2f62528 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowView.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/controlflow/ControlFlowView.java @@ -1,804 +1,804 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; -import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; -import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTimestamp; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; -import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; -import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; -import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; -import org.eclipse.linuxtools.tmf.core.signal.TmfExperimentSelectedSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfRangeSynchSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; -import org.eclipse.linuxtools.tmf.core.signal.TmfStateSystemBuildCompleted; -import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier2; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; -import org.eclipse.linuxtools.tmf.ui.views.TmfView; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphSelectionListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphCombo; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphSelectionEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils.Resolution; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.TreeColumn; -import org.eclipse.ui.IActionBars; - -/** - * The Control Flow view main object - * - */ -public class ControlFlowView extends TmfView { - - // ------------------------------------------------------------------------ - // Constants - // ------------------------------------------------------------------------ - - /** - * View ID. - */ - public static final String ID = "org.eclipse.linuxtools.lttng2.kernel.ui.views.controlflow"; //$NON-NLS-1$ - - /** - * Initial time range - */ - private static final long INITIAL_WINDOW_OFFSET = (1L * 100 * 1000 * 1000); // .1sec - - private static final String PROCESS_COLUMN = Messages.ControlFlowView_processColumn; - private static final String TID_COLUMN = Messages.ControlFlowView_tidColumn; - private static final String PTID_COLUMN = Messages.ControlFlowView_ptidColumn; - private static final String BIRTH_TIME_COLUMN = Messages.ControlFlowView_birthTimeColumn; - private static final String TRACE_COLUMN = Messages.ControlFlowView_traceColumn; - - private final String[] COLUMN_NAMES = new String[] { - PROCESS_COLUMN, - TID_COLUMN, - PTID_COLUMN, - BIRTH_TIME_COLUMN, - TRACE_COLUMN - }; - - /** - * Redraw state enum - */ - private enum State { IDLE, BUSY, PENDING } - - // ------------------------------------------------------------------------ - // Fields - // ------------------------------------------------------------------------ - - // The timegraph combo - private TimeGraphCombo fTimeGraphCombo; - - // The selected experiment - private TmfExperiment fSelectedExperiment; - - // The timegraph entry list - private ArrayList fEntryList; - - // The time graph entry list synchronization object - final private Object fEntryListSyncObj = new Object(); - - // The start time - private long fStartTime; - - // The end time - private long fEndTime; - - // The display width - private final int fDisplayWidth; - - // The zoom thread - private ZoomThread fZoomThread; - - // The next resource action - private Action fNextResourceAction; - - // The previous resource action - private Action fPreviousResourceAction; - - // A comparator class - private final ControlFlowEntryComparator fControlFlowEntryComparator = new ControlFlowEntryComparator(); - - // The redraw state used to prevent unnecessary queuing of display runnables - private State fRedrawState = State.IDLE; - - // The redraw synchronization object - final private Object fSyncObj = new Object(); - - // ------------------------------------------------------------------------ - // Classes - // ------------------------------------------------------------------------ - - private class TreeContentProvider implements ITreeContentProvider { - - @Override - public void dispose() { - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - @Override - public Object[] getElements(Object inputElement) { - return (ITimeGraphEntry[]) inputElement; - } - - @Override - public Object[] getChildren(Object parentElement) { - ITimeGraphEntry entry = (ITimeGraphEntry) parentElement; - return entry.getChildren(); - } - - @Override - public Object getParent(Object element) { - ITimeGraphEntry entry = (ITimeGraphEntry) element; - return entry.getParent(); - } - - @Override - public boolean hasChildren(Object element) { - ITimeGraphEntry entry = (ITimeGraphEntry) element; - return entry.hasChildren(); - } - - } - - private class TreeLabelProvider implements ITableLabelProvider { - - @Override - public void addListener(ILabelProviderListener listener) { - } - - @Override - public void dispose() { - } - - @Override - public boolean isLabelProperty(Object element, String property) { - return false; - } - - @Override - public void removeListener(ILabelProviderListener listener) { - } - - @Override - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - @Override - public String getColumnText(Object element, int columnIndex) { - ControlFlowEntry entry = (ControlFlowEntry) element; - if (columnIndex == 0) { - return entry.getName(); - } else if (columnIndex == 1) { - return Integer.toString(entry.getThreadId()); - } else if (columnIndex == 2) { - if (entry.getParentThreadId() > 0) { - return Integer.toString(entry.getParentThreadId()); - } - } else if (columnIndex == 3) { - return Utils.formatTime(entry.getBirthTime(), TimeFormat.ABSOLUTE, Resolution.NANOSEC); - } else if (columnIndex == 4) { - return entry.getTrace().getName(); - } - return ""; //$NON-NLS-1$ - } - - } - - private static class ControlFlowEntryComparator implements Comparator { - - @Override - public int compare(ITimeGraphEntry o1, ITimeGraphEntry o2) { - int result = 0; - - if ((o1 instanceof ControlFlowEntry) && (o2 instanceof ControlFlowEntry)) { - ControlFlowEntry entry1 = (ControlFlowEntry) o1; - ControlFlowEntry entry2 = (ControlFlowEntry) o2; - result = entry1.getTrace().getStartTime().compareTo(entry2.getTrace().getStartTime()); - if (result == 0) { - result = entry1.getTrace().getName().compareTo(entry2.getTrace().getName()); - } - if (result == 0) { - result = entry1.getThreadId() < entry2.getThreadId() ? -1 : entry1.getThreadId() > entry2.getThreadId() ? 1 : 0; - } - } - - if (result == 0) { - result = o1.getStartTime() < o2.getStartTime() ? -1 : o1.getStartTime() > o2.getStartTime() ? 1 : 0; - } - - return result; - } - } - - - private class ZoomThread extends Thread { - private final long fZoomStartTime; - private final long fZoomEndTime; - private final long fResolution; - private final IProgressMonitor fMonitor; - - public ZoomThread(long startTime, long endTime) { - super("ControlFlowView zoom"); //$NON-NLS-1$ - fZoomStartTime = startTime; - fZoomEndTime = endTime; - fResolution = Math.max(1, (fZoomEndTime - fZoomStartTime) / fDisplayWidth); - fMonitor = new NullProgressMonitor(); - } - - @Override - public void run() { - ArrayList entryList = null; - synchronized (fEntryListSyncObj) { - entryList = fEntryList; - } - if (entryList == null) { - return; - } - for (ControlFlowEntry entry : entryList) { - if (fMonitor.isCanceled()) { - break; - } - zoom(entry, fMonitor); - } - } - - private void zoom(ControlFlowEntry entry, IProgressMonitor monitor) { - if (fZoomStartTime <= fStartTime && fZoomEndTime >= fEndTime) { - entry.setZoomedEventList(null); - } else { - List zoomedEventList = getEventList(entry, fZoomStartTime, fZoomEndTime, fResolution, monitor); - if (zoomedEventList != null) { - entry.setZoomedEventList(zoomedEventList); - } - } - redraw(); - for (ControlFlowEntry child : entry.getChildren()) { - if (fMonitor.isCanceled()) { - return; - } - zoom(child, monitor); - } - } - - public void cancel() { - fMonitor.setCanceled(true); - } - } - - // ------------------------------------------------------------------------ - // Constructors - // ------------------------------------------------------------------------ - - /** - * Constructor - */ - public ControlFlowView() { - super(ID); - fDisplayWidth = Display.getDefault().getBounds().width; - } - - // ------------------------------------------------------------------------ - // ViewPart - // ------------------------------------------------------------------------ - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.views.TmfView#createPartControl(org.eclipse.swt.widgets.Composite) - */ - @Override - public void createPartControl(Composite parent) { - fTimeGraphCombo = new TimeGraphCombo(parent, SWT.NONE); - - fTimeGraphCombo.setTreeContentProvider(new TreeContentProvider()); - - fTimeGraphCombo.setTreeLabelProvider(new TreeLabelProvider()); - - fTimeGraphCombo.setTimeGraphProvider(new ControlFlowPresentationProvider()); - - fTimeGraphCombo.setTreeColumns(COLUMN_NAMES); - - fTimeGraphCombo.getTimeGraphViewer().addRangeListener(new ITimeGraphRangeListener() { - @Override - public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { - final long startTime = event.getStartTime(); - final long endTime = event.getEndTime(); - TmfTimeRange range = new TmfTimeRange(new CtfTmfTimestamp(startTime), new CtfTmfTimestamp(endTime)); - TmfTimestamp time = new CtfTmfTimestamp(fTimeGraphCombo.getTimeGraphViewer().getSelectedTime()); - broadcast(new TmfRangeSynchSignal(ControlFlowView.this, range, time)); - if (fZoomThread != null) { - fZoomThread.cancel(); - } - startZoomThread(startTime, endTime); - } - }); - - fTimeGraphCombo.getTimeGraphViewer().addTimeListener(new ITimeGraphTimeListener() { - @Override - public void timeSelected(TimeGraphTimeEvent event) { - long time = event.getTime(); - broadcast(new TmfTimeSynchSignal(ControlFlowView.this, new CtfTmfTimestamp(time))); - } - }); - - fTimeGraphCombo.addSelectionListener(new ITimeGraphSelectionListener() { - @Override - public void selectionChanged(TimeGraphSelectionEvent event) { - //ITimeGraphEntry selection = event.getSelection(); - } - }); - - fTimeGraphCombo.getTimeGraphViewer().setTimeCalendarFormat(true); - - final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ - @Override - public void run() { - if (TmfExperiment.getCurrentExperiment() != null) { - selectExperiment(TmfExperiment.getCurrentExperiment()); - } - } - }; - thread.start(); - - // View Action Handling - makeActions(); - contributeToActionBars(); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#setFocus() - */ - @Override - public void setFocus() { - fTimeGraphCombo.setFocus(); - } - - // ------------------------------------------------------------------------ - // Signal handlers - // ------------------------------------------------------------------------ - - /** - * Handler for the experiment selected signal - * - * @param signal - * The signal that's received - */ - @TmfSignalHandler - public void experimentSelected(final TmfExperimentSelectedSignal signal) { - if (signal.getExperiment().equals(fSelectedExperiment)) { - return; - } - - final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ - @Override - public void run() { - selectExperiment(signal.getExperiment()); - } - }; - thread.start(); - } - - /** - * Handler for the synch signal - * - * @param signal - * The signal that's received - */ - @TmfSignalHandler - public void synchToTime(final TmfTimeSynchSignal signal) { - if (signal.getSource() == this || fSelectedExperiment == null || fSelectedExperiment.getTraces() == null) { - return; - } - final long time = signal.getCurrentTime().normalize(0, -9).getValue(); - - int thread = -1; - for (ITmfTrace trace : fSelectedExperiment.getTraces()) { - if (thread > 0) { - break; - } - if (trace instanceof CtfKernelTrace) { - CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; - IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); - if (time >= ssq.getStartTime() && time <= ssq.getCurrentEndTime()) { - List currentThreadQuarks = ssq.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$ - for (int currentThreadQuark : currentThreadQuarks) { - try { - ITmfStateInterval currentThreadInterval = ssq.querySingleState(time, currentThreadQuark); - int currentThread = currentThreadInterval.getStateValue().unboxInt(); - if (currentThread > 0) { - int statusQuark = ssq.getQuarkAbsolute(Attributes.THREADS, Integer.toString(currentThread), Attributes.STATUS); - ITmfStateInterval statusInterval = ssq.querySingleState(time, statusQuark); - if (statusInterval.getStartTime() == time) { - thread = currentThread; - break; - } - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - } - } - } - } - final int selectedThread = thread; - - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphCombo.isDisposed()) { - return; - } - fTimeGraphCombo.getTimeGraphViewer().setSelectedTime(time, true); - startZoomThread(fTimeGraphCombo.getTimeGraphViewer().getTime0(), fTimeGraphCombo.getTimeGraphViewer().getTime1()); - - if (selectedThread > 0) { - for (Object element : fTimeGraphCombo.getTimeGraphViewer().getExpandedElements()) { - if (element instanceof ControlFlowEntry) { - ControlFlowEntry entry = (ControlFlowEntry) element; - if (entry.getThreadId() == selectedThread) { - fTimeGraphCombo.setSelection(entry); - break; - } - } - } - } - } - }); - } - - /** - * Handler for the range sync signal - * - * @param signal - * The signal that's received - */ - @TmfSignalHandler - public void synchToRange(final TmfRangeSynchSignal signal) { - if (signal.getSource() == this || fSelectedExperiment == null) { - return; - } - final long startTime = signal.getCurrentRange().getStartTime().normalize(0, -9).getValue(); - final long endTime = signal.getCurrentRange().getEndTime().normalize(0, -9).getValue(); - final long time = signal.getCurrentTime().normalize(0, -9).getValue(); - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphCombo.isDisposed()) { - return; - } - fTimeGraphCombo.getTimeGraphViewer().setStartFinishTime(startTime, endTime); - fTimeGraphCombo.getTimeGraphViewer().setSelectedTime(time, false); - startZoomThread(startTime, endTime); - } - }); - } - - /** - * Handler for the state system build completed signal - * - * @param signal - * The signal that's received - */ - @TmfSignalHandler - public void stateSystemBuildCompleted (final TmfStateSystemBuildCompleted signal) { - final TmfExperiment selectedExperiment = fSelectedExperiment; - if (selectedExperiment == null || selectedExperiment.getTraces() == null) { - return; - } - for (ITmfTrace trace : selectedExperiment.getTraces()) { - if (trace == signal.getTrace() && trace instanceof CtfKernelTrace) { - final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ - @Override - public void run() { - // rebuild the model - selectExperiment(selectedExperiment); - } - }; - thread.start(); - } - } - } - - // ------------------------------------------------------------------------ - // Internal - // ------------------------------------------------------------------------ - - @SuppressWarnings("unchecked") - private void selectExperiment(TmfExperiment experiment) { - fStartTime = Long.MAX_VALUE; - fEndTime = Long.MIN_VALUE; - fSelectedExperiment = (TmfExperiment) experiment; - ArrayList rootList = new ArrayList(); - for (ITmfTrace trace : experiment.getTraces()) { - if (trace instanceof CtfKernelTrace) { - ArrayList entryList = new ArrayList(); - CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; - IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); - long start = ssq.getStartTime(); - long end = ssq.getCurrentEndTime() + 1; - fStartTime = Math.min(fStartTime, start); - fEndTime = Math.max(fEndTime, end); - List threadQuarks = ssq.getQuarks(Attributes.THREADS, "*"); //$NON-NLS-1$ - for (int threadQuark : threadQuarks) { - String threadName = ssq.getAttributeName(threadQuark); - int threadId = -1; - try { - threadId = Integer.parseInt(threadName); - } catch (NumberFormatException e1) { - continue; - } - if (threadId == 0) { // ignore the swapper thread - continue; - } - int execNameQuark = -1; - try { - try { - execNameQuark = ssq.getQuarkRelative(threadQuark, Attributes.EXEC_NAME); - } catch (AttributeNotFoundException e) { - continue; - } - int ppidQuark = ssq.getQuarkRelative(threadQuark, Attributes.PPID); - List execNameIntervals = ssq.queryHistoryRange(execNameQuark, start, end - 1); - long birthTime = -1; - for (ITmfStateInterval execNameInterval : execNameIntervals) { - if (!execNameInterval.getStateValue().isNull() && execNameInterval.getStateValue().getType() == 1) { - String execName = execNameInterval.getStateValue().unboxStr(); - long startTime = execNameInterval.getStartTime(); - long endTime = execNameInterval.getEndTime() + 1; - if (birthTime == -1) { - birthTime = startTime; - } - int ppid = -1; - if (ppidQuark != -1) { - ITmfStateInterval ppidInterval = ssq.querySingleState(startTime, ppidQuark); - ppid = ppidInterval.getStateValue().unboxInt(); - } - ControlFlowEntry entry = new ControlFlowEntry(threadQuark, ctfKernelTrace, execName, threadId, ppid, birthTime, startTime, endTime); - entryList.add(entry); - entry.addEvent(new TimeEvent(entry, startTime, endTime - startTime)); - } else { - birthTime = -1; - } - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - } - buildTree(entryList, rootList); - } - Collections.sort(rootList, fControlFlowEntryComparator); - synchronized (fEntryListSyncObj) { - fEntryList = (ArrayList) rootList.clone(); - } - refresh(INITIAL_WINDOW_OFFSET); - } - for (ControlFlowEntry entry : rootList) { - buildStatusEvents(entry); - } - } - - private static void buildTree(ArrayList entryList, - ArrayList rootList) { - for (ControlFlowEntry entry : entryList) { - boolean root = true; - if (entry.getParentThreadId() > 0) { - for (ControlFlowEntry parent : entryList) { - if (parent.getThreadId() == entry.getParentThreadId() && - entry.getStartTime() >= parent.getStartTime() && - entry.getStartTime() <= parent.getEndTime()) { - parent.addChild(entry); - root = false; - break; - } - } - } - if (root) { - rootList.add(entry); - } - } - } - - private void buildStatusEvents(ControlFlowEntry entry) { - IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); - long start = ssq.getStartTime(); - long end = ssq.getCurrentEndTime() + 1; - long resolution = Math.max(1, (end - start) / fDisplayWidth); - List eventList = getEventList(entry, entry.getStartTime(), entry.getEndTime(), resolution, new NullProgressMonitor()); - entry.setEventList(eventList); - redraw(); - for (ITimeGraphEntry child : entry.getChildren()) { - buildStatusEvents((ControlFlowEntry) child); - } - } - - private static List getEventList(ControlFlowEntry entry, - long startTime, long endTime, long resolution, - IProgressMonitor monitor) { - startTime = Math.max(startTime, entry.getStartTime()); - endTime = Math.min(endTime, entry.getEndTime()); - if (endTime <= startTime) { - return null; - } - IStateSystemQuerier2 ssq = (IStateSystemQuerier2) entry.getTrace().getStateSystem(); - List eventList = null; - try { - int statusQuark = ssq.getQuarkRelative(entry.getThreadQuark(), Attributes.STATUS); - List statusIntervals = ssq.queryHistoryRange(statusQuark, startTime, endTime - 1, resolution, monitor); - eventList = new ArrayList(statusIntervals.size()); - long lastEndTime = -1; - for (ITmfStateInterval statusInterval : statusIntervals) { - if (monitor.isCanceled()) { - return null; - } - long time = statusInterval.getStartTime(); - long duration = statusInterval.getEndTime() - time + 1; - int status = -1; - try { - status = statusInterval.getStateValue().unboxInt(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - if (lastEndTime != time && lastEndTime != -1) { - eventList.add(new ControlFlowEvent(entry, lastEndTime, time - lastEndTime, 0)); - } - eventList.add(new ControlFlowEvent(entry, time, duration, status)); - lastEndTime = time + duration; - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } - return eventList; - } - - private void refresh(final long windowRange) { - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphCombo.isDisposed()) { - return; - } - ITimeGraphEntry[] entries = null; - synchronized (fEntryListSyncObj) { - entries = fEntryList.toArray(new ITimeGraphEntry[0]); - } - Arrays.sort(entries, fControlFlowEntryComparator); - fTimeGraphCombo.setInput(entries); - fTimeGraphCombo.getTimeGraphViewer().setTimeBounds(fStartTime, fEndTime); - - long endTime = fStartTime + windowRange; - - if (fEndTime < endTime) { - endTime = fEndTime; - } - fTimeGraphCombo.getTimeGraphViewer().setStartFinishTime(fStartTime, endTime); - for (TreeColumn column : fTimeGraphCombo.getTreeViewer().getTree().getColumns()) { - column.pack(); - } - - startZoomThread(fStartTime, endTime); - } - }); - } - - private void redraw() { - synchronized (fSyncObj) { - if (fRedrawState == State.IDLE) { - fRedrawState = State.BUSY; - } else { - fRedrawState = State.PENDING; - return; - } - } - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphCombo.isDisposed()) { - return; - } - fTimeGraphCombo.redraw(); - fTimeGraphCombo.update(); - synchronized (fSyncObj) { - if (fRedrawState == State.PENDING) { - fRedrawState = State.IDLE; - redraw(); - } else { - fRedrawState = State.IDLE; - } - } - } - }); - } - - private void startZoomThread(long startTime, long endTime) { - if (fZoomThread != null) { - fZoomThread.cancel(); - } - fZoomThread = new ZoomThread(startTime, endTime); - fZoomThread.start(); - } - - private void makeActions() { - fPreviousResourceAction = fTimeGraphCombo.getTimeGraphViewer().getPreviousItemAction(); - fPreviousResourceAction.setText(Messages.ControlFlowView_previousProcessActionNameText); - fPreviousResourceAction.setToolTipText(Messages.ControlFlowView_previousProcessActionToolTipText); - fNextResourceAction = fTimeGraphCombo.getTimeGraphViewer().getNextItemAction(); - fNextResourceAction.setText(Messages.ControlFlowView_nextProcessActionNameText); - fNextResourceAction.setToolTipText(Messages.ControlFlowView_nextProcessActionToolTipText); - } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalToolBar(bars.getToolBarManager()); - } - - private void fillLocalToolBar(IToolBarManager manager) { - manager.add(fTimeGraphCombo.getTimeGraphViewer().getShowLegendAction()); - manager.add(new Separator()); - manager.add(fTimeGraphCombo.getTimeGraphViewer().getResetScaleAction()); - manager.add(fTimeGraphCombo.getTimeGraphViewer().getPreviousEventAction()); - manager.add(fTimeGraphCombo.getTimeGraphViewer().getNextEventAction()); - manager.add(fPreviousResourceAction); - manager.add(fNextResourceAction); - manager.add(fTimeGraphCombo.getTimeGraphViewer().getZoomInAction()); - manager.add(fTimeGraphCombo.getTimeGraphViewer().getZoomOutAction()); - manager.add(new Separator()); - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; +import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; +import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTimestamp; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; +import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; +import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; +import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; +import org.eclipse.linuxtools.tmf.core.signal.TmfExperimentSelectedSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfRangeSynchSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; +import org.eclipse.linuxtools.tmf.core.signal.TmfStateSystemBuildCompleted; +import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier2; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; +import org.eclipse.linuxtools.tmf.ui.views.TmfView; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphSelectionListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphCombo; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphSelectionEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils.Resolution; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.TreeColumn; +import org.eclipse.ui.IActionBars; + +/** + * The Control Flow view main object + * + */ +public class ControlFlowView extends TmfView { + + // ------------------------------------------------------------------------ + // Constants + // ------------------------------------------------------------------------ + + /** + * View ID. + */ + public static final String ID = "org.eclipse.linuxtools.lttng2.kernel.ui.views.controlflow"; //$NON-NLS-1$ + + /** + * Initial time range + */ + private static final long INITIAL_WINDOW_OFFSET = (1L * 100 * 1000 * 1000); // .1sec + + private static final String PROCESS_COLUMN = Messages.ControlFlowView_processColumn; + private static final String TID_COLUMN = Messages.ControlFlowView_tidColumn; + private static final String PTID_COLUMN = Messages.ControlFlowView_ptidColumn; + private static final String BIRTH_TIME_COLUMN = Messages.ControlFlowView_birthTimeColumn; + private static final String TRACE_COLUMN = Messages.ControlFlowView_traceColumn; + + private final String[] COLUMN_NAMES = new String[] { + PROCESS_COLUMN, + TID_COLUMN, + PTID_COLUMN, + BIRTH_TIME_COLUMN, + TRACE_COLUMN + }; + + /** + * Redraw state enum + */ + private enum State { IDLE, BUSY, PENDING } + + // ------------------------------------------------------------------------ + // Fields + // ------------------------------------------------------------------------ + + // The timegraph combo + private TimeGraphCombo fTimeGraphCombo; + + // The selected experiment + private TmfExperiment fSelectedExperiment; + + // The timegraph entry list + private ArrayList fEntryList; + + // The time graph entry list synchronization object + final private Object fEntryListSyncObj = new Object(); + + // The start time + private long fStartTime; + + // The end time + private long fEndTime; + + // The display width + private final int fDisplayWidth; + + // The zoom thread + private ZoomThread fZoomThread; + + // The next resource action + private Action fNextResourceAction; + + // The previous resource action + private Action fPreviousResourceAction; + + // A comparator class + private final ControlFlowEntryComparator fControlFlowEntryComparator = new ControlFlowEntryComparator(); + + // The redraw state used to prevent unnecessary queuing of display runnables + private State fRedrawState = State.IDLE; + + // The redraw synchronization object + final private Object fSyncObj = new Object(); + + // ------------------------------------------------------------------------ + // Classes + // ------------------------------------------------------------------------ + + private class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + + @Override + public Object[] getElements(Object inputElement) { + return (ITimeGraphEntry[]) inputElement; + } + + @Override + public Object[] getChildren(Object parentElement) { + ITimeGraphEntry entry = (ITimeGraphEntry) parentElement; + return entry.getChildren(); + } + + @Override + public Object getParent(Object element) { + ITimeGraphEntry entry = (ITimeGraphEntry) element; + return entry.getParent(); + } + + @Override + public boolean hasChildren(Object element) { + ITimeGraphEntry entry = (ITimeGraphEntry) element; + return entry.hasChildren(); + } + + } + + private class TreeLabelProvider implements ITableLabelProvider { + + @Override + public void addListener(ILabelProviderListener listener) { + } + + @Override + public void dispose() { + } + + @Override + public boolean isLabelProperty(Object element, String property) { + return false; + } + + @Override + public void removeListener(ILabelProviderListener listener) { + } + + @Override + public Image getColumnImage(Object element, int columnIndex) { + return null; + } + + @Override + public String getColumnText(Object element, int columnIndex) { + ControlFlowEntry entry = (ControlFlowEntry) element; + if (columnIndex == 0) { + return entry.getName(); + } else if (columnIndex == 1) { + return Integer.toString(entry.getThreadId()); + } else if (columnIndex == 2) { + if (entry.getParentThreadId() > 0) { + return Integer.toString(entry.getParentThreadId()); + } + } else if (columnIndex == 3) { + return Utils.formatTime(entry.getBirthTime(), TimeFormat.ABSOLUTE, Resolution.NANOSEC); + } else if (columnIndex == 4) { + return entry.getTrace().getName(); + } + return ""; //$NON-NLS-1$ + } + + } + + private static class ControlFlowEntryComparator implements Comparator { + + @Override + public int compare(ITimeGraphEntry o1, ITimeGraphEntry o2) { + int result = 0; + + if ((o1 instanceof ControlFlowEntry) && (o2 instanceof ControlFlowEntry)) { + ControlFlowEntry entry1 = (ControlFlowEntry) o1; + ControlFlowEntry entry2 = (ControlFlowEntry) o2; + result = entry1.getTrace().getStartTime().compareTo(entry2.getTrace().getStartTime()); + if (result == 0) { + result = entry1.getTrace().getName().compareTo(entry2.getTrace().getName()); + } + if (result == 0) { + result = entry1.getThreadId() < entry2.getThreadId() ? -1 : entry1.getThreadId() > entry2.getThreadId() ? 1 : 0; + } + } + + if (result == 0) { + result = o1.getStartTime() < o2.getStartTime() ? -1 : o1.getStartTime() > o2.getStartTime() ? 1 : 0; + } + + return result; + } + } + + + private class ZoomThread extends Thread { + private final long fZoomStartTime; + private final long fZoomEndTime; + private final long fResolution; + private final IProgressMonitor fMonitor; + + public ZoomThread(long startTime, long endTime) { + super("ControlFlowView zoom"); //$NON-NLS-1$ + fZoomStartTime = startTime; + fZoomEndTime = endTime; + fResolution = Math.max(1, (fZoomEndTime - fZoomStartTime) / fDisplayWidth); + fMonitor = new NullProgressMonitor(); + } + + @Override + public void run() { + ArrayList entryList = null; + synchronized (fEntryListSyncObj) { + entryList = fEntryList; + } + if (entryList == null) { + return; + } + for (ControlFlowEntry entry : entryList) { + if (fMonitor.isCanceled()) { + break; + } + zoom(entry, fMonitor); + } + } + + private void zoom(ControlFlowEntry entry, IProgressMonitor monitor) { + if (fZoomStartTime <= fStartTime && fZoomEndTime >= fEndTime) { + entry.setZoomedEventList(null); + } else { + List zoomedEventList = getEventList(entry, fZoomStartTime, fZoomEndTime, fResolution, monitor); + if (zoomedEventList != null) { + entry.setZoomedEventList(zoomedEventList); + } + } + redraw(); + for (ControlFlowEntry child : entry.getChildren()) { + if (fMonitor.isCanceled()) { + return; + } + zoom(child, monitor); + } + } + + public void cancel() { + fMonitor.setCanceled(true); + } + } + + // ------------------------------------------------------------------------ + // Constructors + // ------------------------------------------------------------------------ + + /** + * Constructor + */ + public ControlFlowView() { + super(ID); + fDisplayWidth = Display.getDefault().getBounds().width; + } + + // ------------------------------------------------------------------------ + // ViewPart + // ------------------------------------------------------------------------ + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.views.TmfView#createPartControl(org.eclipse.swt.widgets.Composite) + */ + @Override + public void createPartControl(Composite parent) { + fTimeGraphCombo = new TimeGraphCombo(parent, SWT.NONE); + + fTimeGraphCombo.setTreeContentProvider(new TreeContentProvider()); + + fTimeGraphCombo.setTreeLabelProvider(new TreeLabelProvider()); + + fTimeGraphCombo.setTimeGraphProvider(new ControlFlowPresentationProvider()); + + fTimeGraphCombo.setTreeColumns(COLUMN_NAMES); + + fTimeGraphCombo.getTimeGraphViewer().addRangeListener(new ITimeGraphRangeListener() { + @Override + public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { + final long startTime = event.getStartTime(); + final long endTime = event.getEndTime(); + TmfTimeRange range = new TmfTimeRange(new CtfTmfTimestamp(startTime), new CtfTmfTimestamp(endTime)); + TmfTimestamp time = new CtfTmfTimestamp(fTimeGraphCombo.getTimeGraphViewer().getSelectedTime()); + broadcast(new TmfRangeSynchSignal(ControlFlowView.this, range, time)); + if (fZoomThread != null) { + fZoomThread.cancel(); + } + startZoomThread(startTime, endTime); + } + }); + + fTimeGraphCombo.getTimeGraphViewer().addTimeListener(new ITimeGraphTimeListener() { + @Override + public void timeSelected(TimeGraphTimeEvent event) { + long time = event.getTime(); + broadcast(new TmfTimeSynchSignal(ControlFlowView.this, new CtfTmfTimestamp(time))); + } + }); + + fTimeGraphCombo.addSelectionListener(new ITimeGraphSelectionListener() { + @Override + public void selectionChanged(TimeGraphSelectionEvent event) { + //ITimeGraphEntry selection = event.getSelection(); + } + }); + + fTimeGraphCombo.getTimeGraphViewer().setTimeCalendarFormat(true); + + final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ + @Override + public void run() { + if (TmfExperiment.getCurrentExperiment() != null) { + selectExperiment(TmfExperiment.getCurrentExperiment()); + } + } + }; + thread.start(); + + // View Action Handling + makeActions(); + contributeToActionBars(); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#setFocus() + */ + @Override + public void setFocus() { + fTimeGraphCombo.setFocus(); + } + + // ------------------------------------------------------------------------ + // Signal handlers + // ------------------------------------------------------------------------ + + /** + * Handler for the experiment selected signal + * + * @param signal + * The signal that's received + */ + @TmfSignalHandler + public void experimentSelected(final TmfExperimentSelectedSignal signal) { + if (signal.getExperiment().equals(fSelectedExperiment)) { + return; + } + + final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ + @Override + public void run() { + selectExperiment(signal.getExperiment()); + } + }; + thread.start(); + } + + /** + * Handler for the synch signal + * + * @param signal + * The signal that's received + */ + @TmfSignalHandler + public void synchToTime(final TmfTimeSynchSignal signal) { + if (signal.getSource() == this || fSelectedExperiment == null || fSelectedExperiment.getTraces() == null) { + return; + } + final long time = signal.getCurrentTime().normalize(0, -9).getValue(); + + int thread = -1; + for (ITmfTrace trace : fSelectedExperiment.getTraces()) { + if (thread > 0) { + break; + } + if (trace instanceof CtfKernelTrace) { + CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; + IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); + if (time >= ssq.getStartTime() && time <= ssq.getCurrentEndTime()) { + List currentThreadQuarks = ssq.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$ + for (int currentThreadQuark : currentThreadQuarks) { + try { + ITmfStateInterval currentThreadInterval = ssq.querySingleState(time, currentThreadQuark); + int currentThread = currentThreadInterval.getStateValue().unboxInt(); + if (currentThread > 0) { + int statusQuark = ssq.getQuarkAbsolute(Attributes.THREADS, Integer.toString(currentThread), Attributes.STATUS); + ITmfStateInterval statusInterval = ssq.querySingleState(time, statusQuark); + if (statusInterval.getStartTime() == time) { + thread = currentThread; + break; + } + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + } + } + } + } + final int selectedThread = thread; + + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphCombo.isDisposed()) { + return; + } + fTimeGraphCombo.getTimeGraphViewer().setSelectedTime(time, true); + startZoomThread(fTimeGraphCombo.getTimeGraphViewer().getTime0(), fTimeGraphCombo.getTimeGraphViewer().getTime1()); + + if (selectedThread > 0) { + for (Object element : fTimeGraphCombo.getTimeGraphViewer().getExpandedElements()) { + if (element instanceof ControlFlowEntry) { + ControlFlowEntry entry = (ControlFlowEntry) element; + if (entry.getThreadId() == selectedThread) { + fTimeGraphCombo.setSelection(entry); + break; + } + } + } + } + } + }); + } + + /** + * Handler for the range sync signal + * + * @param signal + * The signal that's received + */ + @TmfSignalHandler + public void synchToRange(final TmfRangeSynchSignal signal) { + if (signal.getSource() == this || fSelectedExperiment == null) { + return; + } + final long startTime = signal.getCurrentRange().getStartTime().normalize(0, -9).getValue(); + final long endTime = signal.getCurrentRange().getEndTime().normalize(0, -9).getValue(); + final long time = signal.getCurrentTime().normalize(0, -9).getValue(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphCombo.isDisposed()) { + return; + } + fTimeGraphCombo.getTimeGraphViewer().setStartFinishTime(startTime, endTime); + fTimeGraphCombo.getTimeGraphViewer().setSelectedTime(time, false); + startZoomThread(startTime, endTime); + } + }); + } + + /** + * Handler for the state system build completed signal + * + * @param signal + * The signal that's received + */ + @TmfSignalHandler + public void stateSystemBuildCompleted (final TmfStateSystemBuildCompleted signal) { + final TmfExperiment selectedExperiment = fSelectedExperiment; + if (selectedExperiment == null || selectedExperiment.getTraces() == null) { + return; + } + for (ITmfTrace trace : selectedExperiment.getTraces()) { + if (trace == signal.getTrace() && trace instanceof CtfKernelTrace) { + final Thread thread = new Thread("ControlFlowView build") { //$NON-NLS-1$ + @Override + public void run() { + // rebuild the model + selectExperiment(selectedExperiment); + } + }; + thread.start(); + } + } + } + + // ------------------------------------------------------------------------ + // Internal + // ------------------------------------------------------------------------ + + @SuppressWarnings("unchecked") + private void selectExperiment(TmfExperiment experiment) { + fStartTime = Long.MAX_VALUE; + fEndTime = Long.MIN_VALUE; + fSelectedExperiment = (TmfExperiment) experiment; + ArrayList rootList = new ArrayList(); + for (ITmfTrace trace : experiment.getTraces()) { + if (trace instanceof CtfKernelTrace) { + ArrayList entryList = new ArrayList(); + CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; + IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); + long start = ssq.getStartTime(); + long end = ssq.getCurrentEndTime() + 1; + fStartTime = Math.min(fStartTime, start); + fEndTime = Math.max(fEndTime, end); + List threadQuarks = ssq.getQuarks(Attributes.THREADS, "*"); //$NON-NLS-1$ + for (int threadQuark : threadQuarks) { + String threadName = ssq.getAttributeName(threadQuark); + int threadId = -1; + try { + threadId = Integer.parseInt(threadName); + } catch (NumberFormatException e1) { + continue; + } + if (threadId == 0) { // ignore the swapper thread + continue; + } + int execNameQuark = -1; + try { + try { + execNameQuark = ssq.getQuarkRelative(threadQuark, Attributes.EXEC_NAME); + } catch (AttributeNotFoundException e) { + continue; + } + int ppidQuark = ssq.getQuarkRelative(threadQuark, Attributes.PPID); + List execNameIntervals = ssq.queryHistoryRange(execNameQuark, start, end - 1); + long birthTime = -1; + for (ITmfStateInterval execNameInterval : execNameIntervals) { + if (!execNameInterval.getStateValue().isNull() && execNameInterval.getStateValue().getType() == 1) { + String execName = execNameInterval.getStateValue().unboxStr(); + long startTime = execNameInterval.getStartTime(); + long endTime = execNameInterval.getEndTime() + 1; + if (birthTime == -1) { + birthTime = startTime; + } + int ppid = -1; + if (ppidQuark != -1) { + ITmfStateInterval ppidInterval = ssq.querySingleState(startTime, ppidQuark); + ppid = ppidInterval.getStateValue().unboxInt(); + } + ControlFlowEntry entry = new ControlFlowEntry(threadQuark, ctfKernelTrace, execName, threadId, ppid, birthTime, startTime, endTime); + entryList.add(entry); + entry.addEvent(new TimeEvent(entry, startTime, endTime - startTime)); + } else { + birthTime = -1; + } + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + } + buildTree(entryList, rootList); + } + Collections.sort(rootList, fControlFlowEntryComparator); + synchronized (fEntryListSyncObj) { + fEntryList = (ArrayList) rootList.clone(); + } + refresh(INITIAL_WINDOW_OFFSET); + } + for (ControlFlowEntry entry : rootList) { + buildStatusEvents(entry); + } + } + + private static void buildTree(ArrayList entryList, + ArrayList rootList) { + for (ControlFlowEntry entry : entryList) { + boolean root = true; + if (entry.getParentThreadId() > 0) { + for (ControlFlowEntry parent : entryList) { + if (parent.getThreadId() == entry.getParentThreadId() && + entry.getStartTime() >= parent.getStartTime() && + entry.getStartTime() <= parent.getEndTime()) { + parent.addChild(entry); + root = false; + break; + } + } + } + if (root) { + rootList.add(entry); + } + } + } + + private void buildStatusEvents(ControlFlowEntry entry) { + IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); + long start = ssq.getStartTime(); + long end = ssq.getCurrentEndTime() + 1; + long resolution = Math.max(1, (end - start) / fDisplayWidth); + List eventList = getEventList(entry, entry.getStartTime(), entry.getEndTime(), resolution, new NullProgressMonitor()); + entry.setEventList(eventList); + redraw(); + for (ITimeGraphEntry child : entry.getChildren()) { + buildStatusEvents((ControlFlowEntry) child); + } + } + + private static List getEventList(ControlFlowEntry entry, + long startTime, long endTime, long resolution, + IProgressMonitor monitor) { + startTime = Math.max(startTime, entry.getStartTime()); + endTime = Math.min(endTime, entry.getEndTime()); + if (endTime <= startTime) { + return null; + } + IStateSystemQuerier2 ssq = (IStateSystemQuerier2) entry.getTrace().getStateSystem(); + List eventList = null; + try { + int statusQuark = ssq.getQuarkRelative(entry.getThreadQuark(), Attributes.STATUS); + List statusIntervals = ssq.queryHistoryRange(statusQuark, startTime, endTime - 1, resolution, monitor); + eventList = new ArrayList(statusIntervals.size()); + long lastEndTime = -1; + for (ITmfStateInterval statusInterval : statusIntervals) { + if (monitor.isCanceled()) { + return null; + } + long time = statusInterval.getStartTime(); + long duration = statusInterval.getEndTime() - time + 1; + int status = -1; + try { + status = statusInterval.getStateValue().unboxInt(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + if (lastEndTime != time && lastEndTime != -1) { + eventList.add(new ControlFlowEvent(entry, lastEndTime, time - lastEndTime, 0)); + } + eventList.add(new ControlFlowEvent(entry, time, duration, status)); + lastEndTime = time + duration; + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } + return eventList; + } + + private void refresh(final long windowRange) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphCombo.isDisposed()) { + return; + } + ITimeGraphEntry[] entries = null; + synchronized (fEntryListSyncObj) { + entries = fEntryList.toArray(new ITimeGraphEntry[0]); + } + Arrays.sort(entries, fControlFlowEntryComparator); + fTimeGraphCombo.setInput(entries); + fTimeGraphCombo.getTimeGraphViewer().setTimeBounds(fStartTime, fEndTime); + + long endTime = fStartTime + windowRange; + + if (fEndTime < endTime) { + endTime = fEndTime; + } + fTimeGraphCombo.getTimeGraphViewer().setStartFinishTime(fStartTime, endTime); + for (TreeColumn column : fTimeGraphCombo.getTreeViewer().getTree().getColumns()) { + column.pack(); + } + + startZoomThread(fStartTime, endTime); + } + }); + } + + private void redraw() { + synchronized (fSyncObj) { + if (fRedrawState == State.IDLE) { + fRedrawState = State.BUSY; + } else { + fRedrawState = State.PENDING; + return; + } + } + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphCombo.isDisposed()) { + return; + } + fTimeGraphCombo.redraw(); + fTimeGraphCombo.update(); + synchronized (fSyncObj) { + if (fRedrawState == State.PENDING) { + fRedrawState = State.IDLE; + redraw(); + } else { + fRedrawState = State.IDLE; + } + } + } + }); + } + + private void startZoomThread(long startTime, long endTime) { + if (fZoomThread != null) { + fZoomThread.cancel(); + } + fZoomThread = new ZoomThread(startTime, endTime); + fZoomThread.start(); + } + + private void makeActions() { + fPreviousResourceAction = fTimeGraphCombo.getTimeGraphViewer().getPreviousItemAction(); + fPreviousResourceAction.setText(Messages.ControlFlowView_previousProcessActionNameText); + fPreviousResourceAction.setToolTipText(Messages.ControlFlowView_previousProcessActionToolTipText); + fNextResourceAction = fTimeGraphCombo.getTimeGraphViewer().getNextItemAction(); + fNextResourceAction.setText(Messages.ControlFlowView_nextProcessActionNameText); + fNextResourceAction.setToolTipText(Messages.ControlFlowView_nextProcessActionToolTipText); + } + + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + fillLocalToolBar(bars.getToolBarManager()); + } + + private void fillLocalToolBar(IToolBarManager manager) { + manager.add(fTimeGraphCombo.getTimeGraphViewer().getShowLegendAction()); + manager.add(new Separator()); + manager.add(fTimeGraphCombo.getTimeGraphViewer().getResetScaleAction()); + manager.add(fTimeGraphCombo.getTimeGraphViewer().getPreviousEventAction()); + manager.add(fTimeGraphCombo.getTimeGraphViewer().getNextEventAction()); + manager.add(fPreviousResourceAction); + manager.add(fNextResourceAction); + manager.add(fTimeGraphCombo.getTimeGraphViewer().getZoomInAction()); + manager.add(fTimeGraphCombo.getTimeGraphViewer().getZoomOutAction()); + manager.add(new Separator()); + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEntry.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEntry.java index d2acc99600..585c2e8953 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEntry.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEntry.java @@ -1,191 +1,191 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common.EventIterator; -import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * An entry, or row, in the resource view - * - * @author Patrick Tasse - */ -public class ResourcesEntry implements ITimeGraphEntry { - - /** Type of resource */ - public static enum Type { - /** Null resources (filler rows, etc.) */ - NULL, - /** Entries for CPUs */ - CPU, - /** Entries for IRQs */ - IRQ, - /** Entries for Soft IRQ */ - SOFT_IRQ } - - private final int fQuark; - private final CtfKernelTrace fTrace; - private ITimeGraphEntry fParent = null; - private final ITimeGraphEntry[] children = null; - private final String fName; - private final Type fType; - private final int fId; - private long fStartTime; - private long fEndTime; - private List fEventList = new ArrayList(); - private List fZoomedEventList = null; - - /** - * Standard constructor - * - * @param quark - * The quark of the state system attribute whose state is shown - * on this row - * @param trace - * The trace that this view is talking about - * @param type - * Type of entry, see the Type enum - * @param id - * The integer id associated with this entry or row - */ - public ResourcesEntry(int quark, CtfKernelTrace trace, Type type, int id) { - fQuark = quark; - fTrace = trace; - fType = type; - fId = id; - fName = type.toString() + ' ' + Integer.toString(id); - } - - @Override - public ITimeGraphEntry getParent() { - return fParent; - } - - @Override - public boolean hasChildren() { - return children != null && children.length > 0; - } - - @Override - public ITimeGraphEntry[] getChildren() { - return children; - } - - @Override - public String getName() { - return fName; - } - - @Override - public long getStartTime() { - return fStartTime; - } - - @Override - public long getEndTime() { - return fEndTime; - } - - @Override - public boolean hasTimeEvents() { - return true; - } - - @Override - public Iterator getTimeEventsIterator() { - return new EventIterator(fEventList, fZoomedEventList); - } - - @Override - public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { - return new EventIterator(fEventList, fZoomedEventList, startTime, stopTime); - } - - /** - * Assign a parent entry to this one, to organize them in a tree in the - * view. - * - * @param parent - * The parent entry - */ - public void setParent(ITimeGraphEntry parent) { - fParent = parent; - } - - /** - * Retrieve the attribute quark that's represented by this entry. - * - * @return The integer quark - */ - public int getQuark() { - return fQuark; - } - - /** - * Retrieve the trace that is associated to this Resource view. - * - * @return The LTTng 2 kernel trace - */ - public CtfKernelTrace getTrace() { - return fTrace; - } - - /** - * Get the entry Type of this entry. Uses the inner Type enum. - * - * @return The entry type - */ - public Type getType() { - return fType; - } - - /** - * Get the integer ID associated with this entry. - * - * @return The ID - */ - public int getId() { - return fId; - } - - /** - * Assign the target event list to this view. - * - * @param eventList - * The list of time events - */ - public void setEventList(List eventList) { - fEventList = eventList; - if (eventList != null && eventList.size() > 0) { - fStartTime = eventList.get(0).getTime(); - ITimeEvent lastEvent = eventList.get(eventList.size() - 1); - fEndTime = lastEvent.getTime() + lastEvent.getDuration(); - } - } - - /** - * Assign the zoomed event list to this view. - * - * @param eventList - * The list of "zoomed" time events - */ - public void setZoomedEventList(List eventList) { - fZoomedEventList = eventList; - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.common.EventIterator; +import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * An entry, or row, in the resource view + * + * @author Patrick Tasse + */ +public class ResourcesEntry implements ITimeGraphEntry { + + /** Type of resource */ + public static enum Type { + /** Null resources (filler rows, etc.) */ + NULL, + /** Entries for CPUs */ + CPU, + /** Entries for IRQs */ + IRQ, + /** Entries for Soft IRQ */ + SOFT_IRQ } + + private final int fQuark; + private final CtfKernelTrace fTrace; + private ITimeGraphEntry fParent = null; + private final ITimeGraphEntry[] children = null; + private final String fName; + private final Type fType; + private final int fId; + private long fStartTime; + private long fEndTime; + private List fEventList = new ArrayList(); + private List fZoomedEventList = null; + + /** + * Standard constructor + * + * @param quark + * The quark of the state system attribute whose state is shown + * on this row + * @param trace + * The trace that this view is talking about + * @param type + * Type of entry, see the Type enum + * @param id + * The integer id associated with this entry or row + */ + public ResourcesEntry(int quark, CtfKernelTrace trace, Type type, int id) { + fQuark = quark; + fTrace = trace; + fType = type; + fId = id; + fName = type.toString() + ' ' + Integer.toString(id); + } + + @Override + public ITimeGraphEntry getParent() { + return fParent; + } + + @Override + public boolean hasChildren() { + return children != null && children.length > 0; + } + + @Override + public ITimeGraphEntry[] getChildren() { + return children; + } + + @Override + public String getName() { + return fName; + } + + @Override + public long getStartTime() { + return fStartTime; + } + + @Override + public long getEndTime() { + return fEndTime; + } + + @Override + public boolean hasTimeEvents() { + return true; + } + + @Override + public Iterator getTimeEventsIterator() { + return new EventIterator(fEventList, fZoomedEventList); + } + + @Override + public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { + return new EventIterator(fEventList, fZoomedEventList, startTime, stopTime); + } + + /** + * Assign a parent entry to this one, to organize them in a tree in the + * view. + * + * @param parent + * The parent entry + */ + public void setParent(ITimeGraphEntry parent) { + fParent = parent; + } + + /** + * Retrieve the attribute quark that's represented by this entry. + * + * @return The integer quark + */ + public int getQuark() { + return fQuark; + } + + /** + * Retrieve the trace that is associated to this Resource view. + * + * @return The LTTng 2 kernel trace + */ + public CtfKernelTrace getTrace() { + return fTrace; + } + + /** + * Get the entry Type of this entry. Uses the inner Type enum. + * + * @return The entry type + */ + public Type getType() { + return fType; + } + + /** + * Get the integer ID associated with this entry. + * + * @return The ID + */ + public int getId() { + return fId; + } + + /** + * Assign the target event list to this view. + * + * @param eventList + * The list of time events + */ + public void setEventList(List eventList) { + fEventList = eventList; + if (eventList != null && eventList.size() > 0) { + fStartTime = eventList.get(0).getTime(); + ITimeEvent lastEvent = eventList.get(eventList.size() - 1); + fEndTime = lastEvent.getTime() + lastEvent.getDuration(); + } + } + + /** + * Assign the zoomed event list to this view. + * + * @param eventList + * The list of "zoomed" time events + */ + public void setZoomedEventList(List eventList) { + fZoomedEventList = eventList; + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEvent.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEvent.java index a2714f71a3..ab7361d1e4 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEvent.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesEvent.java @@ -1,79 +1,79 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; - -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; - -/** - * Time Event implementation specific to the Resource View - * - * @author Patrick Tasse - */ -public class ResourcesEvent extends TimeEvent { - - private final Type fType; - private int fValue; - - /** - * Standard constructor - * - * @param entry - * The entry that this event affects - * @param time - * The start time of the event - * @param duration - * The duration of the event - * @param value - * The value type associated to this event - */ - public ResourcesEvent(ResourcesEntry entry, long time, long duration, - int value) { - super(entry, time, duration); - fType = entry.getType(); - fValue = value; - } - - /** - * Base constructor, with no value assigned - * - * @param entry - * The entry that this event affects - * @param time - * The start time of the event - * @param duration - * The duration of the event - */ - public ResourcesEvent(ResourcesEntry entry, long time, long duration) { - super(entry, time, duration); - fType = Type.NULL; - } - - /** - * Retrieve the value associated with this event - * - * @return The integer value - */ - public int getValue() { - return fValue; - } - - /** - * Retrieve the type of this entry. Uses the ResourcesEntry.Type interface. - * - * @return The entry type - */ - public Type getType() { - return fType; - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; + +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; + +/** + * Time Event implementation specific to the Resource View + * + * @author Patrick Tasse + */ +public class ResourcesEvent extends TimeEvent { + + private final Type fType; + private int fValue; + + /** + * Standard constructor + * + * @param entry + * The entry that this event affects + * @param time + * The start time of the event + * @param duration + * The duration of the event + * @param value + * The value type associated to this event + */ + public ResourcesEvent(ResourcesEntry entry, long time, long duration, + int value) { + super(entry, time, duration); + fType = entry.getType(); + fValue = value; + } + + /** + * Base constructor, with no value assigned + * + * @param entry + * The entry that this event affects + * @param time + * The start time of the event + * @param duration + * The duration of the event + */ + public ResourcesEvent(ResourcesEntry entry, long time, long duration) { + super(entry, time, duration); + fType = Type.NULL; + } + + /** + * Retrieve the value associated with this event + * + * @return The integer value + */ + public int getValue() { + return fValue; + } + + /** + * Retrieve the type of this entry. Uses the ResourcesEntry.Type interface. + * + * @return The entry type + */ + public Type getType() { + return fType; + } +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesPresentationProvider.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesPresentationProvider.java index d53de1f102..e4a149bc5a 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesPresentationProvider.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesPresentationProvider.java @@ -1,223 +1,223 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; -import org.eclipse.linuxtools.internal.lttng2.kernel.core.StateValues; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; -import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; -import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; -import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; -import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.swt.graphics.RGB; - -/** - * Presentation provider for the Resource view, based on the generic TMF - * presentation provider. - * - * @author Patrick Tasse - */ -public class ResourcesPresentationProvider extends TimeGraphPresentationProvider { - - private enum State { - UNKNOWN (new RGB(100, 100, 100)), - IDLE (new RGB(200, 200, 200)), - USERMODE (new RGB(0, 200, 0)), - SYSCALL (new RGB(0, 0, 200)), - IRQ (new RGB(200, 100, 100)), - SOFT_IRQ (new RGB(200, 150, 100)), - IRQ_ACTIVE (new RGB(200, 100, 100)), - SOFT_IRQ_RAISED (new RGB(200, 200, 0)), - SOFT_IRQ_ACTIVE (new RGB(200, 150, 100)); - - public final RGB rgb; - - private State (RGB rgb) { - this.rgb = rgb; - } - } - - @Override - public String getStateTypeName() { - return Messages.ResourcesView_stateTypeName; - } - - @Override - public StateItem[] getStateTable() { - StateItem[] stateTable = new StateItem[State.values().length]; - for (int i = 0; i < stateTable.length; i++) { - State state = State.values()[i]; - stateTable[i] = new StateItem(state.rgb, state.toString()); - } - return stateTable; - } - - @Override - public int getStateTableIndex(ITimeEvent event) { - if (event instanceof ResourcesEvent) { - ResourcesEvent resourcesEvent = (ResourcesEvent) event; - if (resourcesEvent.getType() == Type.CPU) { - int status = resourcesEvent.getValue(); - if (status == StateValues.CPU_STATUS_IDLE) { - return State.IDLE.ordinal(); - } else if (status == StateValues.CPU_STATUS_RUN_USERMODE) { - return State.USERMODE.ordinal(); - } else if (status == StateValues.CPU_STATUS_RUN_SYSCALL) { - return State.SYSCALL.ordinal(); - } else if (status == StateValues.CPU_STATUS_IRQ) { - return State.IRQ.ordinal(); - } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { - return State.SOFT_IRQ.ordinal(); - } - } else if (resourcesEvent.getType() == Type.IRQ) { - return State.IRQ_ACTIVE.ordinal(); - } else if (resourcesEvent.getType() == Type.SOFT_IRQ) { - int cpu = resourcesEvent.getValue(); - if (cpu == StateValues.SOFT_IRQ_RAISED) { - return State.SOFT_IRQ_RAISED.ordinal(); - } - return State.SOFT_IRQ_ACTIVE.ordinal(); - } else { - return -1; // NULL - } - } - return State.UNKNOWN.ordinal(); - } - - @Override - public String getEventName(ITimeEvent event) { - if (event instanceof ResourcesEvent) { - ResourcesEvent resourcesEvent = (ResourcesEvent) event; - if (resourcesEvent.getType() == Type.CPU) { - int status = resourcesEvent.getValue(); - if (status == StateValues.CPU_STATUS_IDLE) { - return State.IDLE.toString(); - } else if (status == StateValues.CPU_STATUS_RUN_USERMODE) { - return State.USERMODE.toString(); - } else if (status == StateValues.CPU_STATUS_RUN_SYSCALL) { - return State.SYSCALL.toString(); - } else if (status == StateValues.CPU_STATUS_IRQ) { - return State.IRQ.toString(); - } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { - return State.SOFT_IRQ.toString(); - } - } else if (resourcesEvent.getType() == Type.IRQ) { - return State.IRQ_ACTIVE.toString(); - } else if (resourcesEvent.getType() == Type.SOFT_IRQ) { - int cpu = resourcesEvent.getValue(); - if (cpu == StateValues.SOFT_IRQ_RAISED) { - return State.SOFT_IRQ_RAISED.toString(); - } - return State.SOFT_IRQ_ACTIVE.toString(); - } else { - return null; - } - } - return State.UNKNOWN.toString(); - } - - @Override - public Map getEventHoverToolTipInfo(ITimeEvent event) { - - Map retMap = new HashMap(); - if (event instanceof ResourcesEvent) { - - ResourcesEvent resourcesEvent = (ResourcesEvent) event; - - // Check for IRQ or Soft_IRQ type - if (resourcesEvent.getType().equals(Type.IRQ) || resourcesEvent.getType().equals(Type.SOFT_IRQ)) { - - // Get CPU of IRQ or SoftIRQ and provide it for the tooltip display - int cpu = resourcesEvent.getValue(); - if (cpu >= 0) { - retMap.put(Messages.ResourcesView_attributeCpuName, String.valueOf(cpu)); - } - } - - // Check for type CPU - if (resourcesEvent.getType().equals(Type.CPU)) { - int status = resourcesEvent.getValue(); - - if (status == StateValues.CPU_STATUS_IRQ) { - // In IRQ state get the IRQ that caused the interruption - ResourcesEntry entry = (ResourcesEntry) event.getEntry(); - IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); - int cpu = entry.getId(); - - IStateSystemQuerier ss = entry.getTrace().getStateSystem(); - try { - List fullState = ss.queryFullState(event.getTime()); - List irqQuarks = ss.getQuarks(Attributes.RESOURCES, Attributes.IRQS, "*"); //$NON-NLS-1$ - - for (int irqQuark : irqQuarks) { - if (fullState.get(irqQuark).getStateValue().unboxInt() == cpu) { - ITmfStateInterval value = ssq.querySingleState(event.getTime(), irqQuark); - if (!value.getStateValue().isNull()) { - int irq = Integer.parseInt(ssq.getAttributeName(irqQuark)); - retMap.put(Messages.ResourcesView_attributeIrqName, String.valueOf(irq)); - } - break; - } - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { - // In SOFT_IRQ state get the SOFT_IRQ that caused the interruption - ResourcesEntry entry = (ResourcesEntry) event.getEntry(); - IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); - int cpu = entry.getId(); - - IStateSystemQuerier ss = entry.getTrace().getStateSystem(); - try { - List fullState = ss.queryFullState(event.getTime()); - List softIrqQuarks = ss.getQuarks(Attributes.RESOURCES, Attributes.SOFT_IRQS, "*"); //$NON-NLS-1$ - - for (int softIrqQuark : softIrqQuarks) { - if (fullState.get(softIrqQuark).getStateValue().unboxInt() == cpu) { - ITmfStateInterval value = ssq.querySingleState(event.getTime(), softIrqQuark); - if (!value.getStateValue().isNull()) { - int softIrq = Integer.parseInt(ssq.getAttributeName(softIrqQuark)); - retMap.put(Messages.ResourcesView_attributeSoftIrqName, String.valueOf(softIrq)); - } - break; - } - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - } - } - } - - return retMap; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; +import org.eclipse.linuxtools.internal.lttng2.kernel.core.StateValues; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; +import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; +import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; +import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; +import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.swt.graphics.RGB; + +/** + * Presentation provider for the Resource view, based on the generic TMF + * presentation provider. + * + * @author Patrick Tasse + */ +public class ResourcesPresentationProvider extends TimeGraphPresentationProvider { + + private enum State { + UNKNOWN (new RGB(100, 100, 100)), + IDLE (new RGB(200, 200, 200)), + USERMODE (new RGB(0, 200, 0)), + SYSCALL (new RGB(0, 0, 200)), + IRQ (new RGB(200, 100, 100)), + SOFT_IRQ (new RGB(200, 150, 100)), + IRQ_ACTIVE (new RGB(200, 100, 100)), + SOFT_IRQ_RAISED (new RGB(200, 200, 0)), + SOFT_IRQ_ACTIVE (new RGB(200, 150, 100)); + + public final RGB rgb; + + private State (RGB rgb) { + this.rgb = rgb; + } + } + + @Override + public String getStateTypeName() { + return Messages.ResourcesView_stateTypeName; + } + + @Override + public StateItem[] getStateTable() { + StateItem[] stateTable = new StateItem[State.values().length]; + for (int i = 0; i < stateTable.length; i++) { + State state = State.values()[i]; + stateTable[i] = new StateItem(state.rgb, state.toString()); + } + return stateTable; + } + + @Override + public int getStateTableIndex(ITimeEvent event) { + if (event instanceof ResourcesEvent) { + ResourcesEvent resourcesEvent = (ResourcesEvent) event; + if (resourcesEvent.getType() == Type.CPU) { + int status = resourcesEvent.getValue(); + if (status == StateValues.CPU_STATUS_IDLE) { + return State.IDLE.ordinal(); + } else if (status == StateValues.CPU_STATUS_RUN_USERMODE) { + return State.USERMODE.ordinal(); + } else if (status == StateValues.CPU_STATUS_RUN_SYSCALL) { + return State.SYSCALL.ordinal(); + } else if (status == StateValues.CPU_STATUS_IRQ) { + return State.IRQ.ordinal(); + } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { + return State.SOFT_IRQ.ordinal(); + } + } else if (resourcesEvent.getType() == Type.IRQ) { + return State.IRQ_ACTIVE.ordinal(); + } else if (resourcesEvent.getType() == Type.SOFT_IRQ) { + int cpu = resourcesEvent.getValue(); + if (cpu == StateValues.SOFT_IRQ_RAISED) { + return State.SOFT_IRQ_RAISED.ordinal(); + } + return State.SOFT_IRQ_ACTIVE.ordinal(); + } else { + return -1; // NULL + } + } + return State.UNKNOWN.ordinal(); + } + + @Override + public String getEventName(ITimeEvent event) { + if (event instanceof ResourcesEvent) { + ResourcesEvent resourcesEvent = (ResourcesEvent) event; + if (resourcesEvent.getType() == Type.CPU) { + int status = resourcesEvent.getValue(); + if (status == StateValues.CPU_STATUS_IDLE) { + return State.IDLE.toString(); + } else if (status == StateValues.CPU_STATUS_RUN_USERMODE) { + return State.USERMODE.toString(); + } else if (status == StateValues.CPU_STATUS_RUN_SYSCALL) { + return State.SYSCALL.toString(); + } else if (status == StateValues.CPU_STATUS_IRQ) { + return State.IRQ.toString(); + } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { + return State.SOFT_IRQ.toString(); + } + } else if (resourcesEvent.getType() == Type.IRQ) { + return State.IRQ_ACTIVE.toString(); + } else if (resourcesEvent.getType() == Type.SOFT_IRQ) { + int cpu = resourcesEvent.getValue(); + if (cpu == StateValues.SOFT_IRQ_RAISED) { + return State.SOFT_IRQ_RAISED.toString(); + } + return State.SOFT_IRQ_ACTIVE.toString(); + } else { + return null; + } + } + return State.UNKNOWN.toString(); + } + + @Override + public Map getEventHoverToolTipInfo(ITimeEvent event) { + + Map retMap = new HashMap(); + if (event instanceof ResourcesEvent) { + + ResourcesEvent resourcesEvent = (ResourcesEvent) event; + + // Check for IRQ or Soft_IRQ type + if (resourcesEvent.getType().equals(Type.IRQ) || resourcesEvent.getType().equals(Type.SOFT_IRQ)) { + + // Get CPU of IRQ or SoftIRQ and provide it for the tooltip display + int cpu = resourcesEvent.getValue(); + if (cpu >= 0) { + retMap.put(Messages.ResourcesView_attributeCpuName, String.valueOf(cpu)); + } + } + + // Check for type CPU + if (resourcesEvent.getType().equals(Type.CPU)) { + int status = resourcesEvent.getValue(); + + if (status == StateValues.CPU_STATUS_IRQ) { + // In IRQ state get the IRQ that caused the interruption + ResourcesEntry entry = (ResourcesEntry) event.getEntry(); + IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); + int cpu = entry.getId(); + + IStateSystemQuerier ss = entry.getTrace().getStateSystem(); + try { + List fullState = ss.queryFullState(event.getTime()); + List irqQuarks = ss.getQuarks(Attributes.RESOURCES, Attributes.IRQS, "*"); //$NON-NLS-1$ + + for (int irqQuark : irqQuarks) { + if (fullState.get(irqQuark).getStateValue().unboxInt() == cpu) { + ITmfStateInterval value = ssq.querySingleState(event.getTime(), irqQuark); + if (!value.getStateValue().isNull()) { + int irq = Integer.parseInt(ssq.getAttributeName(irqQuark)); + retMap.put(Messages.ResourcesView_attributeIrqName, String.valueOf(irq)); + } + break; + } + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + } else if (status == StateValues.CPU_STATUS_SOFTIRQ) { + // In SOFT_IRQ state get the SOFT_IRQ that caused the interruption + ResourcesEntry entry = (ResourcesEntry) event.getEntry(); + IStateSystemQuerier ssq = entry.getTrace().getStateSystem(); + int cpu = entry.getId(); + + IStateSystemQuerier ss = entry.getTrace().getStateSystem(); + try { + List fullState = ss.queryFullState(event.getTime()); + List softIrqQuarks = ss.getQuarks(Attributes.RESOURCES, Attributes.SOFT_IRQS, "*"); //$NON-NLS-1$ + + for (int softIrqQuark : softIrqQuarks) { + if (fullState.get(softIrqQuark).getStateValue().unboxInt() == cpu) { + ITmfStateInterval value = ssq.querySingleState(event.getTime(), softIrqQuark); + if (!value.getStateValue().isNull()) { + int softIrq = Integer.parseInt(ssq.getAttributeName(softIrqQuark)); + retMap.put(Messages.ResourcesView_attributeSoftIrqName, String.valueOf(softIrq)); + } + break; + } + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + } + } + } + + return retMap; + } + +} diff --git a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesView.java b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesView.java index 4dca24190c..7ba9aff5d1 100644 --- a/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesView.java +++ b/org.eclipse.linuxtools.lttng2.kernel.ui/src/org/eclipse/linuxtools/internal/lttng2/kernel/ui/views/resources/ResourcesView.java @@ -1,699 +1,699 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; -import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; -import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; -import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTimestamp; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; -import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; -import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; -import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; -import org.eclipse.linuxtools.tmf.core.signal.TmfExperimentSelectedSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfRangeSynchSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; -import org.eclipse.linuxtools.tmf.core.signal.TmfStateSystemBuildCompleted; -import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; -import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier2; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; -import org.eclipse.linuxtools.tmf.ui.views.TmfView; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphViewer; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IActionBars; - -/** - * Main implementation for the LTTng 2.0 kernel Resource view - * - * @author Patrick Tasse - */ -public class ResourcesView extends TmfView { - - // ------------------------------------------------------------------------ - // Constants - // ------------------------------------------------------------------------ - - /** View ID. */ - public static final String ID = "org.eclipse.linuxtools.lttng2.kernel.ui.views.resources"; //$NON-NLS-1$ - - /** Initial time range */ - private static final long INITIAL_WINDOW_OFFSET = (1L * 100 * 1000 * 1000); // .1sec - - /** - * Redraw state enum - */ - private enum State { IDLE, BUSY, PENDING } - - // ------------------------------------------------------------------------ - // Fields - // ------------------------------------------------------------------------ - - // The time graph viewer - TimeGraphViewer fTimeGraphViewer; - - // The selected experiment - private TmfExperiment fSelectedExperiment; - - // The time graph entry list - private ArrayList fEntryList; - - // The time graph entry list synchronization object - final private Object fEntryListSyncObj = new Object(); - - // The start time - private long fStartTime; - - // The end time - private long fEndTime; - - // The display width - private final int fDisplayWidth; - - // The next resource action - private Action fNextResourceAction; - - // The previous resource action - private Action fPreviousResourceAction; - - // The zoom thread - private ZoomThread fZoomThread; - - // The redraw state used to prevent unnecessary queuing of display runnables - private State fRedrawState = State.IDLE; - - // The redraw synchronization object - final private Object fSyncObj = new Object(); - - // ------------------------------------------------------------------------ - // Classes - // ------------------------------------------------------------------------ - - private class TraceEntry implements ITimeGraphEntry { - // The Trace - private final CtfKernelTrace fTrace; - // The start time - private final long fTraceStartTime; - // The end time - private final long fTraceEndTime; - // The children of the entry - private final ArrayList fChildren; - // The name of entry - private final String fName; - - public TraceEntry(CtfKernelTrace trace, String name, long startTime, long endTime) { - fTrace = trace; - fChildren = new ArrayList(); - fName = name; - fTraceStartTime = startTime; - fTraceEndTime = endTime; - } - - @Override - public ITimeGraphEntry getParent() { - return null; - } - - @Override - public boolean hasChildren() { - return fChildren != null && fChildren.size() > 0; - } - - @Override - public ResourcesEntry[] getChildren() { - return fChildren.toArray(new ResourcesEntry[0]); - } - - @Override - public String getName() { - return fName; - } - - @Override - public long getStartTime() { - return fTraceStartTime; - } - - @Override - public long getEndTime() { - return fTraceEndTime; - } - - @Override - public boolean hasTimeEvents() { - return false; - } - - @Override - public Iterator getTimeEventsIterator() { - return null; - } - - @Override - public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { - return null; - } - - public CtfKernelTrace getTrace() { - return fTrace; - } - - public void addChild(ResourcesEntry entry) { - int index; - for (index = 0; index < fChildren.size(); index++) { - ResourcesEntry other = fChildren.get(index); - if (entry.getType().compareTo(other.getType()) < 0) { - break; - } else if (entry.getType().equals(other.getType())) { - if (entry.getId() < other.getId()) { - break; - } - } - } - entry.setParent(this); - fChildren.add(index, entry); - } - } - - private static class TraceEntryComparator implements Comparator { - @Override - public int compare(ITimeGraphEntry o1, ITimeGraphEntry o2) { - int result = o1.getStartTime() < o2.getStartTime() ? -1 : o1.getStartTime() > o2.getStartTime() ? 1 : 0; - if (result == 0) { - result = o1.getName().compareTo(o2.getName()); - } - return result; - } - } - - private class ZoomThread extends Thread { - private final long fZoomStartTime; - private final long fZoomEndTime; - private final IProgressMonitor fMonitor; - - public ZoomThread(long startTime, long endTime) { - super("ResourcesView zoom"); //$NON-NLS-1$ - fZoomStartTime = startTime; - fZoomEndTime = endTime; - fMonitor = new NullProgressMonitor(); - } - - @Override - public void run() { - ArrayList entryList = null; - synchronized (fEntryListSyncObj) { - entryList = fEntryList; - } - if (entryList == null) { - return; - } - long resolution = Math.max(1, (fZoomEndTime - fZoomStartTime) / fDisplayWidth); - for (TraceEntry traceEntry : entryList) { - for (ITimeGraphEntry child : traceEntry.getChildren()) { - if (fMonitor.isCanceled()) { - break; - } - ResourcesEntry entry = (ResourcesEntry) child; - if (fZoomStartTime <= fStartTime && fZoomEndTime >= fEndTime) { - entry.setZoomedEventList(null); - } else { - List zoomedEventList = getEventList(entry, fZoomStartTime, fZoomEndTime, resolution, true, fMonitor); - if (zoomedEventList != null) { - entry.setZoomedEventList(zoomedEventList); - } - } - redraw(); - } - } - } - - public void cancel() { - fMonitor.setCanceled(true); - } - } - - // ------------------------------------------------------------------------ - // Constructors - // ------------------------------------------------------------------------ - - /** - * Default constructor - */ - public ResourcesView() { - super(ID); - fDisplayWidth = Display.getDefault().getBounds().width; - } - - // ------------------------------------------------------------------------ - // ViewPart - // ------------------------------------------------------------------------ - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.views.TmfView#createPartControl(org.eclipse.swt.widgets.Composite) - */ - @Override - public void createPartControl(Composite parent) { - fTimeGraphViewer = new TimeGraphViewer(parent, SWT.NONE); - - fTimeGraphViewer.setTimeGraphProvider(new ResourcesPresentationProvider()); - - fTimeGraphViewer.setTimeCalendarFormat(true); - - fTimeGraphViewer.addRangeListener(new ITimeGraphRangeListener() { - @Override - public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { - long startTime = event.getStartTime(); - long endTime = event.getEndTime(); - TmfTimeRange range = new TmfTimeRange(new CtfTmfTimestamp(startTime), new CtfTmfTimestamp(endTime)); - TmfTimestamp time = new CtfTmfTimestamp(fTimeGraphViewer.getSelectedTime()); - broadcast(new TmfRangeSynchSignal(ResourcesView.this, range, time)); - startZoomThread(startTime, endTime); - } - }); - - fTimeGraphViewer.addTimeListener(new ITimeGraphTimeListener() { - @Override - public void timeSelected(TimeGraphTimeEvent event) { - long time = event.getTime(); - broadcast(new TmfTimeSynchSignal(ResourcesView.this, new CtfTmfTimestamp(time))); - } - }); - - final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ - @Override - public void run() { - if (TmfExperiment.getCurrentExperiment() != null) { - selectExperiment(TmfExperiment.getCurrentExperiment()); - } - } - }; - thread.start(); - - // View Action Handling - makeActions(); - contributeToActionBars(); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#setFocus() - */ - @Override - public void setFocus() { - fTimeGraphViewer.setFocus(); - } - - // ------------------------------------------------------------------------ - // Signal handlers - // ------------------------------------------------------------------------ - - /** - * Handler for the ExperimentSelected signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void experimentSelected(final TmfExperimentSelectedSignal signal) { - if (signal.getExperiment().equals(fSelectedExperiment)) { - return; - } - - final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ - @Override - public void run() { - selectExperiment(signal.getExperiment()); - } - }; - thread.start(); - } - - /** - * Handler for the TimeSynch signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void synchToTime(final TmfTimeSynchSignal signal) { - if (signal.getSource() == this || fSelectedExperiment == null) { - return; - } - final long time = signal.getCurrentTime().normalize(0, -9).getValue(); - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphViewer.getControl().isDisposed()) { - return; - } - fTimeGraphViewer.setSelectedTime(time, true); - startZoomThread(fTimeGraphViewer.getTime0(), fTimeGraphViewer.getTime1()); - } - }); - } - - /** - * Handler for the RangeSynch signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void synchToRange(final TmfRangeSynchSignal signal) { - if (signal.getSource() == this || fSelectedExperiment == null) { - return; - } - final long startTime = signal.getCurrentRange().getStartTime().normalize(0, -9).getValue(); - final long endTime = signal.getCurrentRange().getEndTime().normalize(0, -9).getValue(); - final long time = signal.getCurrentTime().normalize(0, -9).getValue(); - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphViewer.getControl().isDisposed()) { - return; - } - fTimeGraphViewer.setStartFinishTime(startTime, endTime); - fTimeGraphViewer.setSelectedTime(time, false); - startZoomThread(startTime, endTime); - } - }); - } - - /** - * Handler for the StatesystemBuildCompleted signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void stateSystemBuildCompleted (final TmfStateSystemBuildCompleted signal) { - final TmfExperiment selectedExperiment = fSelectedExperiment; - if (selectedExperiment == null || selectedExperiment.getTraces() == null) { - return; - } - for (ITmfTrace trace : selectedExperiment.getTraces()) { - if (trace == signal.getTrace() && trace instanceof CtfKernelTrace) { - final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ - @Override - public void run() { - // rebuild the model - selectExperiment(selectedExperiment); - } - }; - thread.start(); - } - } - } - - // ------------------------------------------------------------------------ - // Internal - // ------------------------------------------------------------------------ - - @SuppressWarnings("unchecked") - private void selectExperiment(TmfExperiment experiment) { - fStartTime = Long.MAX_VALUE; - fEndTime = Long.MIN_VALUE; - fSelectedExperiment = (TmfExperiment) experiment; - ArrayList entryList = new ArrayList(); - for (ITmfTrace trace : experiment.getTraces()) { - if (trace instanceof CtfKernelTrace) { - CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; - IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); - long startTime = ssq.getStartTime(); - long endTime = ssq.getCurrentEndTime() + 1; - TraceEntry groupEntry = new TraceEntry(ctfKernelTrace, trace.getName(), startTime, endTime); - entryList.add(groupEntry); - fStartTime = Math.min(fStartTime, startTime); - fEndTime = Math.max(fEndTime, endTime); - List cpuQuarks = ssq.getQuarks(Attributes.CPUS, "*"); //$NON-NLS-1$ - ResourcesEntry[] cpuEntries = new ResourcesEntry[cpuQuarks.size()]; - for (int i = 0; i < cpuQuarks.size(); i++) { - int cpuQuark = cpuQuarks.get(i); - int cpu = Integer.parseInt(ssq.getAttributeName(cpuQuark)); - ResourcesEntry entry = new ResourcesEntry(cpuQuark, ctfKernelTrace, Type.CPU, cpu); - groupEntry.addChild(entry); - cpuEntries[i] = entry; - } - List irqQuarks = ssq.getQuarks(Attributes.RESOURCES, Attributes.IRQS, "*"); //$NON-NLS-1$ - ResourcesEntry[] irqEntries = new ResourcesEntry[irqQuarks.size()]; - for (int i = 0; i < irqQuarks.size(); i++) { - int irqQuark = irqQuarks.get(i); - int irq = Integer.parseInt(ssq.getAttributeName(irqQuark)); - ResourcesEntry entry = new ResourcesEntry(irqQuark, ctfKernelTrace, Type.IRQ, irq); - groupEntry.addChild(entry); - irqEntries[i] = entry; - } - List softIrqQuarks = ssq.getQuarks(Attributes.RESOURCES, Attributes.SOFT_IRQS, "*"); //$NON-NLS-1$ - ResourcesEntry[] softIrqEntries = new ResourcesEntry[softIrqQuarks.size()]; - for (int i = 0; i < softIrqQuarks.size(); i++) { - int softIrqQuark = softIrqQuarks.get(i); - int softIrq = Integer.parseInt(ssq.getAttributeName(softIrqQuark)); - ResourcesEntry entry = new ResourcesEntry(softIrqQuark, ctfKernelTrace, Type.SOFT_IRQ, softIrq); - groupEntry.addChild(entry); - softIrqEntries[i] = entry; - } - } - } - synchronized (fEntryListSyncObj) { - fEntryList = (ArrayList) entryList.clone(); - } - refresh(INITIAL_WINDOW_OFFSET); - for (TraceEntry traceEntry : entryList) { - CtfKernelTrace ctfKernelTrace = traceEntry.getTrace(); - IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); - long startTime = ssq.getStartTime(); - long endTime = ssq.getCurrentEndTime() + 1; - long resolution = (endTime - startTime) / fDisplayWidth; - for (ResourcesEntry entry : traceEntry.getChildren()) { - List eventList = getEventList(entry, startTime, endTime, resolution, false, new NullProgressMonitor()); - entry.setEventList(eventList); - redraw(); - } - } - } - - private static List getEventList(ResourcesEntry entry, - long startTime, long endTime, long resolution, boolean includeNull, - IProgressMonitor monitor) { - IStateSystemQuerier2 ssq = (IStateSystemQuerier2) entry.getTrace().getStateSystem(); - startTime = Math.max(startTime, ssq.getStartTime()); - endTime = Math.min(endTime, ssq.getCurrentEndTime() + 1); - if (endTime <= startTime) { - return null; - } - List eventList = null; - int quark = entry.getQuark(); - try { - if (entry.getType().equals(Type.CPU)) { - int statusQuark = ssq.getQuarkRelative(quark, Attributes.STATUS); - List statusIntervals = ssq.queryHistoryRange(statusQuark, startTime, endTime - 1, resolution, monitor); - eventList = new ArrayList(statusIntervals.size()); - long lastEndTime = -1; - for (ITmfStateInterval statusInterval : statusIntervals) { - if (monitor.isCanceled()) { - return null; - } - int status = statusInterval.getStateValue().unboxInt(); - long time = statusInterval.getStartTime(); - long duration = statusInterval.getEndTime() - time + 1; - if (!statusInterval.getStateValue().isNull()) { - if (lastEndTime != time && lastEndTime != -1) { - eventList.add(new TimeEvent(entry, lastEndTime, time - lastEndTime)); - } - eventList.add(new ResourcesEvent(entry, time, duration, status)); - lastEndTime = time + duration; - } else { - if (includeNull) { - eventList.add(new ResourcesEvent(entry, time, duration)); - } - } - } - } else if (entry.getType().equals(Type.IRQ)) { - List irqIntervals = ssq.queryHistoryRange(quark, startTime, endTime - 1, resolution, monitor); - eventList = new ArrayList(irqIntervals.size()); - long lastEndTime = -1; - boolean lastIsNull = true; - for (ITmfStateInterval irqInterval : irqIntervals) { - if (monitor.isCanceled()) { - return null; - } - long time = irqInterval.getStartTime(); - long duration = irqInterval.getEndTime() - time + 1; - if (!irqInterval.getStateValue().isNull()) { - int cpu = irqInterval.getStateValue().unboxInt(); - eventList.add(new ResourcesEvent(entry, time, duration, cpu)); - lastIsNull = false; - } else { - if (lastEndTime != time && lastEndTime != -1 && lastIsNull) { - eventList.add(new ResourcesEvent(entry, lastEndTime, time - lastEndTime, -1)); - } - if (includeNull) { - eventList.add(new ResourcesEvent(entry, time, duration)); - } - lastIsNull = true; - } - lastEndTime = time + duration; - } - } else if (entry.getType().equals(Type.SOFT_IRQ)) { - List softIrqIntervals = ssq.queryHistoryRange(quark, startTime, endTime - 1, resolution, monitor); - eventList = new ArrayList(softIrqIntervals.size()); - long lastEndTime = -1; - boolean lastIsNull = true; - for (ITmfStateInterval softIrqInterval : softIrqIntervals) { - if (monitor.isCanceled()) { - return null; - } - long time = softIrqInterval.getStartTime(); - long duration = softIrqInterval.getEndTime() - time + 1; - if (!softIrqInterval.getStateValue().isNull()) { - int cpu = softIrqInterval.getStateValue().unboxInt(); - eventList.add(new ResourcesEvent(entry, time, duration, cpu)); - } else { - if (lastEndTime != time && lastEndTime != -1 && lastIsNull) { - eventList.add(new ResourcesEvent(entry, lastEndTime, time - lastEndTime, -1)); - } - if (includeNull) { - eventList.add(new ResourcesEvent(entry, time, duration)); - } - lastIsNull = true; - } - lastEndTime = time + duration; - } - } - } catch (AttributeNotFoundException e) { - e.printStackTrace(); - } catch (TimeRangeException e) { - e.printStackTrace(); - } catch (StateValueTypeException e) { - e.printStackTrace(); - } - return eventList; - } - - private void refresh(final long windowRange) { - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphViewer.getControl().isDisposed()) { - return; - } - ITimeGraphEntry[] entries = null; - synchronized (fEntryListSyncObj) { - entries = fEntryList.toArray(new ITimeGraphEntry[0]); - } - Arrays.sort(entries, new TraceEntryComparator()); - fTimeGraphViewer.setInput(entries); - fTimeGraphViewer.setTimeBounds(fStartTime, fEndTime); - - long endTime = fStartTime + windowRange; - - if (fEndTime < endTime) { - endTime = fEndTime; - } - fTimeGraphViewer.setStartFinishTime(fStartTime, endTime); - - startZoomThread(fStartTime, endTime); - } - }); - } - - - private void redraw() { - synchronized (fSyncObj) { - if (fRedrawState == State.IDLE) { - fRedrawState = State.BUSY; - } else { - fRedrawState = State.PENDING; - return; - } - } - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fTimeGraphViewer.getControl().isDisposed()) { - return; - } - fTimeGraphViewer.getControl().redraw(); - fTimeGraphViewer.getControl().update(); - synchronized (fSyncObj) { - if (fRedrawState == State.PENDING) { - fRedrawState = State.IDLE; - redraw(); - } else { - fRedrawState = State.IDLE; - } - } - } - }); - } - - private void startZoomThread(long startTime, long endTime) { - if (fZoomThread != null) { - fZoomThread.cancel(); - } - fZoomThread = new ZoomThread(startTime, endTime); - fZoomThread.start(); - } - - private void makeActions() { - fPreviousResourceAction = fTimeGraphViewer.getPreviousItemAction(); - fPreviousResourceAction.setText(Messages.ResourcesView_previousResourceActionNameText); - fPreviousResourceAction.setToolTipText(Messages.ResourcesView_previousResourceActionToolTipText); - fNextResourceAction = fTimeGraphViewer.getNextItemAction(); - fNextResourceAction.setText(Messages.ResourcesView_nextResourceActionNameText); - fNextResourceAction.setToolTipText(Messages.ResourcesView_previousResourceActionToolTipText); - } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalToolBar(bars.getToolBarManager()); - } - - private void fillLocalToolBar(IToolBarManager manager) { - manager.add(fTimeGraphViewer.getShowLegendAction()); - manager.add(new Separator()); - manager.add(fTimeGraphViewer.getResetScaleAction()); - manager.add(fTimeGraphViewer.getPreviousEventAction()); - manager.add(fTimeGraphViewer.getNextEventAction()); - manager.add(fPreviousResourceAction); - manager.add(fNextResourceAction); - manager.add(fTimeGraphViewer.getZoomInAction()); - manager.add(fTimeGraphViewer.getZoomOutAction()); - manager.add(new Separator()); - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.linuxtools.internal.lttng2.kernel.core.Attributes; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.Messages; +import org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesEntry.Type; +import org.eclipse.linuxtools.lttng2.kernel.core.trace.CtfKernelTrace; +import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTimestamp; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException; +import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException; +import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException; +import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval; +import org.eclipse.linuxtools.tmf.core.signal.TmfExperimentSelectedSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfRangeSynchSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; +import org.eclipse.linuxtools.tmf.core.signal.TmfStateSystemBuildCompleted; +import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier; +import org.eclipse.linuxtools.tmf.core.statesystem.IStateSystemQuerier2; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; +import org.eclipse.linuxtools.tmf.ui.views.TmfView; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphViewer; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.TimeEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IActionBars; + +/** + * Main implementation for the LTTng 2.0 kernel Resource view + * + * @author Patrick Tasse + */ +public class ResourcesView extends TmfView { + + // ------------------------------------------------------------------------ + // Constants + // ------------------------------------------------------------------------ + + /** View ID. */ + public static final String ID = "org.eclipse.linuxtools.lttng2.kernel.ui.views.resources"; //$NON-NLS-1$ + + /** Initial time range */ + private static final long INITIAL_WINDOW_OFFSET = (1L * 100 * 1000 * 1000); // .1sec + + /** + * Redraw state enum + */ + private enum State { IDLE, BUSY, PENDING } + + // ------------------------------------------------------------------------ + // Fields + // ------------------------------------------------------------------------ + + // The time graph viewer + TimeGraphViewer fTimeGraphViewer; + + // The selected experiment + private TmfExperiment fSelectedExperiment; + + // The time graph entry list + private ArrayList fEntryList; + + // The time graph entry list synchronization object + final private Object fEntryListSyncObj = new Object(); + + // The start time + private long fStartTime; + + // The end time + private long fEndTime; + + // The display width + private final int fDisplayWidth; + + // The next resource action + private Action fNextResourceAction; + + // The previous resource action + private Action fPreviousResourceAction; + + // The zoom thread + private ZoomThread fZoomThread; + + // The redraw state used to prevent unnecessary queuing of display runnables + private State fRedrawState = State.IDLE; + + // The redraw synchronization object + final private Object fSyncObj = new Object(); + + // ------------------------------------------------------------------------ + // Classes + // ------------------------------------------------------------------------ + + private class TraceEntry implements ITimeGraphEntry { + // The Trace + private final CtfKernelTrace fTrace; + // The start time + private final long fTraceStartTime; + // The end time + private final long fTraceEndTime; + // The children of the entry + private final ArrayList fChildren; + // The name of entry + private final String fName; + + public TraceEntry(CtfKernelTrace trace, String name, long startTime, long endTime) { + fTrace = trace; + fChildren = new ArrayList(); + fName = name; + fTraceStartTime = startTime; + fTraceEndTime = endTime; + } + + @Override + public ITimeGraphEntry getParent() { + return null; + } + + @Override + public boolean hasChildren() { + return fChildren != null && fChildren.size() > 0; + } + + @Override + public ResourcesEntry[] getChildren() { + return fChildren.toArray(new ResourcesEntry[0]); + } + + @Override + public String getName() { + return fName; + } + + @Override + public long getStartTime() { + return fTraceStartTime; + } + + @Override + public long getEndTime() { + return fTraceEndTime; + } + + @Override + public boolean hasTimeEvents() { + return false; + } + + @Override + public Iterator getTimeEventsIterator() { + return null; + } + + @Override + public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration) { + return null; + } + + public CtfKernelTrace getTrace() { + return fTrace; + } + + public void addChild(ResourcesEntry entry) { + int index; + for (index = 0; index < fChildren.size(); index++) { + ResourcesEntry other = fChildren.get(index); + if (entry.getType().compareTo(other.getType()) < 0) { + break; + } else if (entry.getType().equals(other.getType())) { + if (entry.getId() < other.getId()) { + break; + } + } + } + entry.setParent(this); + fChildren.add(index, entry); + } + } + + private static class TraceEntryComparator implements Comparator { + @Override + public int compare(ITimeGraphEntry o1, ITimeGraphEntry o2) { + int result = o1.getStartTime() < o2.getStartTime() ? -1 : o1.getStartTime() > o2.getStartTime() ? 1 : 0; + if (result == 0) { + result = o1.getName().compareTo(o2.getName()); + } + return result; + } + } + + private class ZoomThread extends Thread { + private final long fZoomStartTime; + private final long fZoomEndTime; + private final IProgressMonitor fMonitor; + + public ZoomThread(long startTime, long endTime) { + super("ResourcesView zoom"); //$NON-NLS-1$ + fZoomStartTime = startTime; + fZoomEndTime = endTime; + fMonitor = new NullProgressMonitor(); + } + + @Override + public void run() { + ArrayList entryList = null; + synchronized (fEntryListSyncObj) { + entryList = fEntryList; + } + if (entryList == null) { + return; + } + long resolution = Math.max(1, (fZoomEndTime - fZoomStartTime) / fDisplayWidth); + for (TraceEntry traceEntry : entryList) { + for (ITimeGraphEntry child : traceEntry.getChildren()) { + if (fMonitor.isCanceled()) { + break; + } + ResourcesEntry entry = (ResourcesEntry) child; + if (fZoomStartTime <= fStartTime && fZoomEndTime >= fEndTime) { + entry.setZoomedEventList(null); + } else { + List zoomedEventList = getEventList(entry, fZoomStartTime, fZoomEndTime, resolution, true, fMonitor); + if (zoomedEventList != null) { + entry.setZoomedEventList(zoomedEventList); + } + } + redraw(); + } + } + } + + public void cancel() { + fMonitor.setCanceled(true); + } + } + + // ------------------------------------------------------------------------ + // Constructors + // ------------------------------------------------------------------------ + + /** + * Default constructor + */ + public ResourcesView() { + super(ID); + fDisplayWidth = Display.getDefault().getBounds().width; + } + + // ------------------------------------------------------------------------ + // ViewPart + // ------------------------------------------------------------------------ + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.views.TmfView#createPartControl(org.eclipse.swt.widgets.Composite) + */ + @Override + public void createPartControl(Composite parent) { + fTimeGraphViewer = new TimeGraphViewer(parent, SWT.NONE); + + fTimeGraphViewer.setTimeGraphProvider(new ResourcesPresentationProvider()); + + fTimeGraphViewer.setTimeCalendarFormat(true); + + fTimeGraphViewer.addRangeListener(new ITimeGraphRangeListener() { + @Override + public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { + long startTime = event.getStartTime(); + long endTime = event.getEndTime(); + TmfTimeRange range = new TmfTimeRange(new CtfTmfTimestamp(startTime), new CtfTmfTimestamp(endTime)); + TmfTimestamp time = new CtfTmfTimestamp(fTimeGraphViewer.getSelectedTime()); + broadcast(new TmfRangeSynchSignal(ResourcesView.this, range, time)); + startZoomThread(startTime, endTime); + } + }); + + fTimeGraphViewer.addTimeListener(new ITimeGraphTimeListener() { + @Override + public void timeSelected(TimeGraphTimeEvent event) { + long time = event.getTime(); + broadcast(new TmfTimeSynchSignal(ResourcesView.this, new CtfTmfTimestamp(time))); + } + }); + + final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ + @Override + public void run() { + if (TmfExperiment.getCurrentExperiment() != null) { + selectExperiment(TmfExperiment.getCurrentExperiment()); + } + } + }; + thread.start(); + + // View Action Handling + makeActions(); + contributeToActionBars(); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#setFocus() + */ + @Override + public void setFocus() { + fTimeGraphViewer.setFocus(); + } + + // ------------------------------------------------------------------------ + // Signal handlers + // ------------------------------------------------------------------------ + + /** + * Handler for the ExperimentSelected signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void experimentSelected(final TmfExperimentSelectedSignal signal) { + if (signal.getExperiment().equals(fSelectedExperiment)) { + return; + } + + final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ + @Override + public void run() { + selectExperiment(signal.getExperiment()); + } + }; + thread.start(); + } + + /** + * Handler for the TimeSynch signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void synchToTime(final TmfTimeSynchSignal signal) { + if (signal.getSource() == this || fSelectedExperiment == null) { + return; + } + final long time = signal.getCurrentTime().normalize(0, -9).getValue(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphViewer.getControl().isDisposed()) { + return; + } + fTimeGraphViewer.setSelectedTime(time, true); + startZoomThread(fTimeGraphViewer.getTime0(), fTimeGraphViewer.getTime1()); + } + }); + } + + /** + * Handler for the RangeSynch signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void synchToRange(final TmfRangeSynchSignal signal) { + if (signal.getSource() == this || fSelectedExperiment == null) { + return; + } + final long startTime = signal.getCurrentRange().getStartTime().normalize(0, -9).getValue(); + final long endTime = signal.getCurrentRange().getEndTime().normalize(0, -9).getValue(); + final long time = signal.getCurrentTime().normalize(0, -9).getValue(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphViewer.getControl().isDisposed()) { + return; + } + fTimeGraphViewer.setStartFinishTime(startTime, endTime); + fTimeGraphViewer.setSelectedTime(time, false); + startZoomThread(startTime, endTime); + } + }); + } + + /** + * Handler for the StatesystemBuildCompleted signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void stateSystemBuildCompleted (final TmfStateSystemBuildCompleted signal) { + final TmfExperiment selectedExperiment = fSelectedExperiment; + if (selectedExperiment == null || selectedExperiment.getTraces() == null) { + return; + } + for (ITmfTrace trace : selectedExperiment.getTraces()) { + if (trace == signal.getTrace() && trace instanceof CtfKernelTrace) { + final Thread thread = new Thread("ResourcesView build") { //$NON-NLS-1$ + @Override + public void run() { + // rebuild the model + selectExperiment(selectedExperiment); + } + }; + thread.start(); + } + } + } + + // ------------------------------------------------------------------------ + // Internal + // ------------------------------------------------------------------------ + + @SuppressWarnings("unchecked") + private void selectExperiment(TmfExperiment experiment) { + fStartTime = Long.MAX_VALUE; + fEndTime = Long.MIN_VALUE; + fSelectedExperiment = (TmfExperiment) experiment; + ArrayList entryList = new ArrayList(); + for (ITmfTrace trace : experiment.getTraces()) { + if (trace instanceof CtfKernelTrace) { + CtfKernelTrace ctfKernelTrace = (CtfKernelTrace) trace; + IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); + long startTime = ssq.getStartTime(); + long endTime = ssq.getCurrentEndTime() + 1; + TraceEntry groupEntry = new TraceEntry(ctfKernelTrace, trace.getName(), startTime, endTime); + entryList.add(groupEntry); + fStartTime = Math.min(fStartTime, startTime); + fEndTime = Math.max(fEndTime, endTime); + List cpuQuarks = ssq.getQuarks(Attributes.CPUS, "*"); //$NON-NLS-1$ + ResourcesEntry[] cpuEntries = new ResourcesEntry[cpuQuarks.size()]; + for (int i = 0; i < cpuQuarks.size(); i++) { + int cpuQuark = cpuQuarks.get(i); + int cpu = Integer.parseInt(ssq.getAttributeName(cpuQuark)); + ResourcesEntry entry = new ResourcesEntry(cpuQuark, ctfKernelTrace, Type.CPU, cpu); + groupEntry.addChild(entry); + cpuEntries[i] = entry; + } + List irqQuarks = ssq.getQuarks(Attributes.RESOURCES, Attributes.IRQS, "*"); //$NON-NLS-1$ + ResourcesEntry[] irqEntries = new ResourcesEntry[irqQuarks.size()]; + for (int i = 0; i < irqQuarks.size(); i++) { + int irqQuark = irqQuarks.get(i); + int irq = Integer.parseInt(ssq.getAttributeName(irqQuark)); + ResourcesEntry entry = new ResourcesEntry(irqQuark, ctfKernelTrace, Type.IRQ, irq); + groupEntry.addChild(entry); + irqEntries[i] = entry; + } + List softIrqQuarks = ssq.getQuarks(Attributes.RESOURCES, Attributes.SOFT_IRQS, "*"); //$NON-NLS-1$ + ResourcesEntry[] softIrqEntries = new ResourcesEntry[softIrqQuarks.size()]; + for (int i = 0; i < softIrqQuarks.size(); i++) { + int softIrqQuark = softIrqQuarks.get(i); + int softIrq = Integer.parseInt(ssq.getAttributeName(softIrqQuark)); + ResourcesEntry entry = new ResourcesEntry(softIrqQuark, ctfKernelTrace, Type.SOFT_IRQ, softIrq); + groupEntry.addChild(entry); + softIrqEntries[i] = entry; + } + } + } + synchronized (fEntryListSyncObj) { + fEntryList = (ArrayList) entryList.clone(); + } + refresh(INITIAL_WINDOW_OFFSET); + for (TraceEntry traceEntry : entryList) { + CtfKernelTrace ctfKernelTrace = traceEntry.getTrace(); + IStateSystemQuerier ssq = ctfKernelTrace.getStateSystem(); + long startTime = ssq.getStartTime(); + long endTime = ssq.getCurrentEndTime() + 1; + long resolution = (endTime - startTime) / fDisplayWidth; + for (ResourcesEntry entry : traceEntry.getChildren()) { + List eventList = getEventList(entry, startTime, endTime, resolution, false, new NullProgressMonitor()); + entry.setEventList(eventList); + redraw(); + } + } + } + + private static List getEventList(ResourcesEntry entry, + long startTime, long endTime, long resolution, boolean includeNull, + IProgressMonitor monitor) { + IStateSystemQuerier2 ssq = (IStateSystemQuerier2) entry.getTrace().getStateSystem(); + startTime = Math.max(startTime, ssq.getStartTime()); + endTime = Math.min(endTime, ssq.getCurrentEndTime() + 1); + if (endTime <= startTime) { + return null; + } + List eventList = null; + int quark = entry.getQuark(); + try { + if (entry.getType().equals(Type.CPU)) { + int statusQuark = ssq.getQuarkRelative(quark, Attributes.STATUS); + List statusIntervals = ssq.queryHistoryRange(statusQuark, startTime, endTime - 1, resolution, monitor); + eventList = new ArrayList(statusIntervals.size()); + long lastEndTime = -1; + for (ITmfStateInterval statusInterval : statusIntervals) { + if (monitor.isCanceled()) { + return null; + } + int status = statusInterval.getStateValue().unboxInt(); + long time = statusInterval.getStartTime(); + long duration = statusInterval.getEndTime() - time + 1; + if (!statusInterval.getStateValue().isNull()) { + if (lastEndTime != time && lastEndTime != -1) { + eventList.add(new TimeEvent(entry, lastEndTime, time - lastEndTime)); + } + eventList.add(new ResourcesEvent(entry, time, duration, status)); + lastEndTime = time + duration; + } else { + if (includeNull) { + eventList.add(new ResourcesEvent(entry, time, duration)); + } + } + } + } else if (entry.getType().equals(Type.IRQ)) { + List irqIntervals = ssq.queryHistoryRange(quark, startTime, endTime - 1, resolution, monitor); + eventList = new ArrayList(irqIntervals.size()); + long lastEndTime = -1; + boolean lastIsNull = true; + for (ITmfStateInterval irqInterval : irqIntervals) { + if (monitor.isCanceled()) { + return null; + } + long time = irqInterval.getStartTime(); + long duration = irqInterval.getEndTime() - time + 1; + if (!irqInterval.getStateValue().isNull()) { + int cpu = irqInterval.getStateValue().unboxInt(); + eventList.add(new ResourcesEvent(entry, time, duration, cpu)); + lastIsNull = false; + } else { + if (lastEndTime != time && lastEndTime != -1 && lastIsNull) { + eventList.add(new ResourcesEvent(entry, lastEndTime, time - lastEndTime, -1)); + } + if (includeNull) { + eventList.add(new ResourcesEvent(entry, time, duration)); + } + lastIsNull = true; + } + lastEndTime = time + duration; + } + } else if (entry.getType().equals(Type.SOFT_IRQ)) { + List softIrqIntervals = ssq.queryHistoryRange(quark, startTime, endTime - 1, resolution, monitor); + eventList = new ArrayList(softIrqIntervals.size()); + long lastEndTime = -1; + boolean lastIsNull = true; + for (ITmfStateInterval softIrqInterval : softIrqIntervals) { + if (monitor.isCanceled()) { + return null; + } + long time = softIrqInterval.getStartTime(); + long duration = softIrqInterval.getEndTime() - time + 1; + if (!softIrqInterval.getStateValue().isNull()) { + int cpu = softIrqInterval.getStateValue().unboxInt(); + eventList.add(new ResourcesEvent(entry, time, duration, cpu)); + } else { + if (lastEndTime != time && lastEndTime != -1 && lastIsNull) { + eventList.add(new ResourcesEvent(entry, lastEndTime, time - lastEndTime, -1)); + } + if (includeNull) { + eventList.add(new ResourcesEvent(entry, time, duration)); + } + lastIsNull = true; + } + lastEndTime = time + duration; + } + } + } catch (AttributeNotFoundException e) { + e.printStackTrace(); + } catch (TimeRangeException e) { + e.printStackTrace(); + } catch (StateValueTypeException e) { + e.printStackTrace(); + } + return eventList; + } + + private void refresh(final long windowRange) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphViewer.getControl().isDisposed()) { + return; + } + ITimeGraphEntry[] entries = null; + synchronized (fEntryListSyncObj) { + entries = fEntryList.toArray(new ITimeGraphEntry[0]); + } + Arrays.sort(entries, new TraceEntryComparator()); + fTimeGraphViewer.setInput(entries); + fTimeGraphViewer.setTimeBounds(fStartTime, fEndTime); + + long endTime = fStartTime + windowRange; + + if (fEndTime < endTime) { + endTime = fEndTime; + } + fTimeGraphViewer.setStartFinishTime(fStartTime, endTime); + + startZoomThread(fStartTime, endTime); + } + }); + } + + + private void redraw() { + synchronized (fSyncObj) { + if (fRedrawState == State.IDLE) { + fRedrawState = State.BUSY; + } else { + fRedrawState = State.PENDING; + return; + } + } + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fTimeGraphViewer.getControl().isDisposed()) { + return; + } + fTimeGraphViewer.getControl().redraw(); + fTimeGraphViewer.getControl().update(); + synchronized (fSyncObj) { + if (fRedrawState == State.PENDING) { + fRedrawState = State.IDLE; + redraw(); + } else { + fRedrawState = State.IDLE; + } + } + } + }); + } + + private void startZoomThread(long startTime, long endTime) { + if (fZoomThread != null) { + fZoomThread.cancel(); + } + fZoomThread = new ZoomThread(startTime, endTime); + fZoomThread.start(); + } + + private void makeActions() { + fPreviousResourceAction = fTimeGraphViewer.getPreviousItemAction(); + fPreviousResourceAction.setText(Messages.ResourcesView_previousResourceActionNameText); + fPreviousResourceAction.setToolTipText(Messages.ResourcesView_previousResourceActionToolTipText); + fNextResourceAction = fTimeGraphViewer.getNextItemAction(); + fNextResourceAction.setText(Messages.ResourcesView_nextResourceActionNameText); + fNextResourceAction.setToolTipText(Messages.ResourcesView_previousResourceActionToolTipText); + } + + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + fillLocalToolBar(bars.getToolBarManager()); + } + + private void fillLocalToolBar(IToolBarManager manager) { + manager.add(fTimeGraphViewer.getShowLegendAction()); + manager.add(new Separator()); + manager.add(fTimeGraphViewer.getResetScaleAction()); + manager.add(fTimeGraphViewer.getPreviousEventAction()); + manager.add(fTimeGraphViewer.getNextEventAction()); + manager.add(fPreviousResourceAction); + manager.add(fNextResourceAction); + manager.add(fTimeGraphViewer.getZoomInAction()); + manager.add(fTimeGraphViewer.getZoomOutAction()); + manager.add(new Separator()); + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/Tracer.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/Tracer.java index 3dad637b1b..d024e1d479 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/Tracer.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/Tracer.java @@ -1,185 +1,185 @@ -package org.eclipse.linuxtools.internal.tmf.core; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStreamWriter; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; -import org.eclipse.linuxtools.tmf.core.component.ITmfDataProvider; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; - -@SuppressWarnings({"nls", "javadoc"}) -public class Tracer { - - private static String pluginID = Activator.PLUGIN_ID; - - static Boolean ERROR = Boolean.FALSE; - static Boolean WARNING = Boolean.FALSE; - static Boolean INFO = Boolean.FALSE; - - static Boolean COMPONENT = Boolean.FALSE; - static Boolean REQUEST = Boolean.FALSE; - static Boolean SIGNAL = Boolean.FALSE; - static Boolean EVENT = Boolean.FALSE; - - private static String LOGNAME = "trace.log"; - private static BufferedWriter fTraceLog = new BufferedWriter(new OutputStreamWriter(System.out)); - - private static BufferedWriter openLogFile(String filename) { - BufferedWriter outfile = null; - try { - outfile = new BufferedWriter(new FileWriter(filename)); - } catch (IOException e) { - Activator.getDefault().logError("Error opening log file " + filename, e); - } - return outfile; - } - - public static void init() { - - String traceKey; - boolean isTracing = false; - - traceKey = Platform.getDebugOption(pluginID + "/error"); - if (traceKey != null) { - ERROR = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= ERROR; - } - - traceKey = Platform.getDebugOption(pluginID + "/warning"); - if (traceKey != null) { - WARNING = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= WARNING; - } - - traceKey = Platform.getDebugOption(pluginID + "/info"); - if (traceKey != null) { - INFO = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= INFO; - } - - traceKey = Platform.getDebugOption(pluginID + "/component"); - if (traceKey != null) { - COMPONENT = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= COMPONENT; - } - - traceKey = Platform.getDebugOption(pluginID + "/request"); - if (traceKey != null) { - REQUEST = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= REQUEST; - } - - traceKey = Platform.getDebugOption(pluginID + "/signal"); - if (traceKey != null) { - SIGNAL = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= SIGNAL; - } - - traceKey = Platform.getDebugOption(pluginID + "/event"); - if (traceKey != null) { - EVENT = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= EVENT; - } - - // Create trace log file if needed - if (isTracing) { - fTraceLog = openLogFile(LOGNAME); - } - } - - public static void stop() { - if (fTraceLog == null) { - return; - } - - try { - fTraceLog.close(); - fTraceLog = null; - } catch (IOException e) { - Activator.getDefault().logError("Error closing log file", e); - } - } - - // Predicates - public static boolean isErrorTraced() { - return ERROR; - } - - public static boolean isComponentTraced() { - return COMPONENT; - } - - public static boolean isRequestTraced() { - return REQUEST; - } - - public static boolean isSignalTraced() { - return SIGNAL; - } - - public static boolean isEventTraced() { - return EVENT; - } - - // Tracers - public static synchronized void trace(String msg) { - long currentTime = System.currentTimeMillis(); - StringBuilder message = new StringBuilder("["); - message.append(currentTime / 1000); - message.append("."); - message.append(String.format("%1$03d", currentTime % 1000)); - message.append("] "); - - message.append("[Th="); - message.append(String.format("%1$03d", Thread.currentThread().getId())); - message.append("] "); - - message.append(msg); - - if (fTraceLog != null) { - try { - fTraceLog.write(message.toString()); - fTraceLog.newLine(); - fTraceLog.flush(); - } catch (IOException e) { - Activator.getDefault().logError("Error writing to log file", e); - } - } - } - - public static void traceComponent(ITmfComponent component, String msg) { - String message = ("[CMP] Cmp=" + component.getName() + " " + msg); - trace(message); - } - - public static void traceRequest(ITmfDataRequest request, String msg) { - String message = ("[REQ] Req=" + request.getRequestId() + " " + msg); - trace(message); - } - - public static void traceSignal(TmfSignal signal, String msg) { - String message = ("[SIG] Sig=" + signal.getClass().getSimpleName() + " Target=" + msg); - trace(message); - } - - public static void traceEvent(ITmfDataProvider provider, ITmfDataRequest request, ITmfEvent event) { - String message = ("[EVT] Provider=" + provider.toString() + ", Req=" + request.getRequestId() + ", Event=" + event.getTimestamp()); - trace(message); - } - - public static void traceError(String msg) { - String message = ("[ERR] Err=" + msg); - trace(message); - } - - public static void traceInfo(String msg) { - String message = ("[INF] " + msg); - trace(message); - } - -} +package org.eclipse.linuxtools.internal.tmf.core; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; + +import org.eclipse.core.runtime.Platform; +import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; +import org.eclipse.linuxtools.tmf.core.component.ITmfDataProvider; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; + +@SuppressWarnings({"nls", "javadoc"}) +public class Tracer { + + private static String pluginID = Activator.PLUGIN_ID; + + static Boolean ERROR = Boolean.FALSE; + static Boolean WARNING = Boolean.FALSE; + static Boolean INFO = Boolean.FALSE; + + static Boolean COMPONENT = Boolean.FALSE; + static Boolean REQUEST = Boolean.FALSE; + static Boolean SIGNAL = Boolean.FALSE; + static Boolean EVENT = Boolean.FALSE; + + private static String LOGNAME = "trace.log"; + private static BufferedWriter fTraceLog = new BufferedWriter(new OutputStreamWriter(System.out)); + + private static BufferedWriter openLogFile(String filename) { + BufferedWriter outfile = null; + try { + outfile = new BufferedWriter(new FileWriter(filename)); + } catch (IOException e) { + Activator.getDefault().logError("Error opening log file " + filename, e); + } + return outfile; + } + + public static void init() { + + String traceKey; + boolean isTracing = false; + + traceKey = Platform.getDebugOption(pluginID + "/error"); + if (traceKey != null) { + ERROR = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= ERROR; + } + + traceKey = Platform.getDebugOption(pluginID + "/warning"); + if (traceKey != null) { + WARNING = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= WARNING; + } + + traceKey = Platform.getDebugOption(pluginID + "/info"); + if (traceKey != null) { + INFO = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= INFO; + } + + traceKey = Platform.getDebugOption(pluginID + "/component"); + if (traceKey != null) { + COMPONENT = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= COMPONENT; + } + + traceKey = Platform.getDebugOption(pluginID + "/request"); + if (traceKey != null) { + REQUEST = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= REQUEST; + } + + traceKey = Platform.getDebugOption(pluginID + "/signal"); + if (traceKey != null) { + SIGNAL = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= SIGNAL; + } + + traceKey = Platform.getDebugOption(pluginID + "/event"); + if (traceKey != null) { + EVENT = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= EVENT; + } + + // Create trace log file if needed + if (isTracing) { + fTraceLog = openLogFile(LOGNAME); + } + } + + public static void stop() { + if (fTraceLog == null) { + return; + } + + try { + fTraceLog.close(); + fTraceLog = null; + } catch (IOException e) { + Activator.getDefault().logError("Error closing log file", e); + } + } + + // Predicates + public static boolean isErrorTraced() { + return ERROR; + } + + public static boolean isComponentTraced() { + return COMPONENT; + } + + public static boolean isRequestTraced() { + return REQUEST; + } + + public static boolean isSignalTraced() { + return SIGNAL; + } + + public static boolean isEventTraced() { + return EVENT; + } + + // Tracers + public static synchronized void trace(String msg) { + long currentTime = System.currentTimeMillis(); + StringBuilder message = new StringBuilder("["); + message.append(currentTime / 1000); + message.append("."); + message.append(String.format("%1$03d", currentTime % 1000)); + message.append("] "); + + message.append("[Th="); + message.append(String.format("%1$03d", Thread.currentThread().getId())); + message.append("] "); + + message.append(msg); + + if (fTraceLog != null) { + try { + fTraceLog.write(message.toString()); + fTraceLog.newLine(); + fTraceLog.flush(); + } catch (IOException e) { + Activator.getDefault().logError("Error writing to log file", e); + } + } + } + + public static void traceComponent(ITmfComponent component, String msg) { + String message = ("[CMP] Cmp=" + component.getName() + " " + msg); + trace(message); + } + + public static void traceRequest(ITmfDataRequest request, String msg) { + String message = ("[REQ] Req=" + request.getRequestId() + " " + msg); + trace(message); + } + + public static void traceSignal(TmfSignal signal, String msg) { + String message = ("[SIG] Sig=" + signal.getClass().getSimpleName() + " Target=" + msg); + trace(message); + } + + public static void traceEvent(ITmfDataProvider provider, ITmfDataRequest request, ITmfEvent event) { + String message = ("[EVT] Provider=" + provider.toString() + ", Req=" + request.getRequestId() + ", Event=" + event.getTimestamp()); + trace(message); + } + + public static void traceError(String msg) { + String message = ("[ERR] Err=" + msg); + trace(message); + } + + public static void traceInfo(String msg) { + String message = ("[INF] " + msg); + trace(message); + } + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/ITmfFilter.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/ITmfFilter.java index 00ce5c28f7..dd9f0654c8 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/ITmfFilter.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/ITmfFilter.java @@ -1,33 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * The TMF filter interface. - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITmfFilter { - - /** - * Verify the filter conditions on an event - * - * @param event The event to verify. - * @return True if the event matches the filter conditions. - */ - public boolean matches(ITmfEvent event); - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * The TMF filter interface. + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITmfFilter { + + /** + * Verify the filter conditions on an event + * + * @param event The event to verify. + * @return True if the event matches the filter conditions. + */ + public boolean matches(ITmfEvent event); + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java index d55ee636ef..aa9d347cb8 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java @@ -1,127 +1,127 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Francois Godin (copelnug@gmail.com) - Initial API - * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; - - -/** - *

This is Node Interface in the Filter Tree

- */ -public interface ITmfFilterTreeNode extends ITmfFilter { - - /** - *

Get the parent node of current node

- * - * @return The parent node (null when the node has no parent). - */ - public ITmfFilterTreeNode getParent(); - - /** - *

Get the current node name

- * - * @return The name of the current node. - */ - public String getNodeName(); - - /** - *

Tell if the node has children

- * - * @return True if the node has children. - */ - public boolean hasChildren(); - - /** - *

Return the number of children

- * - * @return The number of children. - */ - public int getChildrenCount(); - - /** - *

Get the array of children

- * - * @return The array (possibly empty) of children nodes. - */ - public ITmfFilterTreeNode[] getChildren(); - - /** - *

Get the node by index

- * - * @param index The index of node to return. - * @return The desired node (null if the node is not exists). - */ - public ITmfFilterTreeNode getChild(int index); - - /** - *

Remove the node from its parent

- * - *

Shifts all nodes after the removed one to prevent having an empty spot. - * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.

- * - * @return The removed node. - */ - public ITmfFilterTreeNode remove(); - - /** - *

Remove the child from the current node

- * - *

Shifts all nodes after the removed one to prevent having an empty spot. - * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.

- * - * @param node the parent node - * - * @return The removed node. - */ - public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node); - - /** - *

Append a node to the current children

- * - * @param node Node to append. - * @return Index of added node (-1 if the node cannot be added). - */ - public int addChild(ITmfFilterTreeNode node); - - /** - *

Replace a child node

- * - * @param index Index of the node to replace. - * @param node Node who will replace. - * @return Node replaced. - */ - public ITmfFilterTreeNode replaceChild(int index, ITmfFilterTreeNode node); - - /** - *

Sets the parent of current node

- * - * @param parent The parent of current node. - */ - public void setParent(ITmfFilterTreeNode parent); - - /** - *

Gets the list of valid children node names that could be added to the node

- * - * @return The list of valid children node names. - */ - public List getValidChildren(); - - /** - * @return a clone of the node - */ - public ITmfFilterTreeNode clone(); - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Francois Godin (copelnug@gmail.com) - Initial API + * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; + + +/** + *

This is Node Interface in the Filter Tree

+ */ +public interface ITmfFilterTreeNode extends ITmfFilter { + + /** + *

Get the parent node of current node

+ * + * @return The parent node (null when the node has no parent). + */ + public ITmfFilterTreeNode getParent(); + + /** + *

Get the current node name

+ * + * @return The name of the current node. + */ + public String getNodeName(); + + /** + *

Tell if the node has children

+ * + * @return True if the node has children. + */ + public boolean hasChildren(); + + /** + *

Return the number of children

+ * + * @return The number of children. + */ + public int getChildrenCount(); + + /** + *

Get the array of children

+ * + * @return The array (possibly empty) of children nodes. + */ + public ITmfFilterTreeNode[] getChildren(); + + /** + *

Get the node by index

+ * + * @param index The index of node to return. + * @return The desired node (null if the node is not exists). + */ + public ITmfFilterTreeNode getChild(int index); + + /** + *

Remove the node from its parent

+ * + *

Shifts all nodes after the removed one to prevent having an empty spot. + * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.

+ * + * @return The removed node. + */ + public ITmfFilterTreeNode remove(); + + /** + *

Remove the child from the current node

+ * + *

Shifts all nodes after the removed one to prevent having an empty spot. + * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.

+ * + * @param node the parent node + * + * @return The removed node. + */ + public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node); + + /** + *

Append a node to the current children

+ * + * @param node Node to append. + * @return Index of added node (-1 if the node cannot be added). + */ + public int addChild(ITmfFilterTreeNode node); + + /** + *

Replace a child node

+ * + * @param index Index of the node to replace. + * @param node Node who will replace. + * @return Node replaced. + */ + public ITmfFilterTreeNode replaceChild(int index, ITmfFilterTreeNode node); + + /** + *

Sets the parent of current node

+ * + * @param parent The parent of current node. + */ + public void setParent(ITmfFilterTreeNode parent); + + /** + *

Gets the list of valid children node names that could be added to the node

+ * + * @return The list of valid children node names. + */ + public List getValidChildren(); + + /** + * @return a clone of the node + */ + public ITmfFilterTreeNode clone(); + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java index 71559a555b..158999f437 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - - -/** - * Filter node for the 'and' operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterAndNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "AND"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - - private boolean fNot = false; - - /** - * @param parent the parent node - */ - public TmfFilterAndNode(ITmfFilterTreeNode parent) { - super(parent); - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - for (ITmfFilterTreeNode node : getChildren()) { - if (! node.matches(event)) { - return false ^ fNot; - } - } - return true ^ fNot; - } - - @Override - public String toString() { - StringBuffer buf = new StringBuffer(); - if (fNot) { - buf.append("not "); //$NON-NLS-1$ - } - if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { - buf.append("( "); //$NON-NLS-1$ - } - for (int i = 0; i < getChildrenCount(); i++) { - ITmfFilterTreeNode node = getChildren()[i]; - buf.append(node.toString()); - if (i < getChildrenCount() - 1) { - buf.append(" and "); //$NON-NLS-1$ - } - } - if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { - buf.append(" )"); //$NON-NLS-1$ - } - return buf.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + + +/** + * Filter node for the 'and' operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterAndNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "AND"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + + private boolean fNot = false; + + /** + * @param parent the parent node + */ + public TmfFilterAndNode(ITmfFilterTreeNode parent) { + super(parent); + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + for (ITmfFilterTreeNode node : getChildren()) { + if (! node.matches(event)) { + return false ^ fNot; + } + } + return true ^ fNot; + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + if (fNot) { + buf.append("not "); //$NON-NLS-1$ + } + if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { + buf.append("( "); //$NON-NLS-1$ + } + for (int i = 0; i < getChildrenCount(); i++) { + ITmfFilterTreeNode node = getChildren()[i]; + buf.append(node.toString()); + if (i < getChildrenCount() - 1) { + buf.append(" and "); //$NON-NLS-1$ + } + } + if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { + buf.append(" )"); //$NON-NLS-1$ + } + return buf.toString(); + } + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java index 9a30f982c9..e7fc83784d 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java @@ -1,222 +1,222 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; - - -/** - * Filter node for the comparison operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterCompareNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "COMPARE"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ - public static final String RESULT_ATTR = "result"; //$NON-NLS-1$ - public static final String TYPE_ATTR = "type"; //$NON-NLS-1$ - public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ - - /** - * Supported comparison types - */ - public static enum Type { - NUM, - ALPHA, - TIMESTAMP - } - - private boolean fNot = false; - private String fField; - private int fResult; - private Type fType = Type.NUM; - private String fValue; - private Number fValueNumber; - private TmfTimestamp fValueTimestamp; - - /** - * @param parent the parent node - */ - public TmfFilterCompareNode(ITmfFilterTreeNode parent) { - super(parent); - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - /** - * @return the field name - */ - public String getField() { - return fField; - } - - /** - * @param field the field name - */ - public void setField(String field) { - this.fField = field; - } - - /** - * @return the compare result - */ - public int getResult() { - return fResult; - } - - /** - * @param result the compare result - */ - public void setResult(int result) { - this.fResult = result; - } - - /** - * @return the comparison type - */ - public Type getType() { - return fType; - } - - /** - * @param type the comparison type - */ - public void setType(Type type) { - this.fType = type; - setValue(fValue); - } - - /** - * @return the comparison value - */ - public String getValue() { - return fValue; - } - - /** - * @param value the comparison value - */ - public void setValue(String value) { - this.fValue = value; - fValueNumber = null; - fValueTimestamp = null; - if (value == null) { - return; - } - if (fType == Type.NUM) { - try { - fValueNumber = NumberFormat.getInstance().parse(value).doubleValue(); - } catch (ParseException e) { - } - } else if (fType == Type.TIMESTAMP) { - try { - fValueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat.getInstance().parse(value.toString()).doubleValue())); - } catch (ParseException e) { - } - } - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - Object value = getFieldValue(event, fField); - if (value == null) { - return false ^ fNot; - } - if (fType == Type.NUM) { - if (fValueNumber != null) { - if (value instanceof Number) { - Double valueDouble = ((Number) value).doubleValue(); - return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) ^ fNot; - } - try { - Double valueDouble = NumberFormat.getInstance().parse(value.toString()) - .doubleValue(); - return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) - ^ fNot; - } catch (ParseException e) { - } - } - } else if (fType == Type.ALPHA) { - String valueString = value.toString(); - int comp = valueString.compareTo(fValue.toString()); - if (comp < -1) { - comp = -1; - } else if (comp > 1) { - comp = 1; - } - return (comp == fResult) ^ fNot; - } else if (fType == Type.TIMESTAMP) { - if (fValueTimestamp != null) { - if (value instanceof TmfTimestamp) { - TmfTimestamp valueTimestamp = (TmfTimestamp) value; - return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot; - } - try { - TmfTimestamp valueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat - .getInstance().parse(value.toString()).doubleValue())); - return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot; - } catch (ParseException e) { - } - } - } - return false ^ fNot; - } - - @Override - public List getValidChildren() { - return new ArrayList(0); - } - - @Override - public String toString() { - String result = (fResult == 0 ? "= " : fResult < 0 ? "< " : "> "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - String open = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "["); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - String close = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - return fField + (fNot ? " not " : " ") + result + open + fValue + close; //$NON-NLS-1$ //$NON-NLS-2$ - } - - @Override - public ITmfFilterTreeNode clone() { - TmfFilterCompareNode clone = (TmfFilterCompareNode) super.clone(); - clone.fField = fField; - clone.setValue(fValue); - return clone; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; + + +/** + * Filter node for the comparison operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterCompareNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "COMPARE"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ + public static final String RESULT_ATTR = "result"; //$NON-NLS-1$ + public static final String TYPE_ATTR = "type"; //$NON-NLS-1$ + public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ + + /** + * Supported comparison types + */ + public static enum Type { + NUM, + ALPHA, + TIMESTAMP + } + + private boolean fNot = false; + private String fField; + private int fResult; + private Type fType = Type.NUM; + private String fValue; + private Number fValueNumber; + private TmfTimestamp fValueTimestamp; + + /** + * @param parent the parent node + */ + public TmfFilterCompareNode(ITmfFilterTreeNode parent) { + super(parent); + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + /** + * @return the field name + */ + public String getField() { + return fField; + } + + /** + * @param field the field name + */ + public void setField(String field) { + this.fField = field; + } + + /** + * @return the compare result + */ + public int getResult() { + return fResult; + } + + /** + * @param result the compare result + */ + public void setResult(int result) { + this.fResult = result; + } + + /** + * @return the comparison type + */ + public Type getType() { + return fType; + } + + /** + * @param type the comparison type + */ + public void setType(Type type) { + this.fType = type; + setValue(fValue); + } + + /** + * @return the comparison value + */ + public String getValue() { + return fValue; + } + + /** + * @param value the comparison value + */ + public void setValue(String value) { + this.fValue = value; + fValueNumber = null; + fValueTimestamp = null; + if (value == null) { + return; + } + if (fType == Type.NUM) { + try { + fValueNumber = NumberFormat.getInstance().parse(value).doubleValue(); + } catch (ParseException e) { + } + } else if (fType == Type.TIMESTAMP) { + try { + fValueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat.getInstance().parse(value.toString()).doubleValue())); + } catch (ParseException e) { + } + } + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + Object value = getFieldValue(event, fField); + if (value == null) { + return false ^ fNot; + } + if (fType == Type.NUM) { + if (fValueNumber != null) { + if (value instanceof Number) { + Double valueDouble = ((Number) value).doubleValue(); + return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) ^ fNot; + } + try { + Double valueDouble = NumberFormat.getInstance().parse(value.toString()) + .doubleValue(); + return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) + ^ fNot; + } catch (ParseException e) { + } + } + } else if (fType == Type.ALPHA) { + String valueString = value.toString(); + int comp = valueString.compareTo(fValue.toString()); + if (comp < -1) { + comp = -1; + } else if (comp > 1) { + comp = 1; + } + return (comp == fResult) ^ fNot; + } else if (fType == Type.TIMESTAMP) { + if (fValueTimestamp != null) { + if (value instanceof TmfTimestamp) { + TmfTimestamp valueTimestamp = (TmfTimestamp) value; + return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot; + } + try { + TmfTimestamp valueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat + .getInstance().parse(value.toString()).doubleValue())); + return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot; + } catch (ParseException e) { + } + } + } + return false ^ fNot; + } + + @Override + public List getValidChildren() { + return new ArrayList(0); + } + + @Override + public String toString() { + String result = (fResult == 0 ? "= " : fResult < 0 ? "< " : "> "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + String open = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "["); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + String close = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return fField + (fNot ? " not " : " ") + result + open + fValue + close; //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + public ITmfFilterTreeNode clone() { + TmfFilterCompareNode clone = (TmfFilterCompareNode) super.clone(); + clone.fField = fField; + clone.setValue(fValue); + return clone; + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java index a00af6f4ec..97410f98f3 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java @@ -1,140 +1,140 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * Filter node for the 'contains' operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterContainsNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "CONTAINS"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ - public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ - public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$ - - private boolean fNot = false; - private String fField; - private String fValue; - private String fValueUpperCase; - private boolean fIgnoreCase = false; - - /** - * @param parent the parent node - */ - public TmfFilterContainsNode(ITmfFilterTreeNode parent) { - super(parent); - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - /** - * @return the field name - */ - public String getField() { - return fField; - } - - /** - * @param field the field name - */ - public void setField(String field) { - this.fField = field; - } - - /** - * @return the contains value - */ - public String getValue() { - return fValue; - } - - /** - * @param value the contains value - */ - public void setValue(String value) { - this.fValue = value; - fValueUpperCase = value.toUpperCase(); - } - - /** - * @return the ignoreCase state - */ - public boolean isIgnoreCase() { - return fIgnoreCase; - } - - /** - * @param ignoreCase the ignoreCase state - */ - public void setIgnoreCase(boolean ignoreCase) { - this.fIgnoreCase = ignoreCase; - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - Object value = getFieldValue(event, fField); - if (value == null) { - return false ^ fNot; - } - String valueString = value.toString(); - if (fIgnoreCase) { - return valueString.toUpperCase().contains(fValueUpperCase) ^ fNot; - } - return valueString.contains(fValue) ^ fNot; - } - - @Override - public List getValidChildren() { - return new ArrayList(0); - } - - @Override - public String toString() { - return fField + (fNot ? " not" : "") + " contains \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - @Override - public ITmfFilterTreeNode clone() { - TmfFilterContainsNode clone = (TmfFilterContainsNode) super.clone(); - clone.fField = fField; - clone.setValue(fValue); - return clone; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * Filter node for the 'contains' operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterContainsNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "CONTAINS"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ + public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ + public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$ + + private boolean fNot = false; + private String fField; + private String fValue; + private String fValueUpperCase; + private boolean fIgnoreCase = false; + + /** + * @param parent the parent node + */ + public TmfFilterContainsNode(ITmfFilterTreeNode parent) { + super(parent); + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + /** + * @return the field name + */ + public String getField() { + return fField; + } + + /** + * @param field the field name + */ + public void setField(String field) { + this.fField = field; + } + + /** + * @return the contains value + */ + public String getValue() { + return fValue; + } + + /** + * @param value the contains value + */ + public void setValue(String value) { + this.fValue = value; + fValueUpperCase = value.toUpperCase(); + } + + /** + * @return the ignoreCase state + */ + public boolean isIgnoreCase() { + return fIgnoreCase; + } + + /** + * @param ignoreCase the ignoreCase state + */ + public void setIgnoreCase(boolean ignoreCase) { + this.fIgnoreCase = ignoreCase; + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + Object value = getFieldValue(event, fField); + if (value == null) { + return false ^ fNot; + } + String valueString = value.toString(); + if (fIgnoreCase) { + return valueString.toUpperCase().contains(fValueUpperCase) ^ fNot; + } + return valueString.contains(fValue) ^ fNot; + } + + @Override + public List getValidChildren() { + return new ArrayList(0); + } + + @Override + public String toString() { + return fField + (fNot ? " not" : "") + " contains \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + @Override + public ITmfFilterTreeNode clone() { + TmfFilterContainsNode clone = (TmfFilterContainsNode) super.clone(); + clone.fField = fField; + clone.setValue(fValue); + return clone; + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java index 8c54f04f56..9bd3efda64 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java @@ -1,142 +1,142 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - - -/** - * Filter node for the '==' operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterEqualsNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "EQUALS"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ - public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ - public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$ - - private boolean fNot = false; - private String fField; - private String fValue; - private boolean fIgnoreCase = false; - - /** - * @param parent the aprent node - */ - public TmfFilterEqualsNode(ITmfFilterTreeNode parent) { - super(parent); - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - /** - * @return the field name - */ - public String getField() { - return fField; - } - - /** - * @param field the field name - */ - public void setField(String field) { - this.fField = field; - } - - /** - * @return the equals value - */ - public String getValue() { - return fValue; - } - - /** - * @param value the equals value - */ - public void setValue(String value) { - this.fValue = value; - } - - /** - * @return the ignoreCase state - */ - public boolean isIgnoreCase() { - return fIgnoreCase; - } - - /** - * @param ignoreCase the ignoreCase state - */ - public void setIgnoreCase(boolean ignoreCase) { - this.fIgnoreCase = ignoreCase; - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - Object value = getFieldValue(event, fField); - if (value == null) { - return false ^ fNot; - } - String valueString = value.toString(); - if (valueString == null) { - return false ^ fNot; - } - if (fIgnoreCase) { - return valueString.equalsIgnoreCase(fValue) ^ fNot; - } - return valueString.equals(fValue) ^ fNot; - } - - @Override - public List getValidChildren() { - return new ArrayList(0); - } - - @Override - public String toString() { - return fField + (fNot ? " not" : "") + " equals \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - @Override - public ITmfFilterTreeNode clone() { - TmfFilterEqualsNode clone = (TmfFilterEqualsNode) super.clone(); - clone.fField = fField; - clone.fValue = fValue; - return clone; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + + +/** + * Filter node for the '==' operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterEqualsNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "EQUALS"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ + public static final String VALUE_ATTR = "value"; //$NON-NLS-1$ + public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$ + + private boolean fNot = false; + private String fField; + private String fValue; + private boolean fIgnoreCase = false; + + /** + * @param parent the aprent node + */ + public TmfFilterEqualsNode(ITmfFilterTreeNode parent) { + super(parent); + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + /** + * @return the field name + */ + public String getField() { + return fField; + } + + /** + * @param field the field name + */ + public void setField(String field) { + this.fField = field; + } + + /** + * @return the equals value + */ + public String getValue() { + return fValue; + } + + /** + * @param value the equals value + */ + public void setValue(String value) { + this.fValue = value; + } + + /** + * @return the ignoreCase state + */ + public boolean isIgnoreCase() { + return fIgnoreCase; + } + + /** + * @param ignoreCase the ignoreCase state + */ + public void setIgnoreCase(boolean ignoreCase) { + this.fIgnoreCase = ignoreCase; + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + Object value = getFieldValue(event, fField); + if (value == null) { + return false ^ fNot; + } + String valueString = value.toString(); + if (valueString == null) { + return false ^ fNot; + } + if (fIgnoreCase) { + return valueString.equalsIgnoreCase(fValue) ^ fNot; + } + return valueString.equals(fValue) ^ fNot; + } + + @Override + public List getValidChildren() { + return new ArrayList(0); + } + + @Override + public String toString() { + return fField + (fNot ? " not" : "") + " equals \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + @Override + public ITmfFilterTreeNode clone() { + TmfFilterEqualsNode clone = (TmfFilterEqualsNode) super.clone(); + clone.fField = fField; + clone.fValue = fValue; + return clone; + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java index 70137b7857..223abe6a88 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java @@ -1,133 +1,133 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * Filter node for an event - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterEventTypeNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "EVENTTYPE"; //$NON-NLS-1$ - public static final String TYPE_ATTR = "type"; //$NON-NLS-1$ - public static final String NAME_ATTR = "name"; //$NON-NLS-1$ - - private String fType; - private String fName; - - /** - * @param parent the parent node - */ - public TmfFilterEventTypeNode(ITmfFilterTreeNode parent) { - super(parent); - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - /** - * @return the event type - */ - public String getEventType() { - return fType; - } - - /** - * @param type the event type - */ - public void setEventType(String type) { - this.fType = type; - } - - /** - * @return TBD - */ - public String getName() { - return fName; - } - - /** - * @param name TBD - */ - public void setName(String name) { - this.fName = name; - } - - @Override - public boolean matches(ITmfEvent event) { - boolean match = false; - if (fType.contains(":")) { //$NON-NLS-1$ - // special case for custom parsers - if (fType.startsWith(event.getClass().getCanonicalName())) { - if (fType.endsWith(event.getType().getName())) { - match = true; - } - } - } else { - if (event.getClass().getCanonicalName().equals(fType)) { - match = true; - } - } - if (match) { - // There should be at most one child - for (ITmfFilterTreeNode node : getChildren()) { - if (! node.matches(event)) { - return false; - } - } - return true; - } - return false; - } - - @Override - public List getValidChildren() { - if (getChildrenCount() == 0) { - return super.getValidChildren(); - } - return new ArrayList(0); // only one child allowed - } - - @Override - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append("EventType is " + fName); //$NON-NLS-1$ - if (getChildrenCount() > 0) { - buf.append(" and "); //$NON-NLS-1$ - } - if (getChildrenCount() > 1) { - buf.append("( "); //$NON-NLS-1$ - } - for (int i = 0; i < getChildrenCount(); i++) { - ITmfFilterTreeNode node = getChildren()[i]; - buf.append(node.toString()); - if (i < getChildrenCount() - 1) { - buf.append(" and "); //$NON-NLS-1$ - } - } - if (getChildrenCount() > 1) { - buf.append(" )"); //$NON-NLS-1$ - } - return buf.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * Filter node for an event + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterEventTypeNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "EVENTTYPE"; //$NON-NLS-1$ + public static final String TYPE_ATTR = "type"; //$NON-NLS-1$ + public static final String NAME_ATTR = "name"; //$NON-NLS-1$ + + private String fType; + private String fName; + + /** + * @param parent the parent node + */ + public TmfFilterEventTypeNode(ITmfFilterTreeNode parent) { + super(parent); + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + /** + * @return the event type + */ + public String getEventType() { + return fType; + } + + /** + * @param type the event type + */ + public void setEventType(String type) { + this.fType = type; + } + + /** + * @return TBD + */ + public String getName() { + return fName; + } + + /** + * @param name TBD + */ + public void setName(String name) { + this.fName = name; + } + + @Override + public boolean matches(ITmfEvent event) { + boolean match = false; + if (fType.contains(":")) { //$NON-NLS-1$ + // special case for custom parsers + if (fType.startsWith(event.getClass().getCanonicalName())) { + if (fType.endsWith(event.getType().getName())) { + match = true; + } + } + } else { + if (event.getClass().getCanonicalName().equals(fType)) { + match = true; + } + } + if (match) { + // There should be at most one child + for (ITmfFilterTreeNode node : getChildren()) { + if (! node.matches(event)) { + return false; + } + } + return true; + } + return false; + } + + @Override + public List getValidChildren() { + if (getChildrenCount() == 0) { + return super.getValidChildren(); + } + return new ArrayList(0); // only one child allowed + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("EventType is " + fName); //$NON-NLS-1$ + if (getChildrenCount() > 0) { + buf.append(" and "); //$NON-NLS-1$ + } + if (getChildrenCount() > 1) { + buf.append("( "); //$NON-NLS-1$ + } + for (int i = 0; i < getChildrenCount(); i++) { + ITmfFilterTreeNode node = getChildren()[i]; + buf.append(node.toString()); + if (i < getChildrenCount() - 1) { + buf.append(" and "); //$NON-NLS-1$ + } + } + if (getChildrenCount() > 1) { + buf.append(" )"); //$NON-NLS-1$ + } + return buf.toString(); + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterMatchesNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterMatchesNode.java index 8d2c35c875..eb3d5ae48e 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterMatchesNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterMatchesNode.java @@ -1,146 +1,146 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * Filter node for the regex match - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterMatchesNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "MATCHES"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ - public static final String REGEX_ATTR = "regex"; //$NON-NLS-1$ - - private boolean fNot = false; - private String fField; - private String fRegex; - private Pattern fPattern; - - /** - * @param parent the parent node - */ - public TmfFilterMatchesNode(ITmfFilterTreeNode parent) { - super(parent); - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - /** - * @return the field name - */ - public String getField() { - return fField; - } - - /** - * @param field the field name - */ - public void setField(String field) { - this.fField = field; - } - - /** - * @return the regular expression - */ - public String getRegex() { - return fRegex; - } - - /** - * @param regex the regular expression - */ - public void setRegex(String regex) { - this.fRegex = regex; - try { - this.fPattern = Pattern.compile(regex); - } catch (PatternSyntaxException e) { - this.fPattern = null; - } - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - if (fPattern == null) { - return false ^ fNot; - } - - Object value = getFieldValue(event, fField); - if (value == null) { - return false ^ fNot; - } - String valueString = value.toString(); - - return fPattern.matcher(valueString).matches() ^ fNot; - } - - @Override - public List getValidChildren() { - return new ArrayList(0); - } - - @Override - public String toString() { - return fField + (fNot ? " not" : "") + " matches \"" + fRegex + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - @Override - public ITmfFilterTreeNode clone() { - TmfFilterMatchesNode clone = (TmfFilterMatchesNode) super.clone(); - clone.fField = fField; - clone.setRegex(fRegex); - return clone; - } - - /** - * @param pattern the rough regex pattern - * @return the compliant regex - */ - public static String regexFix(String pattern) { - // if the pattern does not contain one of the expressions .* !^ - // (at the beginning) $ (at the end), then a .* is added at the - // beginning and at the end of the pattern - if (!(pattern.indexOf(".*") >= 0 || pattern.charAt(0) == '^' || pattern.charAt(pattern.length() - 1) == '$')) { //$NON-NLS-1$ - pattern = ".*" + pattern + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ - } - return pattern; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * Filter node for the regex match + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterMatchesNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "MATCHES"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + public static final String FIELD_ATTR = "field"; //$NON-NLS-1$ + public static final String REGEX_ATTR = "regex"; //$NON-NLS-1$ + + private boolean fNot = false; + private String fField; + private String fRegex; + private Pattern fPattern; + + /** + * @param parent the parent node + */ + public TmfFilterMatchesNode(ITmfFilterTreeNode parent) { + super(parent); + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + /** + * @return the field name + */ + public String getField() { + return fField; + } + + /** + * @param field the field name + */ + public void setField(String field) { + this.fField = field; + } + + /** + * @return the regular expression + */ + public String getRegex() { + return fRegex; + } + + /** + * @param regex the regular expression + */ + public void setRegex(String regex) { + this.fRegex = regex; + try { + this.fPattern = Pattern.compile(regex); + } catch (PatternSyntaxException e) { + this.fPattern = null; + } + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + if (fPattern == null) { + return false ^ fNot; + } + + Object value = getFieldValue(event, fField); + if (value == null) { + return false ^ fNot; + } + String valueString = value.toString(); + + return fPattern.matcher(valueString).matches() ^ fNot; + } + + @Override + public List getValidChildren() { + return new ArrayList(0); + } + + @Override + public String toString() { + return fField + (fNot ? " not" : "") + " matches \"" + fRegex + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + @Override + public ITmfFilterTreeNode clone() { + TmfFilterMatchesNode clone = (TmfFilterMatchesNode) super.clone(); + clone.fField = fField; + clone.setRegex(fRegex); + return clone; + } + + /** + * @param pattern the rough regex pattern + * @return the compliant regex + */ + public static String regexFix(String pattern) { + // if the pattern does not contain one of the expressions .* !^ + // (at the beginning) $ (at the end), then a .* is added at the + // beginning and at the end of the pattern + if (!(pattern.indexOf(".*") >= 0 || pattern.charAt(0) == '^' || pattern.charAt(pattern.length() - 1) == '$')) { //$NON-NLS-1$ + pattern = ".*" + pattern + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return pattern; + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java index 9c610f3073..ad08829f43 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java @@ -1,107 +1,107 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * Filter node for the event match operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "FILTER"; //$NON-NLS-1$ - public static final String NAME_ATTR = "name"; //$NON-NLS-1$ - - String fFilterName; - - /** - * @param filterName the filter name - */ - public TmfFilterNode(String filterName) { - super(null); - fFilterName = filterName; - } - - /** - * @param parent the parent node - * @param filterName the filter name - */ - public TmfFilterNode(ITmfFilterTreeNode parent, String filterName) { - super(parent); - fFilterName = filterName; - } - - /** - * @return the filer name - */ - public String getFilterName() { - return fFilterName; - } - - /** - * @param filterName the filer name - */ - public void setFilterName(String filterName) { - fFilterName = filterName; - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - // There should be at most one child - for (ITmfFilterTreeNode node : getChildren()) { - if (node.matches(event)) { - return true; - } - } - return false; - } - - @Override - public List getValidChildren() { - if (getChildrenCount() == 0) { - return super.getValidChildren(); - } - return new ArrayList(0); // only one child allowed - } - - @Override - public String toString() { - StringBuffer buf = new StringBuffer(); - if (getChildrenCount() > 1) { - buf.append("( "); //$NON-NLS-1$ - } - for (int i = 0; i < getChildrenCount(); i++) { - ITmfFilterTreeNode node = getChildren()[i]; - buf.append(node.toString()); - if (i < (getChildrenCount() - 1)) { - buf.append(" and "); //$NON-NLS-1$ - } - } - if (getChildrenCount() > 1) { - buf.append(" )"); //$NON-NLS-1$ - } - return buf.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * Filter node for the event match operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "FILTER"; //$NON-NLS-1$ + public static final String NAME_ATTR = "name"; //$NON-NLS-1$ + + String fFilterName; + + /** + * @param filterName the filter name + */ + public TmfFilterNode(String filterName) { + super(null); + fFilterName = filterName; + } + + /** + * @param parent the parent node + * @param filterName the filter name + */ + public TmfFilterNode(ITmfFilterTreeNode parent, String filterName) { + super(parent); + fFilterName = filterName; + } + + /** + * @return the filer name + */ + public String getFilterName() { + return fFilterName; + } + + /** + * @param filterName the filer name + */ + public void setFilterName(String filterName) { + fFilterName = filterName; + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + // There should be at most one child + for (ITmfFilterTreeNode node : getChildren()) { + if (node.matches(event)) { + return true; + } + } + return false; + } + + @Override + public List getValidChildren() { + if (getChildrenCount() == 0) { + return super.getValidChildren(); + } + return new ArrayList(0); // only one child allowed + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + if (getChildrenCount() > 1) { + buf.append("( "); //$NON-NLS-1$ + } + for (int i = 0; i < getChildrenCount(); i++) { + ITmfFilterTreeNode node = getChildren()[i]; + buf.append(node.toString()); + if (i < (getChildrenCount() - 1)) { + buf.append(" and "); //$NON-NLS-1$ + } + } + if (getChildrenCount() > 1) { + buf.append(" )"); //$NON-NLS-1$ + } + return buf.toString(); + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java index fa474e1959..05969daca3 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * Filter node for the 'or' operation - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TmfFilterOrNode extends TmfFilterTreeNode { - - public static final String NODE_NAME = "OR"; //$NON-NLS-1$ - public static final String NOT_ATTR = "not"; //$NON-NLS-1$ - - private boolean fNot = false; - - /** - * @param parent the parent node - */ - public TmfFilterOrNode(ITmfFilterTreeNode parent) { - super(parent); - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - /** - * @return the NOT state - */ - public boolean isNot() { - return fNot; - } - - /** - * @param not the NOT state - */ - public void setNot(boolean not) { - this.fNot = not; - } - - @Override - public boolean matches(ITmfEvent event) { - for (ITmfFilterTreeNode node : getChildren()) { - if (node.matches(event)) { - return true ^ fNot; - } - } - return false & fNot; - } - - @Override - public String toString() { - StringBuffer buf = new StringBuffer(); - if (fNot) { - buf.append("not "); //$NON-NLS-1$ - } - if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { - buf.append("( "); //$NON-NLS-1$ - } - for (int i = 0; i < getChildrenCount(); i++) { - ITmfFilterTreeNode node = getChildren()[i]; - buf.append(node.toString()); - if (i < getChildrenCount() - 1) { - buf.append(" or "); //$NON-NLS-1$ - } - } - if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { - buf.append(" )"); //$NON-NLS-1$ - } - return buf.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * Filter node for the 'or' operation + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TmfFilterOrNode extends TmfFilterTreeNode { + + public static final String NODE_NAME = "OR"; //$NON-NLS-1$ + public static final String NOT_ATTR = "not"; //$NON-NLS-1$ + + private boolean fNot = false; + + /** + * @param parent the parent node + */ + public TmfFilterOrNode(ITmfFilterTreeNode parent) { + super(parent); + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + /** + * @return the NOT state + */ + public boolean isNot() { + return fNot; + } + + /** + * @param not the NOT state + */ + public void setNot(boolean not) { + this.fNot = not; + } + + @Override + public boolean matches(ITmfEvent event) { + for (ITmfFilterTreeNode node : getChildren()) { + if (node.matches(event)) { + return true ^ fNot; + } + } + return false & fNot; + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + if (fNot) { + buf.append("not "); //$NON-NLS-1$ + } + if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { + buf.append("( "); //$NON-NLS-1$ + } + for (int i = 0; i < getChildrenCount(); i++) { + ITmfFilterTreeNode node = getChildren()[i]; + buf.append(node.toString()); + if (i < getChildrenCount() - 1) { + buf.append(" or "); //$NON-NLS-1$ + } + } + if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) { + buf.append(" )"); //$NON-NLS-1$ + } + return buf.toString(); + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java index f7f00be67a..6a3cb99a7a 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.Arrays; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; - -/** - * The Filter tree root node - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfFilterRootNode extends TmfFilterTreeNode { - - @SuppressWarnings("javadoc") - public static final String NODE_NAME = "ROOT"; //$NON-NLS-1$ - - private static final String[] VALID_CHILDREN = { - TmfFilterNode.NODE_NAME - }; - - /** - * Default constructor - */ - public TmfFilterRootNode() { - super(null); - } - - @Override - public String getNodeName() { - return NODE_NAME; - } - - @Override - public boolean matches(ITmfEvent event) { - for (ITmfFilterTreeNode node : getChildren()) { - if (! node.matches(event)) { - return false; - } - } - return true; - } - - @Override - public List getValidChildren() { - return Arrays.asList(VALID_CHILDREN); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; + +/** + * The Filter tree root node + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfFilterRootNode extends TmfFilterTreeNode { + + @SuppressWarnings("javadoc") + public static final String NODE_NAME = "ROOT"; //$NON-NLS-1$ + + private static final String[] VALID_CHILDREN = { + TmfFilterNode.NODE_NAME + }; + + /** + * Default constructor + */ + public TmfFilterRootNode() { + super(null); + } + + @Override + public String getNodeName() { + return NODE_NAME; + } + + @Override + public boolean matches(ITmfEvent event) { + for (ITmfFilterTreeNode node : getChildren()) { + if (! node.matches(event)) { + return false; + } + } + return true; + } + + @Override + public List getValidChildren() { + return Arrays.asList(VALID_CHILDREN); + } + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterTreeNode.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterTreeNode.java index d5cb9b5d5a..6f65440c8c 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterTreeNode.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterTreeNode.java @@ -1,214 +1,214 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.model; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; - -/** - * The base class for the Filter tree nodes - * - * @version 1.0 - * @author Yuriy Vashchuk - * @author Patrick Tasse - */ -public abstract class TmfFilterTreeNode implements ITmfFilterTreeNode, Cloneable { - - private static final String[] VALID_CHILDREN = { - TmfFilterEventTypeNode.NODE_NAME, - TmfFilterAndNode.NODE_NAME, - TmfFilterOrNode.NODE_NAME, - TmfFilterContainsNode.NODE_NAME, - TmfFilterEqualsNode.NODE_NAME, - TmfFilterMatchesNode.NODE_NAME, - TmfFilterCompareNode.NODE_NAME - }; - - private ITmfFilterTreeNode parent = null; - private ArrayList children = new ArrayList(); - - /** - * @param parent the parent node - */ - public TmfFilterTreeNode(final ITmfFilterTreeNode parent) { - if (parent != null) { - parent.addChild(this); - } - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getParent() - */ - @Override - public ITmfFilterTreeNode getParent() { - return parent; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getNodeName() - */ - @Override - public abstract String getNodeName(); - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#hasChildren() - */ - @Override - public boolean hasChildren() { - return (children.size() > 0); - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChildrenCount() - */ - @Override - public int getChildrenCount() { - return children.size(); - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChildren() - */ - @Override - public ITmfFilterTreeNode[] getChildren() { - return children.toArray(new ITmfFilterTreeNode[0]); - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChild(int) - */ - @Override - public ITmfFilterTreeNode getChild(final int index) throws IndexOutOfBoundsException { - return children.get(index); - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#remove() - */ - @Override - public ITmfFilterTreeNode remove() { - if (getParent() != null) { - getParent().removeChild(this); - } - return this; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#removeChild(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) - */ - @Override - public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node) { - children.remove(node); - node.setParent(null); - return node; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#addChild(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) - */ - @Override - public int addChild(final ITmfFilterTreeNode node) { - node.setParent(this); - if(children.add(node)) { - return (children.size() - 1); - } - return -1; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#replaceChild(int, org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) - */ - @Override - public ITmfFilterTreeNode replaceChild(final int index, final ITmfFilterTreeNode node) throws IndexOutOfBoundsException { - node.setParent(this); - return children.set(index, node); - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#setParent(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) - */ - @Override - public void setParent(final ITmfFilterTreeNode parent) { - this.parent = parent; - } - - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#matches(org.eclipse.linuxtools.tmf.event.TmfEvent) - */ - @Override - public abstract boolean matches(ITmfEvent event); - - /** - * @param event the event - * @param field the field id - * @return the field value - */ - protected Object getFieldValue(ITmfEvent event, String field) { - Object value = null; - if (ITmfEvent.EVENT_FIELD_CONTENT.equals(field)) { - ITmfEventField content = event.getContent(); - value = (content.getValue() != null) ? content.getValue().toString() : content.toString(); - } - else if (ITmfEvent.EVENT_FIELD_TYPE.equals(field)) { - value = event.getType().getName(); - } - else if (ITmfEvent.EVENT_FIELD_TIMESTAMP.equals(field)) { - value = event.getTimestamp().toString(); - } - else if (ITmfEvent.EVENT_FIELD_SOURCE.equals(field)) { - value = event.getSource(); - } - else if (ITmfEvent.EVENT_FIELD_REFERENCE.equals(field)) { - value = event.getReference(); - } - else { - ITmfEventField eventField = event.getContent().getField(field); - if (eventField != null) { - value = eventField.getValue(); - } - } - return value; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getValidChildren() - * - * By default, all node types are valid children. Override if different. - */ - @Override - public List getValidChildren() { - return Arrays.asList(VALID_CHILDREN); - } - - @Override - public ITmfFilterTreeNode clone() { - try { - TmfFilterTreeNode clone = (TmfFilterTreeNode) super.clone(); - clone.parent = null; - clone.children = new ArrayList(children.size()); - for (ITmfFilterTreeNode child : getChildren()) { - clone.addChild(child.clone()); - } - return clone; - } catch (CloneNotSupportedException e) { - return null; - } - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; + +/** + * The base class for the Filter tree nodes + * + * @version 1.0 + * @author Yuriy Vashchuk + * @author Patrick Tasse + */ +public abstract class TmfFilterTreeNode implements ITmfFilterTreeNode, Cloneable { + + private static final String[] VALID_CHILDREN = { + TmfFilterEventTypeNode.NODE_NAME, + TmfFilterAndNode.NODE_NAME, + TmfFilterOrNode.NODE_NAME, + TmfFilterContainsNode.NODE_NAME, + TmfFilterEqualsNode.NODE_NAME, + TmfFilterMatchesNode.NODE_NAME, + TmfFilterCompareNode.NODE_NAME + }; + + private ITmfFilterTreeNode parent = null; + private ArrayList children = new ArrayList(); + + /** + * @param parent the parent node + */ + public TmfFilterTreeNode(final ITmfFilterTreeNode parent) { + if (parent != null) { + parent.addChild(this); + } + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getParent() + */ + @Override + public ITmfFilterTreeNode getParent() { + return parent; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getNodeName() + */ + @Override + public abstract String getNodeName(); + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#hasChildren() + */ + @Override + public boolean hasChildren() { + return (children.size() > 0); + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChildrenCount() + */ + @Override + public int getChildrenCount() { + return children.size(); + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChildren() + */ + @Override + public ITmfFilterTreeNode[] getChildren() { + return children.toArray(new ITmfFilterTreeNode[0]); + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getChild(int) + */ + @Override + public ITmfFilterTreeNode getChild(final int index) throws IndexOutOfBoundsException { + return children.get(index); + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#remove() + */ + @Override + public ITmfFilterTreeNode remove() { + if (getParent() != null) { + getParent().removeChild(this); + } + return this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#removeChild(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) + */ + @Override + public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node) { + children.remove(node); + node.setParent(null); + return node; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#addChild(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) + */ + @Override + public int addChild(final ITmfFilterTreeNode node) { + node.setParent(this); + if(children.add(node)) { + return (children.size() - 1); + } + return -1; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#replaceChild(int, org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) + */ + @Override + public ITmfFilterTreeNode replaceChild(final int index, final ITmfFilterTreeNode node) throws IndexOutOfBoundsException { + node.setParent(this); + return children.set(index, node); + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#setParent(org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode) + */ + @Override + public void setParent(final ITmfFilterTreeNode parent) { + this.parent = parent; + } + + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#matches(org.eclipse.linuxtools.tmf.event.TmfEvent) + */ + @Override + public abstract boolean matches(ITmfEvent event); + + /** + * @param event the event + * @param field the field id + * @return the field value + */ + protected Object getFieldValue(ITmfEvent event, String field) { + Object value = null; + if (ITmfEvent.EVENT_FIELD_CONTENT.equals(field)) { + ITmfEventField content = event.getContent(); + value = (content.getValue() != null) ? content.getValue().toString() : content.toString(); + } + else if (ITmfEvent.EVENT_FIELD_TYPE.equals(field)) { + value = event.getType().getName(); + } + else if (ITmfEvent.EVENT_FIELD_TIMESTAMP.equals(field)) { + value = event.getTimestamp().toString(); + } + else if (ITmfEvent.EVENT_FIELD_SOURCE.equals(field)) { + value = event.getSource(); + } + else if (ITmfEvent.EVENT_FIELD_REFERENCE.equals(field)) { + value = event.getReference(); + } + else { + ITmfEventField eventField = event.getContent().getField(field); + if (eventField != null) { + value = eventField.getValue(); + } + } + return value; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.filter.model.ITmfFilterTreeNode#getValidChildren() + * + * By default, all node types are valid children. Override if different. + */ + @Override + public List getValidChildren() { + return Arrays.asList(VALID_CHILDREN); + } + + @Override + public ITmfFilterTreeNode clone() { + try { + TmfFilterTreeNode clone = (TmfFilterTreeNode) super.clone(); + clone.parent = null; + clone.children = new ArrayList(children.size()); + for (ITmfFilterTreeNode child : getChildren()) { + clone.addChild(child.clone()); + } + return clone; + } catch (CloneNotSupportedException e) { + return null; + } + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java index befbae1c3a..5fb2298013 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java @@ -1,186 +1,186 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation - * based on http://smeric.developpez.com/java/cours/xml/sax/ - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.xml; - -import java.util.Stack; - -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * The SAX Content Handler - * - * @version 1.0 - * @author Yuriy Vashchuk - * @author Patrick Tasse - */ -public class TmfFilterContentHandler extends DefaultHandler { - - private ITmfFilterTreeNode fRoot = null; - private Stack fFilterTreeStack = null; - - /** - * The default constructor - */ - public TmfFilterContentHandler() { - super(); - fFilterTreeStack = new Stack(); - } - - /** - * Getter of tree - * - * @return The builded tree - */ - public ITmfFilterTreeNode getTree() { - return fRoot; - } - - /* - * (non-Javadoc) - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - ITmfFilterTreeNode node = null; - - if (localName.equalsIgnoreCase(TmfFilterRootNode.NODE_NAME)) { - - node = new TmfFilterRootNode(); - - } else if (localName.equals(TmfFilterNode.NODE_NAME)) { - - node = new TmfFilterNode(atts.getValue(TmfFilterNode.NAME_ATTR)); - - } else if (localName.equals(TmfFilterEventTypeNode.NODE_NAME)) { - - node = new TmfFilterEventTypeNode(null); - ((TmfFilterEventTypeNode) node).setEventType(atts.getValue(TmfFilterEventTypeNode.TYPE_ATTR)); - ((TmfFilterEventTypeNode) node).setName(atts.getValue(TmfFilterEventTypeNode.NAME_ATTR)); - - } else if (localName.equals(TmfFilterAndNode.NODE_NAME)) { - - node = new TmfFilterAndNode(null); - String value = atts.getValue(TmfFilterAndNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterAndNode) node).setNot(true); - } - - } else if (localName.equals(TmfFilterOrNode.NODE_NAME)) { - - node = new TmfFilterOrNode(null); - String value = atts.getValue(TmfFilterOrNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterOrNode) node).setNot(true); - } - - } else if (localName.equals(TmfFilterContainsNode.NODE_NAME)) { - - node = new TmfFilterContainsNode(null); - String value = atts.getValue(TmfFilterContainsNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterContainsNode) node).setNot(true); - } - ((TmfFilterContainsNode) node).setField(atts.getValue(TmfFilterContainsNode.FIELD_ATTR)); - ((TmfFilterContainsNode) node).setValue(atts.getValue(TmfFilterContainsNode.VALUE_ATTR)); - value = atts.getValue(TmfFilterContainsNode.IGNORECASE_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterContainsNode) node).setIgnoreCase(true); - } - - } else if (localName.equals(TmfFilterEqualsNode.NODE_NAME)) { - - node = new TmfFilterEqualsNode(null); - String value = atts.getValue(TmfFilterEqualsNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterEqualsNode) node).setNot(true); - } - ((TmfFilterEqualsNode) node).setField(atts.getValue(TmfFilterEqualsNode.FIELD_ATTR)); - ((TmfFilterEqualsNode) node).setValue(atts.getValue(TmfFilterEqualsNode.VALUE_ATTR)); - value = atts.getValue(TmfFilterEqualsNode.IGNORECASE_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterEqualsNode) node).setIgnoreCase(true); - } - - } else if (localName.equals(TmfFilterMatchesNode.NODE_NAME)) { - - node = new TmfFilterMatchesNode(null); - String value = atts.getValue(TmfFilterMatchesNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterMatchesNode) node).setNot(true); - } - ((TmfFilterMatchesNode) node).setField(atts.getValue(TmfFilterMatchesNode.FIELD_ATTR)); - ((TmfFilterMatchesNode) node).setRegex(atts.getValue(TmfFilterMatchesNode.REGEX_ATTR)); - - } else if (localName.equals(TmfFilterCompareNode.NODE_NAME)) { - - node = new TmfFilterCompareNode(null); - String value = atts.getValue(TmfFilterCompareNode.NOT_ATTR); - if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { - ((TmfFilterCompareNode) node).setNot(true); - } - ((TmfFilterCompareNode) node).setField(atts.getValue(TmfFilterCompareNode.FIELD_ATTR)); - value = atts.getValue(TmfFilterCompareNode.TYPE_ATTR); - if (value != null) { - ((TmfFilterCompareNode) node).setType(Type.valueOf(value)); - } - value = atts.getValue(TmfFilterCompareNode.RESULT_ATTR); - if (value != null) { - if (value.equals(Integer.toString(-1))) { - ((TmfFilterCompareNode) node).setResult(-1); - } else if (value.equals(Integer.toString(1))) { - ((TmfFilterCompareNode) node).setResult(1); - } else { - ((TmfFilterCompareNode) node).setResult(0); - } - } - ((TmfFilterCompareNode) node).setValue(atts.getValue(TmfFilterCompareNode.VALUE_ATTR)); - - } - - fFilterTreeStack.push(node); - } - - /* - * (non-Javadoc) - * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - ITmfFilterTreeNode node = fFilterTreeStack.pop(); - - if (fFilterTreeStack.isEmpty()) { - fRoot = node; - } else if (fFilterTreeStack.lastElement() instanceof TmfFilterTreeNode && - node instanceof TmfFilterTreeNode) { - fFilterTreeStack.lastElement().addChild(node); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation + * based on http://smeric.developpez.com/java/cours/xml/sax/ + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.xml; + +import java.util.Stack; + +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * The SAX Content Handler + * + * @version 1.0 + * @author Yuriy Vashchuk + * @author Patrick Tasse + */ +public class TmfFilterContentHandler extends DefaultHandler { + + private ITmfFilterTreeNode fRoot = null; + private Stack fFilterTreeStack = null; + + /** + * The default constructor + */ + public TmfFilterContentHandler() { + super(); + fFilterTreeStack = new Stack(); + } + + /** + * Getter of tree + * + * @return The builded tree + */ + public ITmfFilterTreeNode getTree() { + return fRoot; + } + + /* + * (non-Javadoc) + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + ITmfFilterTreeNode node = null; + + if (localName.equalsIgnoreCase(TmfFilterRootNode.NODE_NAME)) { + + node = new TmfFilterRootNode(); + + } else if (localName.equals(TmfFilterNode.NODE_NAME)) { + + node = new TmfFilterNode(atts.getValue(TmfFilterNode.NAME_ATTR)); + + } else if (localName.equals(TmfFilterEventTypeNode.NODE_NAME)) { + + node = new TmfFilterEventTypeNode(null); + ((TmfFilterEventTypeNode) node).setEventType(atts.getValue(TmfFilterEventTypeNode.TYPE_ATTR)); + ((TmfFilterEventTypeNode) node).setName(atts.getValue(TmfFilterEventTypeNode.NAME_ATTR)); + + } else if (localName.equals(TmfFilterAndNode.NODE_NAME)) { + + node = new TmfFilterAndNode(null); + String value = atts.getValue(TmfFilterAndNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterAndNode) node).setNot(true); + } + + } else if (localName.equals(TmfFilterOrNode.NODE_NAME)) { + + node = new TmfFilterOrNode(null); + String value = atts.getValue(TmfFilterOrNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterOrNode) node).setNot(true); + } + + } else if (localName.equals(TmfFilterContainsNode.NODE_NAME)) { + + node = new TmfFilterContainsNode(null); + String value = atts.getValue(TmfFilterContainsNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterContainsNode) node).setNot(true); + } + ((TmfFilterContainsNode) node).setField(atts.getValue(TmfFilterContainsNode.FIELD_ATTR)); + ((TmfFilterContainsNode) node).setValue(atts.getValue(TmfFilterContainsNode.VALUE_ATTR)); + value = atts.getValue(TmfFilterContainsNode.IGNORECASE_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterContainsNode) node).setIgnoreCase(true); + } + + } else if (localName.equals(TmfFilterEqualsNode.NODE_NAME)) { + + node = new TmfFilterEqualsNode(null); + String value = atts.getValue(TmfFilterEqualsNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterEqualsNode) node).setNot(true); + } + ((TmfFilterEqualsNode) node).setField(atts.getValue(TmfFilterEqualsNode.FIELD_ATTR)); + ((TmfFilterEqualsNode) node).setValue(atts.getValue(TmfFilterEqualsNode.VALUE_ATTR)); + value = atts.getValue(TmfFilterEqualsNode.IGNORECASE_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterEqualsNode) node).setIgnoreCase(true); + } + + } else if (localName.equals(TmfFilterMatchesNode.NODE_NAME)) { + + node = new TmfFilterMatchesNode(null); + String value = atts.getValue(TmfFilterMatchesNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterMatchesNode) node).setNot(true); + } + ((TmfFilterMatchesNode) node).setField(atts.getValue(TmfFilterMatchesNode.FIELD_ATTR)); + ((TmfFilterMatchesNode) node).setRegex(atts.getValue(TmfFilterMatchesNode.REGEX_ATTR)); + + } else if (localName.equals(TmfFilterCompareNode.NODE_NAME)) { + + node = new TmfFilterCompareNode(null); + String value = atts.getValue(TmfFilterCompareNode.NOT_ATTR); + if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) { + ((TmfFilterCompareNode) node).setNot(true); + } + ((TmfFilterCompareNode) node).setField(atts.getValue(TmfFilterCompareNode.FIELD_ATTR)); + value = atts.getValue(TmfFilterCompareNode.TYPE_ATTR); + if (value != null) { + ((TmfFilterCompareNode) node).setType(Type.valueOf(value)); + } + value = atts.getValue(TmfFilterCompareNode.RESULT_ATTR); + if (value != null) { + if (value.equals(Integer.toString(-1))) { + ((TmfFilterCompareNode) node).setResult(-1); + } else if (value.equals(Integer.toString(1))) { + ((TmfFilterCompareNode) node).setResult(1); + } else { + ((TmfFilterCompareNode) node).setResult(0); + } + } + ((TmfFilterCompareNode) node).setValue(atts.getValue(TmfFilterCompareNode.VALUE_ATTR)); + + } + + fFilterTreeStack.push(node); + } + + /* + * (non-Javadoc) + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + ITmfFilterTreeNode node = fFilterTreeStack.pop(); + + if (fFilterTreeStack.isEmpty()) { + fRoot = node; + } else if (fFilterTreeStack.lastElement() instanceof TmfFilterTreeNode && + node instanceof TmfFilterTreeNode) { + fFilterTreeStack.lastElement().addChild(node); + } + + } + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLParser.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLParser.java index e5befebc18..e1c6d6990d 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLParser.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLParser.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.xml; - -import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; - -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - -/** - * The SAX based XML parser - * - * @version 1.0 - * @author Yuriy Vashchuk - * @author Patrick Tasse - */ -public class TmfFilterXMLParser { - - private static ITmfFilterTreeNode fRoot = null; - - /** - * The XMLParser constructor - * - * @param uri The XML file to parse - * @throws SAXException SAX exception - * @throws IOException IO exception - */ - public TmfFilterXMLParser(final String uri) throws SAXException, IOException { - - SAXParserFactory m_parserFactory = null; - m_parserFactory = SAXParserFactory.newInstance(); - m_parserFactory.setNamespaceAware(true); - - XMLReader saxReader = null; - try { - - saxReader = m_parserFactory.newSAXParser().getXMLReader(); - saxReader.setContentHandler(new TmfFilterContentHandler()); - saxReader.parse(uri); - - fRoot = ((TmfFilterContentHandler) saxReader.getContentHandler()).getTree(); - - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } - } - - /** - * Getter of tree - * - * @return The builded tree - */ - public ITmfFilterTreeNode getTree() { - return fRoot; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.xml; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; + +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/** + * The SAX based XML parser + * + * @version 1.0 + * @author Yuriy Vashchuk + * @author Patrick Tasse + */ +public class TmfFilterXMLParser { + + private static ITmfFilterTreeNode fRoot = null; + + /** + * The XMLParser constructor + * + * @param uri The XML file to parse + * @throws SAXException SAX exception + * @throws IOException IO exception + */ + public TmfFilterXMLParser(final String uri) throws SAXException, IOException { + + SAXParserFactory m_parserFactory = null; + m_parserFactory = SAXParserFactory.newInstance(); + m_parserFactory.setNamespaceAware(true); + + XMLReader saxReader = null; + try { + + saxReader = m_parserFactory.newSAXParser().getXMLReader(); + saxReader.setContentHandler(new TmfFilterContentHandler()); + saxReader.parse(uri); + + fRoot = ((TmfFilterContentHandler) saxReader.getContentHandler()).getTree(); + + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + } + + /** + * Getter of tree + * + * @return The builded tree + */ + public ITmfFilterTreeNode getTree() { + return fRoot; + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java index 5a5fca5db0..264a96082e 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java @@ -1,162 +1,162 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.filter.xml; - -import java.io.File; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * The SAX based XML writer - * - * @version 1.0 - * @author Yuriy Vashchuk - * @author Patrick Tasse - */ -public class TmfFilterXMLWriter { - - private Document document = null; - - /** - * The XMLParser constructor - * - * @param root The tree root - * @throws ParserConfigurationException if a DocumentBuilder - * cannot be created which satisfies the configuration requested. - */ - public TmfFilterXMLWriter(final ITmfFilterTreeNode root) throws ParserConfigurationException { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - document = documentBuilder.newDocument(); - - Element rootElement = document.createElement(root.getNodeName()); - document.appendChild(rootElement); - - for (ITmfFilterTreeNode node : root.getChildren()) { - buildXMLTree(document, node, rootElement); - } - } - - /** - * The Tree to XML parser - * - * @param document The XML document - * @param treenode The node to write - * @param parentElement The XML element of the parent - */ - public static void buildXMLTree(final Document document, final ITmfFilterTreeNode treenode, Element parentElement) { - Element element = document.createElement(treenode.getNodeName()); - - if (treenode instanceof TmfFilterNode) { - - TmfFilterNode node = (TmfFilterNode) treenode; - element.setAttribute(TmfFilterNode.NAME_ATTR, node.getFilterName()); - - } else if (treenode instanceof TmfFilterEventTypeNode) { - - TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) treenode; - element.setAttribute(TmfFilterEventTypeNode.TYPE_ATTR, node.getEventType()); - element.setAttribute(TmfFilterEventTypeNode.NAME_ATTR, node.getName()); - - } else if (treenode instanceof TmfFilterAndNode) { - - TmfFilterAndNode node = (TmfFilterAndNode) treenode; - element.setAttribute(TmfFilterAndNode.NOT_ATTR, Boolean.toString(node.isNot())); - - } else if (treenode instanceof TmfFilterOrNode) { - - TmfFilterOrNode node = (TmfFilterOrNode) treenode; - element.setAttribute(TmfFilterOrNode.NOT_ATTR, Boolean.toString(node.isNot())); - - } else if (treenode instanceof TmfFilterContainsNode) { - - TmfFilterContainsNode node = (TmfFilterContainsNode) treenode; - element.setAttribute(TmfFilterContainsNode.NOT_ATTR, Boolean.toString(node.isNot())); - element.setAttribute(TmfFilterContainsNode.FIELD_ATTR, node.getField()); - element.setAttribute(TmfFilterContainsNode.VALUE_ATTR, node.getValue()); - element.setAttribute(TmfFilterContainsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase())); - - } else if (treenode instanceof TmfFilterEqualsNode) { - - TmfFilterEqualsNode node = (TmfFilterEqualsNode) treenode; - element.setAttribute(TmfFilterEqualsNode.NOT_ATTR, Boolean.toString(node.isNot())); - element.setAttribute(TmfFilterEqualsNode.FIELD_ATTR, node.getField()); - element.setAttribute(TmfFilterEqualsNode.VALUE_ATTR, node.getValue()); - element.setAttribute(TmfFilterEqualsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase())); - - } else if (treenode instanceof TmfFilterMatchesNode) { - - TmfFilterMatchesNode node = (TmfFilterMatchesNode) treenode; - element.setAttribute(TmfFilterMatchesNode.NOT_ATTR, Boolean.toString(node.isNot())); - element.setAttribute(TmfFilterMatchesNode.FIELD_ATTR, node.getField()); - element.setAttribute(TmfFilterMatchesNode.REGEX_ATTR, node.getRegex()); - - } else if (treenode instanceof TmfFilterCompareNode) { - - TmfFilterCompareNode node = (TmfFilterCompareNode) treenode; - element.setAttribute(TmfFilterCompareNode.NOT_ATTR, Boolean.toString(node.isNot())); - element.setAttribute(TmfFilterCompareNode.FIELD_ATTR, node.getField()); - element.setAttribute(TmfFilterCompareNode.RESULT_ATTR, Integer.toString(node.getResult())); - element.setAttribute(TmfFilterCompareNode.TYPE_ATTR, node.getType().toString()); - element.setAttribute(TmfFilterCompareNode.VALUE_ATTR, node.getValue()); - - } - - parentElement.appendChild(element); - - for (int i = 0; i < treenode.getChildrenCount(); i++) { - buildXMLTree(document, treenode.getChild(i), element); - } - } - - /** - * Save the tree - * - * @param uri The new Filter XML path - */ - public void saveTree(final String uri) { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - - try { - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(new File(uri)); - transformer.transform(source, result); - } catch (TransformerConfigurationException e) { - e.printStackTrace(); - } catch (TransformerException e) { - e.printStackTrace(); - } - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk (yvashchuk@gmail.com) - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.filter.xml; + +import java.io.File; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * The SAX based XML writer + * + * @version 1.0 + * @author Yuriy Vashchuk + * @author Patrick Tasse + */ +public class TmfFilterXMLWriter { + + private Document document = null; + + /** + * The XMLParser constructor + * + * @param root The tree root + * @throws ParserConfigurationException if a DocumentBuilder + * cannot be created which satisfies the configuration requested. + */ + public TmfFilterXMLWriter(final ITmfFilterTreeNode root) throws ParserConfigurationException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + document = documentBuilder.newDocument(); + + Element rootElement = document.createElement(root.getNodeName()); + document.appendChild(rootElement); + + for (ITmfFilterTreeNode node : root.getChildren()) { + buildXMLTree(document, node, rootElement); + } + } + + /** + * The Tree to XML parser + * + * @param document The XML document + * @param treenode The node to write + * @param parentElement The XML element of the parent + */ + public static void buildXMLTree(final Document document, final ITmfFilterTreeNode treenode, Element parentElement) { + Element element = document.createElement(treenode.getNodeName()); + + if (treenode instanceof TmfFilterNode) { + + TmfFilterNode node = (TmfFilterNode) treenode; + element.setAttribute(TmfFilterNode.NAME_ATTR, node.getFilterName()); + + } else if (treenode instanceof TmfFilterEventTypeNode) { + + TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) treenode; + element.setAttribute(TmfFilterEventTypeNode.TYPE_ATTR, node.getEventType()); + element.setAttribute(TmfFilterEventTypeNode.NAME_ATTR, node.getName()); + + } else if (treenode instanceof TmfFilterAndNode) { + + TmfFilterAndNode node = (TmfFilterAndNode) treenode; + element.setAttribute(TmfFilterAndNode.NOT_ATTR, Boolean.toString(node.isNot())); + + } else if (treenode instanceof TmfFilterOrNode) { + + TmfFilterOrNode node = (TmfFilterOrNode) treenode; + element.setAttribute(TmfFilterOrNode.NOT_ATTR, Boolean.toString(node.isNot())); + + } else if (treenode instanceof TmfFilterContainsNode) { + + TmfFilterContainsNode node = (TmfFilterContainsNode) treenode; + element.setAttribute(TmfFilterContainsNode.NOT_ATTR, Boolean.toString(node.isNot())); + element.setAttribute(TmfFilterContainsNode.FIELD_ATTR, node.getField()); + element.setAttribute(TmfFilterContainsNode.VALUE_ATTR, node.getValue()); + element.setAttribute(TmfFilterContainsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase())); + + } else if (treenode instanceof TmfFilterEqualsNode) { + + TmfFilterEqualsNode node = (TmfFilterEqualsNode) treenode; + element.setAttribute(TmfFilterEqualsNode.NOT_ATTR, Boolean.toString(node.isNot())); + element.setAttribute(TmfFilterEqualsNode.FIELD_ATTR, node.getField()); + element.setAttribute(TmfFilterEqualsNode.VALUE_ATTR, node.getValue()); + element.setAttribute(TmfFilterEqualsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase())); + + } else if (treenode instanceof TmfFilterMatchesNode) { + + TmfFilterMatchesNode node = (TmfFilterMatchesNode) treenode; + element.setAttribute(TmfFilterMatchesNode.NOT_ATTR, Boolean.toString(node.isNot())); + element.setAttribute(TmfFilterMatchesNode.FIELD_ATTR, node.getField()); + element.setAttribute(TmfFilterMatchesNode.REGEX_ATTR, node.getRegex()); + + } else if (treenode instanceof TmfFilterCompareNode) { + + TmfFilterCompareNode node = (TmfFilterCompareNode) treenode; + element.setAttribute(TmfFilterCompareNode.NOT_ATTR, Boolean.toString(node.isNot())); + element.setAttribute(TmfFilterCompareNode.FIELD_ATTR, node.getField()); + element.setAttribute(TmfFilterCompareNode.RESULT_ATTR, Integer.toString(node.getResult())); + element.setAttribute(TmfFilterCompareNode.TYPE_ATTR, node.getType().toString()); + element.setAttribute(TmfFilterCompareNode.VALUE_ATTR, node.getValue()); + + } + + parentElement.appendChild(element); + + for (int i = 0; i < treenode.getChildrenCount(); i++) { + buildXMLTree(document, treenode.getChild(i), element); + } + } + + /** + * Save the tree + * + * @param uri The new Filter XML path + */ + public void saveTree(final String uri) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + + try { + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(new File(uri)); + transformer.transform(source, result); + } catch (TransformerConfigurationException e) { + e.printStackTrace(); + } catch (TransformerException e) { + e.printStackTrace(); + } + } + +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/io/BufferedRandomAccessFile.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/io/BufferedRandomAccessFile.java index cc70b168e0..84f961227f 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/io/BufferedRandomAccessFile.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/io/BufferedRandomAccessFile.java @@ -1,226 +1,226 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation, based on article by Nick Zhang - * (http://www.javaworld.com/javatips/jw-javatip26.html) - ******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.io; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.charset.Charset; - -/** - * A class to mitigate the Java I/O inefficiency of RandomAccessFile. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class BufferedRandomAccessFile extends RandomAccessFile { - - private static final int DEFAULT_BUF_SIZE = 8192; - private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); //$NON-NLS-1$ - - final int BUF_SIZE; - byte buffer[]; - int buf_end = 0; - int buf_pos = 0; - long real_pos = 0; - StringBuilder sb = new StringBuilder(); - - /** - * Constructor using the default buffer size - * - * @param name - * File path. This is passed as-is to the RandomeAccessFile's - * constructor. - * @param mode - * File open mode ("r", "rw", etc.). This is passed as-is to - * RandomAccessFile's constructor. - * @throws IOException - * If the file was not found or couldn't be opened with the - * request permissions - */ - public BufferedRandomAccessFile(String name, String mode) throws IOException { - this(name, mode, DEFAULT_BUF_SIZE); - } - - /** - * Constructor using the default buffer size - * - * @param file - * File object. This is passed as-is to the RandomeAccessFile's - * constructor. - * @param mode - * File open mode ("r", "rw", etc.). This is passed as-is to - * RandomAccessFile's constructor. - * @throws IOException - * If the file was not found or couldn't be opened with the - * request permissions - */ - public BufferedRandomAccessFile(File file, String mode) throws IOException { - this(file, mode, DEFAULT_BUF_SIZE); - } - - /** - * Standard constructor. - * - * @param name - * File path. This is passed as-is to the RandomeAccessFile's - * constructor. - * @param mode - * File open mode ("r", "rw", etc.). This is passed as-is to - * RandomAccessFile's constructor. - * @param bufsize - * Buffer size to use, in bytes - * @throws IOException - * If the file was not found or couldn't be opened with the - * request permissions - */ - public BufferedRandomAccessFile(String name, String mode, int bufsize) throws IOException { - super(name, mode); - invalidate(); - BUF_SIZE = bufsize; - buffer = new byte[BUF_SIZE]; - } - - /** - * Standard constructor. - * - * @param file - * File object. This is passed as-is to the RandomeAccessFile's - * constructor. - * @param mode - * File open mode ("r", "rw", etc.). This is passed as-is to - * RandomAccessFile's constructor. - * @param bufsize - * Buffer size to use, in bytes - * @throws IOException - * If the file was not found or couldn't be opened with the - * request permissions - */ - public BufferedRandomAccessFile(File file, String mode, int bufsize) throws IOException { - super(file, mode); - invalidate(); - BUF_SIZE = bufsize; - buffer = new byte[BUF_SIZE]; - } - - @Override - public final int read() throws IOException{ - if (buf_pos >= buf_end) { - if (fillBuffer() < 0) { - return -1; - } - } - if (buf_end == 0) { - return -1; - } - return buffer[buf_pos++]; - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - int leftover = buf_end - buf_pos; - if (len <= leftover) { - System.arraycopy(buffer, buf_pos, b, off, len); - buf_pos += len; - return len; - } - for(int i = 0; i < len; i++) { - int c = this.read(); - if (c != -1) { - b[off+i] = (byte) c; - } else { - return i; - } - } - return len; - } - - @Override - public long getFilePointer() throws IOException{ - long l = real_pos; - return (l - buf_end + buf_pos); - } - - @Override - public void seek(long pos) throws IOException { - int n = (int) (real_pos - pos); - if(n >= 0 && n <= buf_end) { - buf_pos = buf_end - n; - } else { - super.seek(pos); - invalidate(); - } - } - - /** - * Read the next line from the buffer (ie, until the next '\n'). The bytes - * are interpreted as UTF-8 characters. - * - * @return The String that was read - * @throws IOException - * If we failed reading the file - */ - public final String getNextLine() throws IOException { - String str = null; - if (buf_end - buf_pos <= 0) { - if (fillBuffer() < 0) { - return null; - } - } - int lineend = -1; - for (int i = buf_pos; i < buf_end; i++) { - if (buffer[i] == '\n') { - lineend = i; - break; - } - } - if (lineend < 0) { - sb.delete(0, sb.length()); - int c; - while (((c = read()) != -1) && (c != '\n')) { - sb.append((char) c); - } - if ((c == -1) && (sb.length() == 0)) { - return null; - } - if (sb.charAt(sb.length() - 1) == '\r') { - sb.deleteCharAt(sb.length() - 1); - } - return sb.toString(); - } - if (lineend > 0 && buffer[lineend - 1] == '\r' && lineend > buf_pos) { - str = new String(buffer, buf_pos, lineend - buf_pos - 1, CHARSET_UTF8); - } else { - str = new String(buffer, buf_pos, lineend - buf_pos, CHARSET_UTF8); - } - buf_pos = lineend + 1; - return str; - } - - private int fillBuffer() throws IOException { - int n = super.read(buffer, 0, BUF_SIZE); - if (n >= 0) { - real_pos += n; - buf_end = n; - buf_pos = 0; - } - return n; - } - - private void invalidate() throws IOException { - buf_end = 0; - buf_pos = 0; - real_pos = super.getFilePointer(); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation, based on article by Nick Zhang + * (http://www.javaworld.com/javatips/jw-javatip26.html) + ******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.io; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.charset.Charset; + +/** + * A class to mitigate the Java I/O inefficiency of RandomAccessFile. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class BufferedRandomAccessFile extends RandomAccessFile { + + private static final int DEFAULT_BUF_SIZE = 8192; + private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); //$NON-NLS-1$ + + final int BUF_SIZE; + byte buffer[]; + int buf_end = 0; + int buf_pos = 0; + long real_pos = 0; + StringBuilder sb = new StringBuilder(); + + /** + * Constructor using the default buffer size + * + * @param name + * File path. This is passed as-is to the RandomeAccessFile's + * constructor. + * @param mode + * File open mode ("r", "rw", etc.). This is passed as-is to + * RandomAccessFile's constructor. + * @throws IOException + * If the file was not found or couldn't be opened with the + * request permissions + */ + public BufferedRandomAccessFile(String name, String mode) throws IOException { + this(name, mode, DEFAULT_BUF_SIZE); + } + + /** + * Constructor using the default buffer size + * + * @param file + * File object. This is passed as-is to the RandomeAccessFile's + * constructor. + * @param mode + * File open mode ("r", "rw", etc.). This is passed as-is to + * RandomAccessFile's constructor. + * @throws IOException + * If the file was not found or couldn't be opened with the + * request permissions + */ + public BufferedRandomAccessFile(File file, String mode) throws IOException { + this(file, mode, DEFAULT_BUF_SIZE); + } + + /** + * Standard constructor. + * + * @param name + * File path. This is passed as-is to the RandomeAccessFile's + * constructor. + * @param mode + * File open mode ("r", "rw", etc.). This is passed as-is to + * RandomAccessFile's constructor. + * @param bufsize + * Buffer size to use, in bytes + * @throws IOException + * If the file was not found or couldn't be opened with the + * request permissions + */ + public BufferedRandomAccessFile(String name, String mode, int bufsize) throws IOException { + super(name, mode); + invalidate(); + BUF_SIZE = bufsize; + buffer = new byte[BUF_SIZE]; + } + + /** + * Standard constructor. + * + * @param file + * File object. This is passed as-is to the RandomeAccessFile's + * constructor. + * @param mode + * File open mode ("r", "rw", etc.). This is passed as-is to + * RandomAccessFile's constructor. + * @param bufsize + * Buffer size to use, in bytes + * @throws IOException + * If the file was not found or couldn't be opened with the + * request permissions + */ + public BufferedRandomAccessFile(File file, String mode, int bufsize) throws IOException { + super(file, mode); + invalidate(); + BUF_SIZE = bufsize; + buffer = new byte[BUF_SIZE]; + } + + @Override + public final int read() throws IOException{ + if (buf_pos >= buf_end) { + if (fillBuffer() < 0) { + return -1; + } + } + if (buf_end == 0) { + return -1; + } + return buffer[buf_pos++]; + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + int leftover = buf_end - buf_pos; + if (len <= leftover) { + System.arraycopy(buffer, buf_pos, b, off, len); + buf_pos += len; + return len; + } + for(int i = 0; i < len; i++) { + int c = this.read(); + if (c != -1) { + b[off+i] = (byte) c; + } else { + return i; + } + } + return len; + } + + @Override + public long getFilePointer() throws IOException{ + long l = real_pos; + return (l - buf_end + buf_pos); + } + + @Override + public void seek(long pos) throws IOException { + int n = (int) (real_pos - pos); + if(n >= 0 && n <= buf_end) { + buf_pos = buf_end - n; + } else { + super.seek(pos); + invalidate(); + } + } + + /** + * Read the next line from the buffer (ie, until the next '\n'). The bytes + * are interpreted as UTF-8 characters. + * + * @return The String that was read + * @throws IOException + * If we failed reading the file + */ + public final String getNextLine() throws IOException { + String str = null; + if (buf_end - buf_pos <= 0) { + if (fillBuffer() < 0) { + return null; + } + } + int lineend = -1; + for (int i = buf_pos; i < buf_end; i++) { + if (buffer[i] == '\n') { + lineend = i; + break; + } + } + if (lineend < 0) { + sb.delete(0, sb.length()); + int c; + while (((c = read()) != -1) && (c != '\n')) { + sb.append((char) c); + } + if ((c == -1) && (sb.length() == 0)) { + return null; + } + if (sb.charAt(sb.length() - 1) == '\r') { + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + if (lineend > 0 && buffer[lineend - 1] == '\r' && lineend > buf_pos) { + str = new String(buffer, buf_pos, lineend - buf_pos - 1, CHARSET_UTF8); + } else { + str = new String(buffer, buf_pos, lineend - buf_pos, CHARSET_UTF8); + } + buf_pos = lineend + 1; + return str; + } + + private int fillBuffer() throws IOException { + int n = super.read(buffer, 0, BUF_SIZE); + if (n >= 0) { + real_pos += n; + buf_end = n; + buf_pos = 0; + } + return n; + } + + private void invalidate() throws IOException { + buf_end = 0; + buf_pos = 0; + real_pos = super.getFilePointer(); + } +} diff --git a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfTraceSelectedSignal.java b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfTraceSelectedSignal.java index c4a2d2507c..cc0abf52e4 100644 --- a/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfTraceSelectedSignal.java +++ b/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfTraceSelectedSignal.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.core.signal; - -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -/** - * A trace was selected - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceSelectedSignal extends TmfSignal { - - private final ITmfTrace fTrace; - - /** - * Constructor - * - * @param source - * Object sending this signal - * @param trace - * The trace that was selected - */ - public TmfTraceSelectedSignal(Object source, ITmfTrace trace) { - super(source); - fTrace = trace; - } - - /** - * @return The trace referred to by this signal - */ - public ITmfTrace getTrace() { - return fTrace; - } - - @Override - public String toString() { - return "[TmfTraceSelectedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.core.signal; + +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +/** + * A trace was selected + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceSelectedSignal extends TmfSignal { + + private final ITmfTrace fTrace; + + /** + * Constructor + * + * @param source + * Object sending this signal + * @param trace + * The trace that was selected + */ + public TmfTraceSelectedSignal(Object source, ITmfTrace trace) { + super(source); + fTrace = trace; + } + + /** + * @return The trace referred to by this signal + */ + public ITmfTrace getTrace() { + return fTrace; + } + + @Override + public String toString() { + return "[TmfTraceSelectedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java index 2672ec0feb..101e8f3f07 100644 --- a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java +++ b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation - *******************************************************************************/ -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.adaption; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model.EventImpl; - -/** - * Time Graph Presentation Provider Stub. - */ -@SuppressWarnings("nls") -public class TsfImplProvider extends TimeGraphPresentationProvider { - - // ======================================================================== - // Methods - // ======================================================================== - @Override - public int getStateTableIndex(ITimeEvent event) { - return 0; - } - - @Override - public Map getEventHoverToolTipInfo(ITimeEvent revent) { - Map toolTipEventMsgs = new HashMap(); - if (revent instanceof EventImpl) { - toolTipEventMsgs.put("Test Tip1", "Test Value tip1"); - toolTipEventMsgs.put("Test Tip2", "Test Value tip2"); - } - - return toolTipEventMsgs; - } - - @Override - public String getEventName(ITimeEvent event) { - String name = "Unknown"; - if (event instanceof EventImpl) { - EventImpl devent = (EventImpl) event; - name = devent.getType().toString(); - } - return name; - } -} +/******************************************************************************* + * Copyright (c) 2009, 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.adaption; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model.EventImpl; + +/** + * Time Graph Presentation Provider Stub. + */ +@SuppressWarnings("nls") +public class TsfImplProvider extends TimeGraphPresentationProvider { + + // ======================================================================== + // Methods + // ======================================================================== + @Override + public int getStateTableIndex(ITimeEvent event) { + return 0; + } + + @Override + public Map getEventHoverToolTipInfo(ITimeEvent revent) { + Map toolTipEventMsgs = new HashMap(); + if (revent instanceof EventImpl) { + toolTipEventMsgs.put("Test Tip1", "Test Value tip1"); + toolTipEventMsgs.put("Test Tip2", "Test Value tip2"); + } + + return toolTipEventMsgs; + } + + @Override + public String getEventName(ITimeEvent event) { + String name = "Unknown"; + if (event instanceof EventImpl) { + EventImpl devent = (EventImpl) event; + name = devent.getType().toString(); + } + return name; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java index a557620b03..b88f9c90e9 100644 --- a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java +++ b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation - *******************************************************************************/ -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * ITimeEvent implementation for test purposes. - */ -@SuppressWarnings("javadoc") -public class EventImpl implements ITimeEvent { - // ======================================================================== - // Data - // ======================================================================== - public static enum Type {ERROR, WARNING, TIMEADJUSTMENT, ALARM, EVENT, INFORMATION, UNKNOWN, INFO1, INFO2, INFO3, INFO4, INFO5, INFO6, INFO7, INFO8, INFO9} - - private long time = 0; - private ITimeGraphEntry trace = null; - private Type myType = Type.UNKNOWN; - private long duration; - - // ======================================================================== - // Constructor - // ======================================================================== - public EventImpl(long time, ITimeGraphEntry trace, Type type) { - this.time = time; - this.trace = trace; - this.myType = type; - } - - // ======================================================================== - // Methods - // ======================================================================== - public Type getType() { - return myType; - } - - public void setType(Type myType) { - this.myType = myType; - } - - public void setTime(long time) { - this.time = time; - } - - public void setTrace(ITimeGraphEntry trace) { - this.trace = trace; - } - - @Override - public long getTime() { - return time; - } - - @Override - public ITimeGraphEntry getEntry() { - return trace; - } - - /** - * @param duration the duration to set - */ - public void setDuration(long duration) { - this.duration = duration; - } - - /** - * @return the duration - */ - @Override - public long getDuration() { - return duration; - } - -} +/******************************************************************************* + * Copyright (c) 2009, 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * ITimeEvent implementation for test purposes. + */ +@SuppressWarnings("javadoc") +public class EventImpl implements ITimeEvent { + // ======================================================================== + // Data + // ======================================================================== + public static enum Type {ERROR, WARNING, TIMEADJUSTMENT, ALARM, EVENT, INFORMATION, UNKNOWN, INFO1, INFO2, INFO3, INFO4, INFO5, INFO6, INFO7, INFO8, INFO9} + + private long time = 0; + private ITimeGraphEntry trace = null; + private Type myType = Type.UNKNOWN; + private long duration; + + // ======================================================================== + // Constructor + // ======================================================================== + public EventImpl(long time, ITimeGraphEntry trace, Type type) { + this.time = time; + this.trace = trace; + this.myType = type; + } + + // ======================================================================== + // Methods + // ======================================================================== + public Type getType() { + return myType; + } + + public void setType(Type myType) { + this.myType = myType; + } + + public void setTime(long time) { + this.time = time; + } + + public void setTrace(ITimeGraphEntry trace) { + this.trace = trace; + } + + @Override + public long getTime() { + return time; + } + + @Override + public ITimeGraphEntry getEntry() { + return trace; + } + + /** + * @param duration the duration to set + */ + public void setDuration(long duration) { + this.duration = duration; + } + + /** + * @return the duration + */ + @Override + public long getDuration() { + return duration; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceImpl.java b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceImpl.java index 74e0c9fad2..210c5b0c8c 100644 --- a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceImpl.java +++ b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceImpl.java @@ -1,115 +1,115 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation - *******************************************************************************/ -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; - -import java.util.Iterator; -import java.util.Vector; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -@SuppressWarnings({"javadoc", "nls"}) -public class TraceImpl implements ITimeGraphEntry { - // ======================================================================== - // Data - // ======================================================================== - private String name = "traceDefaultName"; - private long startTime = 0; - private long stopTime = 1; - private String className = "defaultClassName"; - private Vector traceEvents = new Vector(); - - // ======================================================================== - // Constructor - // ======================================================================== - - public TraceImpl(String name, long sTime, long stopTime, String className) { - this.name = name; - this.startTime = sTime; - this.stopTime = stopTime; - this.className = className; - } - - // ======================================================================== - // Methods - // ======================================================================== - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public void setName(String name) { - this.name = name; - } - - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - public void setStopTime(long stopTime) { - this.stopTime = stopTime; - } - - @Override - public String getName() { - return name; - } - - @Override - public long getStartTime() { - return startTime; - } - - @Override - public long getEndTime() { - return stopTime; - } - - @Override - public boolean hasTimeEvents() { - return traceEvents != null; - } - - @Override - public Iterator getTimeEventsIterator() { - return traceEvents.iterator(); - } - - @Override - public Iterator getTimeEventsIterator(long aStartTime, long aStopTime, long maxDuration) { - return traceEvents.iterator(); - } - - public void addTraceEvent(ITimeEvent event) { - traceEvents.add(event); - } - - @Override - public ITimeGraphEntry[] getChildren() { - return null; - } - - @Override - public ITimeGraphEntry getParent() { - return null; - } - - @Override - public boolean hasChildren() { - return false; - } - -} +/******************************************************************************* + * Copyright (c) 2009, 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; + +import java.util.Iterator; +import java.util.Vector; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +@SuppressWarnings({"javadoc", "nls"}) +public class TraceImpl implements ITimeGraphEntry { + // ======================================================================== + // Data + // ======================================================================== + private String name = "traceDefaultName"; + private long startTime = 0; + private long stopTime = 1; + private String className = "defaultClassName"; + private Vector traceEvents = new Vector(); + + // ======================================================================== + // Constructor + // ======================================================================== + + public TraceImpl(String name, long sTime, long stopTime, String className) { + this.name = name; + this.startTime = sTime; + this.stopTime = stopTime; + this.className = className; + } + + // ======================================================================== + // Methods + // ======================================================================== + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public void setName(String name) { + this.name = name; + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + public void setStopTime(long stopTime) { + this.stopTime = stopTime; + } + + @Override + public String getName() { + return name; + } + + @Override + public long getStartTime() { + return startTime; + } + + @Override + public long getEndTime() { + return stopTime; + } + + @Override + public boolean hasTimeEvents() { + return traceEvents != null; + } + + @Override + public Iterator getTimeEventsIterator() { + return traceEvents.iterator(); + } + + @Override + public Iterator getTimeEventsIterator(long aStartTime, long aStopTime, long maxDuration) { + return traceEvents.iterator(); + } + + public void addTraceEvent(ITimeEvent event) { + traceEvents.add(event); + } + + @Override + public ITimeGraphEntry[] getChildren() { + return null; + } + + @Override + public ITimeGraphEntry getParent() { + return null; + } + + @Override + public boolean hasChildren() { + return false; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java index b28d75b66b..bbd8877f65 100644 --- a/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java +++ b/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java @@ -1,232 +1,232 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation - *******************************************************************************/ -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; - -import java.util.Date; - -@SuppressWarnings({"javadoc", "nls"}) -public class TraceModelImplFactory { - - // ======================================================================== - // Data - // ======================================================================== - private int count = 0; - private final TraceStrings[] traceNames; - private static final long msTons = 1000000; - private final Long timeRef = new Date().getTime() * msTons; - - // ======================================================================== - // Constructor - // ======================================================================== - public TraceModelImplFactory() { - traceNames = new TraceStrings[17]; - loadTraceNameStrings(); - } - - // ======================================================================== - // Methods - // ======================================================================== - public TraceImpl[] createTraces() { - TraceImpl trace; - TraceImpl[] traceArr = new TraceImpl[17]; - for (int i = 0; i < traceArr.length; i++) { - trace = new TraceImpl(traceNames[i].name, timeRef, timeRef + 40, - traceNames[i].classNmme); - count = i; - createEvents(trace); - traceArr[i] = trace; - } - return traceArr; - } - - /** - * 5000 Events per Trace. - * @param number - * @return - */ - public TraceImpl[] createLargeTraces(int number) { - TraceImpl trace; - TraceImpl[] traceArr = new TraceImpl[number]; - for (int i = 0; i < traceArr.length; i++) { - int counter = i%17; - long sTime = i * (long) 1E6; - trace = new TraceImpl(traceNames[counter].name, sTime , sTime + 20000, - traceNames[counter].classNmme); - create5000Events(trace); - traceArr[i] = trace; - } - return traceArr; - } - - private static void create5000Events(TraceImpl trace) { - EventImpl event; - Long eventTime; - int numEvents = 5000; - long sTime = trace.getStartTime(); - long eTime = trace.getEndTime(); - long duration = (eTime - sTime)/numEvents; - for (int i = 0; i < numEvents; i++) { - eventTime = sTime + (i * duration); - // eventTime = timeRef + (5 * (count % 4) + (5 * (int) (i/2) )); - // System.out.println("Trace: " + trace.getName() + " EventTime: " - // + eventTime); -// duration = i * msTons + (long) ((i % 4)); - - event = new EventImpl(eventTime, trace, getEventType(i%16)); - event.setDuration(duration); - trace.addTraceEvent(event); - } - } - - private void createEvents(TraceImpl trace) { - EventImpl event; - Long eventTime; - int numEvents = 17; - long duration = 0; - for (int i = 0; i < numEvents; i++) { - eventTime = timeRef + msTons * i + (5 * msTons * count) + (5 * i); - duration = msTons + i * msTons + ((i % 4)); -// duration = i + (long) ((i % 4)); - event = new EventImpl(eventTime, trace, getEventType(i)); - event.setDuration(duration); - trace.addTraceEvent(event); - } - } - - private static EventImpl.Type getEventType(int val) { - if (EventImpl.Type.ALARM.ordinal() == val) { - return EventImpl.Type.ALARM; - } - if (EventImpl.Type.ERROR.ordinal() == val) { - return EventImpl.Type.ERROR; - } - if (EventImpl.Type.EVENT.ordinal() == val) { - return EventImpl.Type.EVENT; - } - if (EventImpl.Type.INFORMATION.ordinal() == val) { - return EventImpl.Type.INFORMATION; - } - if (EventImpl.Type.TIMEADJUSTMENT.ordinal() == val) { - return EventImpl.Type.TIMEADJUSTMENT; - } - if (EventImpl.Type.WARNING.ordinal() == val) { - return EventImpl.Type.WARNING; - } - if (EventImpl.Type.INFO1.ordinal() == val) { - return EventImpl.Type.INFO1; - } - if (EventImpl.Type.INFO2.ordinal() == val) { - return EventImpl.Type.INFO2; - } - if (EventImpl.Type.INFO3.ordinal() == val) { - return EventImpl.Type.INFO3; - } - if (EventImpl.Type.INFO4.ordinal() == val) { - return EventImpl.Type.INFO4; - } - if (EventImpl.Type.INFO5.ordinal() == val) { - return EventImpl.Type.INFO5; - } - if (EventImpl.Type.INFO6.ordinal() == val) { - return EventImpl.Type.INFO6; - } - if (EventImpl.Type.INFO7.ordinal() == val) { - return EventImpl.Type.INFO7; - } - if (EventImpl.Type.INFO8.ordinal() == val) { - return EventImpl.Type.INFO8; - } - if (EventImpl.Type.INFO9.ordinal() == val) { - return EventImpl.Type.INFO9; - } - return EventImpl.Type.UNKNOWN; - } - - private void loadTraceNameStrings() { - traceNames[0] = new TraceStrings(); - traceNames[0].name = "TE Log - TATA BSC11"; - traceNames[0].classNmme = "All Boards"; - - traceNames[1] = new TraceStrings(); - traceNames[1].name = "System Log"; - traceNames[1].classNmme = "BSC11"; - - traceNames[2] = new TraceStrings(); - traceNames[2].name = "Alarm Log"; - traceNames[2].classNmme = "BSC11"; - - traceNames[3] = new TraceStrings(); - traceNames[3].name = "Events Log"; - traceNames[3].classNmme = "BSC 11"; - - traceNames[4] = new TraceStrings(); - traceNames[4].name = "CPU Load"; - traceNames[4].classNmme = "All Boards"; - - traceNames[5] = new TraceStrings(); - traceNames[5].name = "Performance Log"; - traceNames[5].classNmme = "BSC11"; - - traceNames[6] = new TraceStrings(); - traceNames[6].name = "TE Log - TATA BSC14"; - traceNames[6].classNmme = "Board 24"; - - traceNames[7] = new TraceStrings(); - traceNames[7].name = "TE Log - TATA BSC14"; - traceNames[7].classNmme = "Board 23"; - - traceNames[8] = new TraceStrings(); - traceNames[8].name = "TE Log - TATA BSC14"; - traceNames[8].classNmme = "Board 11"; - - traceNames[9] = new TraceStrings(); - traceNames[9].name = "TE Log - TATA BSC14"; - traceNames[9].classNmme = "Board 14, SPO"; - - traceNames[10] = new TraceStrings(); - traceNames[10].name = "INFO 1"; - traceNames[10].classNmme = "All Boards"; - - traceNames[11] = new TraceStrings(); - traceNames[11].name = "INFO2"; - traceNames[11].classNmme = "BSC11"; - - traceNames[12] = new TraceStrings(); - traceNames[12].name = "INFO3"; - traceNames[12].classNmme = "Board 24"; - - traceNames[13] = new TraceStrings(); - traceNames[13].name = "MISC1"; - traceNames[13].classNmme = "Board 23"; - - traceNames[14] = new TraceStrings(); - traceNames[14].name = "MISC2"; - traceNames[14].classNmme = "Board 11"; - - traceNames[15] = new TraceStrings(); - traceNames[15].name = "MISC3"; - traceNames[15].classNmme = "Board 23"; - - traceNames[16] = new TraceStrings(); - traceNames[16].name = "MISC4"; - traceNames[16].classNmme = "Board 11"; - - } - - // ======================================================================== - // Inner Class - // ======================================================================== - private static class TraceStrings { - public String name = ""; - public String classNmme = name + " class"; - } -} +/******************************************************************************* + * Copyright (c) 2009, 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon (alvsan09@gmail.com) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model; + +import java.util.Date; + +@SuppressWarnings({"javadoc", "nls"}) +public class TraceModelImplFactory { + + // ======================================================================== + // Data + // ======================================================================== + private int count = 0; + private final TraceStrings[] traceNames; + private static final long msTons = 1000000; + private final Long timeRef = new Date().getTime() * msTons; + + // ======================================================================== + // Constructor + // ======================================================================== + public TraceModelImplFactory() { + traceNames = new TraceStrings[17]; + loadTraceNameStrings(); + } + + // ======================================================================== + // Methods + // ======================================================================== + public TraceImpl[] createTraces() { + TraceImpl trace; + TraceImpl[] traceArr = new TraceImpl[17]; + for (int i = 0; i < traceArr.length; i++) { + trace = new TraceImpl(traceNames[i].name, timeRef, timeRef + 40, + traceNames[i].classNmme); + count = i; + createEvents(trace); + traceArr[i] = trace; + } + return traceArr; + } + + /** + * 5000 Events per Trace. + * @param number + * @return + */ + public TraceImpl[] createLargeTraces(int number) { + TraceImpl trace; + TraceImpl[] traceArr = new TraceImpl[number]; + for (int i = 0; i < traceArr.length; i++) { + int counter = i%17; + long sTime = i * (long) 1E6; + trace = new TraceImpl(traceNames[counter].name, sTime , sTime + 20000, + traceNames[counter].classNmme); + create5000Events(trace); + traceArr[i] = trace; + } + return traceArr; + } + + private static void create5000Events(TraceImpl trace) { + EventImpl event; + Long eventTime; + int numEvents = 5000; + long sTime = trace.getStartTime(); + long eTime = trace.getEndTime(); + long duration = (eTime - sTime)/numEvents; + for (int i = 0; i < numEvents; i++) { + eventTime = sTime + (i * duration); + // eventTime = timeRef + (5 * (count % 4) + (5 * (int) (i/2) )); + // System.out.println("Trace: " + trace.getName() + " EventTime: " + // + eventTime); +// duration = i * msTons + (long) ((i % 4)); + + event = new EventImpl(eventTime, trace, getEventType(i%16)); + event.setDuration(duration); + trace.addTraceEvent(event); + } + } + + private void createEvents(TraceImpl trace) { + EventImpl event; + Long eventTime; + int numEvents = 17; + long duration = 0; + for (int i = 0; i < numEvents; i++) { + eventTime = timeRef + msTons * i + (5 * msTons * count) + (5 * i); + duration = msTons + i * msTons + ((i % 4)); +// duration = i + (long) ((i % 4)); + event = new EventImpl(eventTime, trace, getEventType(i)); + event.setDuration(duration); + trace.addTraceEvent(event); + } + } + + private static EventImpl.Type getEventType(int val) { + if (EventImpl.Type.ALARM.ordinal() == val) { + return EventImpl.Type.ALARM; + } + if (EventImpl.Type.ERROR.ordinal() == val) { + return EventImpl.Type.ERROR; + } + if (EventImpl.Type.EVENT.ordinal() == val) { + return EventImpl.Type.EVENT; + } + if (EventImpl.Type.INFORMATION.ordinal() == val) { + return EventImpl.Type.INFORMATION; + } + if (EventImpl.Type.TIMEADJUSTMENT.ordinal() == val) { + return EventImpl.Type.TIMEADJUSTMENT; + } + if (EventImpl.Type.WARNING.ordinal() == val) { + return EventImpl.Type.WARNING; + } + if (EventImpl.Type.INFO1.ordinal() == val) { + return EventImpl.Type.INFO1; + } + if (EventImpl.Type.INFO2.ordinal() == val) { + return EventImpl.Type.INFO2; + } + if (EventImpl.Type.INFO3.ordinal() == val) { + return EventImpl.Type.INFO3; + } + if (EventImpl.Type.INFO4.ordinal() == val) { + return EventImpl.Type.INFO4; + } + if (EventImpl.Type.INFO5.ordinal() == val) { + return EventImpl.Type.INFO5; + } + if (EventImpl.Type.INFO6.ordinal() == val) { + return EventImpl.Type.INFO6; + } + if (EventImpl.Type.INFO7.ordinal() == val) { + return EventImpl.Type.INFO7; + } + if (EventImpl.Type.INFO8.ordinal() == val) { + return EventImpl.Type.INFO8; + } + if (EventImpl.Type.INFO9.ordinal() == val) { + return EventImpl.Type.INFO9; + } + return EventImpl.Type.UNKNOWN; + } + + private void loadTraceNameStrings() { + traceNames[0] = new TraceStrings(); + traceNames[0].name = "TE Log - TATA BSC11"; + traceNames[0].classNmme = "All Boards"; + + traceNames[1] = new TraceStrings(); + traceNames[1].name = "System Log"; + traceNames[1].classNmme = "BSC11"; + + traceNames[2] = new TraceStrings(); + traceNames[2].name = "Alarm Log"; + traceNames[2].classNmme = "BSC11"; + + traceNames[3] = new TraceStrings(); + traceNames[3].name = "Events Log"; + traceNames[3].classNmme = "BSC 11"; + + traceNames[4] = new TraceStrings(); + traceNames[4].name = "CPU Load"; + traceNames[4].classNmme = "All Boards"; + + traceNames[5] = new TraceStrings(); + traceNames[5].name = "Performance Log"; + traceNames[5].classNmme = "BSC11"; + + traceNames[6] = new TraceStrings(); + traceNames[6].name = "TE Log - TATA BSC14"; + traceNames[6].classNmme = "Board 24"; + + traceNames[7] = new TraceStrings(); + traceNames[7].name = "TE Log - TATA BSC14"; + traceNames[7].classNmme = "Board 23"; + + traceNames[8] = new TraceStrings(); + traceNames[8].name = "TE Log - TATA BSC14"; + traceNames[8].classNmme = "Board 11"; + + traceNames[9] = new TraceStrings(); + traceNames[9].name = "TE Log - TATA BSC14"; + traceNames[9].classNmme = "Board 14, SPO"; + + traceNames[10] = new TraceStrings(); + traceNames[10].name = "INFO 1"; + traceNames[10].classNmme = "All Boards"; + + traceNames[11] = new TraceStrings(); + traceNames[11].name = "INFO2"; + traceNames[11].classNmme = "BSC11"; + + traceNames[12] = new TraceStrings(); + traceNames[12].name = "INFO3"; + traceNames[12].classNmme = "Board 24"; + + traceNames[13] = new TraceStrings(); + traceNames[13].name = "MISC1"; + traceNames[13].classNmme = "Board 23"; + + traceNames[14] = new TraceStrings(); + traceNames[14].name = "MISC2"; + traceNames[14].classNmme = "Board 11"; + + traceNames[15] = new TraceStrings(); + traceNames[15].name = "MISC3"; + traceNames[15].classNmme = "Board 23"; + + traceNames[16] = new TraceStrings(); + traceNames[16].name = "MISC4"; + traceNames[16].classNmme = "Board 11"; + + } + + // ======================================================================== + // Inner Class + // ======================================================================== + private static class TraceStrings { + public String name = ""; + public String classNmme = name + " class"; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/plugin.xml b/org.eclipse.linuxtools.tmf.ui/plugin.xml index 2952adc4ea..12cfe6ba82 100644 --- a/org.eclipse.linuxtools.tmf.ui/plugin.xml +++ b/org.eclipse.linuxtools.tmf.ui/plugin.xml @@ -1,1216 +1,1216 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %project.new.wizard.description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %project.new.wizard.description + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/Messages.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/Messages.java index 1e33a32342..29e10702f3 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/Messages.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/Messages.java @@ -1,264 +1,264 @@ -package org.eclipse.linuxtools.internal.tmf.ui; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.tmf.ui.messages"; //$NON-NLS-1$ - - public static String ManageCustomParsersDialog_DeleteButtonLabel; - public static String ManageCustomParsersDialog_DeleteConfirmation; - public static String ManageCustomParsersDialog_DeleteParserDialogHeader; - public static String ManageCustomParsersDialog_DialogHeader; - public static String ManageCustomParsersDialog_EditButtonLabel; - public static String ManageCustomParsersDialog_ExportButtonLabel; - public static String ManageCustomParsersDialog_ExportParserSelection; - public static String ManageCustomParsersDialog_ImportButtonLabel; - public static String ManageCustomParsersDialog_ImportParserSelection; - public static String ManageCustomParsersDialog_NewButtonLabel; - public static String ManageCustomParsersDialog_ParseButtonLabel; - public static String ManageCustomParsersDialog_ParseError; - public static String ManageCustomParsersDialog_TextButtonLabel; - public static String ManageCustomParsersDialog_TraceSelection; - - public static String CustomTraceDefinition_messageTag; - public static String CustomTraceDefinition_otherTag; - public static String CustomTraceDefinition_timestampTag; - public static String CustomTxtTraceDefinition_action; - public static String CustomTxtTraceDefinition_cardinality; - public static String CustomTxtTraceDefinition_definition; - public static String CustomTxtTraceDefinition_definitionRootElement; - public static String CustomTxtTraceDefinition_format; - public static String CustomTxtTraceDefinition_inputData; - public static String CustomTxtTraceDefinition_inputLine; - public static String CustomTxtTraceDefinition_max; - public static String CustomTxtTraceDefinition_min; - public static String CustomTxtTraceDefinition_name; - public static String CustomTxtTraceDefinition_outputColumn; - public static String CustomTxtTraceDefinition_regEx; - public static String CustomTxtTraceDefinition_timestampOutputFormat; - public static String CustomXmlTraceDefinition_action; - public static String CustomXmlTraceDefinition_attribute; - public static String CustomXmlTraceDefinition_definition; - public static String CustomXmlTraceDefinition_definitionRootElement; - public static String CustomXmlTraceDefinition_format; - public static String CustomXmlTraceDefinition_ignoreTag; - public static String CustomXmlTraceDefinition_inputData; - public static String CustomXmlTraceDefinition_inputElement; - public static String CustomXmlTraceDefinition_logEntry; - public static String CustomXmlTraceDefinition_name; - public static String CustomXmlTraceDefinition_outputColumn; - public static String CustomXmlTraceDefinition_timestampOutputFormat; - - public static String TmfEventsTable_AddBookmarkActionText; - public static String TmfEventsTable_AddBookmarkDialogText; - public static String TmfEventsTable_AddBookmarkDialogTitle; - public static String TmfEventsTable_ApplyPresetFilterMenuName; - public static String TmfEventsTable_ClearFiltersActionText; - public static String TmfEventsTable_ContentColumnHeader; - public static String TmfEventsTable_FilterHint; - public static String TmfEventsTable_HideRawActionText; - public static String TmfEventsTable_HideTableActionText; - public static String TmfEventsTable_ReferenceColumnHeader; - public static String TmfEventsTable_RemoveBookmarkActionText; - public static String TmfEventsTable_SearchHint; - public static String TmfEventsTable_SearchingJobName; - public static String TmfEventsTable_ShowFilterBarActionText; - public static String TmfEventsTable_ShowRawActionText; - public static String TmfEventsTable_ShowSearchBarActionText; - public static String TmfEventsTable_ShowTableActionText; - public static String TmfEventsTable_SourceColumnHeader; - public static String TmfEventsTable_TimestampColumnHeader; - public static String TmfEventsTable_TypeColumnHeader; - - public static String TmfTimeFilterDialog_EDIT_PROFILING_OPTIONS; - public static String TmfTimeFilterDialog_TRACE_FILTER; - public static String TmfTimeFilterDialog_TRACE_FILTER_DESC; - public static String TmfTimeFilterDialog_TRACE_ID; - public static String TmfTimeFilterDialog_TRACE_NAME; - public static String TmfTimeLegend_LEGEND; - public static String TmfTimeLegend_TRACE_STATES; - public static String TmfTimeLegend_TRACE_STATES_TITLE; - public static String TmfTimeLegend_WINDOW_TITLE; - public static String TmfTimeLegend_StateTypeName; - - public static String TmfTimeTipHandler_DURATION; - public static String TmfTimeTipHandler_TRACE_DATE; - public static String TmfTimeTipHandler_TRACE_EVENT_TIME; - public static String TmfTimeTipHandler_TRACE_START_TIME; - public static String TmfTimeTipHandler_TRACE_STATE; - public static String TmfTimeTipHandler_TRACE_STOP_TIME; - - public static String TmfTimeGraphViewer_ResetScaleActionNameText; - public static String TmfTimeGraphViewer_ResetScaleActionToolTipText; - public static String TmfTimeGraphViewer_LegendActionNameText; - public static String TmfTimeGraphViewer_LegendActionToolTipText; - public static String TmfTimeGraphViewer_NextEventActionNameText; - public static String TmfTimeGraphViewer_NextEventActionToolTipText; - public static String TmfTimeGraphViewer_PreviousEventActionNameText; - public static String TmfTimeGraphViewer_PreviousEventActionToolTipText; - public static String TmfTimeGraphViewer_NextItemActionNameText; - public static String TmfTimeGraphViewer_NextItemActionToolTipText; - public static String TmfTimeGraphViewer_PreviousItemActionNameText; - public static String TmfTimeGraphViewer_PreviousItemActionToolTipText; - public static String TmfTimeGraphViewer_ZoomInActionNameText; - public static String TmfTimeGraphViewer_ZoomInActionToolTipText; - public static String TmfTimeGraphViewer_ZoomOutActionNameText; - public static String TmfTimeGraphViewer_ZoomOutActionToolTipText; - - public static String ColorsView_AddActionToolTipText; - public static String ColorsView_BackgroundButtonText; - public static String ColorsView_BackgroundDialogText; - public static String ColorsView_DeleteActionToolTipText; - public static String ColorsView_ExportActionToolTipText; - public static String ColorsView_FilterButtonText; - public static String ColorsView_ForegroundButtonText; - public static String ColorsView_ForegroundDialogText; - public static String ColorsView_ImportActionToolTipText; - public static String ColorsView_ImportOverwriteDialogMessage1; - public static String ColorsView_ImportOverwriteDialogMessage2; - public static String ColorsView_ImportOverwriteDialogTitle; - public static String ColorsView_MoveDownActionToolTipText; - public static String ColorsView_MoveUpActionToolTipText; - public static String ColorsView_TickButtonText; - public static String TickColorDialog_TickColorDialogTitle; - - public static String CustomTxtParserInputWizardPage_addChildLine; - public static String CustomTxtParserInputWizardPage_addGroup; - public static String CustomTxtParserInputWizardPage_addNextLine; - public static String CustomTxtParserInputWizardPage_append; - public static String CustomTxtParserInputWizardPage_appendWith; - public static String CustomTxtParserInputWizardPage_capturedGroup; - public static String CustomTxtParserInputWizardPage_cardinality; - public static String CustomTxtParserInputWizardPage_dateFormatHelp; - public static String CustomTxtParserInputWizardPage_desccriptionEdit; - public static String CustomTxtParserInputWizardPage_descriptionNew; - public static String CustomTxtParserInputWizardPage_format; - public static String CustomTxtParserInputWizardPage_group; - public static String CustomTxtParserInputWizardPage_highlightAll; - public static String CustomTxtParserInputWizardPage_logType; - public static String CustomTxtParserInputWizardPage_matchingLineRoot; - public static String CustomTxtParserInputWizardPage_matchingOtherLine; - public static String CustomTxtParserInputWizardPage_matchingRootLine; - public static String CustomTxtParserInputWizardPage_max; - public static String CustomTxtParserInputWizardPage_min; - public static String CustomTxtParserInputWizardPage_moveDown; - public static String CustomTxtParserInputWizardPage_moveUp; - public static String CustomTxtParserInputWizardPage_name; - public static String CustomTxtParserInputWizardPage_newGroup; - public static String CustomTxtParserInputWizardPage_noMatch; - public static String CustomTxtParserInputWizardPage_noMatchingGroup; - public static String CustomTxtParserInputWizardPage_noMatchingLine; - public static String CustomTxtParserInputWizardPage_noMatchingTimestamp; - public static String CustomTxtParserInputWizardPage_noMathcingLine; - public static String CustomTxtParserInputWizardPage_nonMatchingLine; - public static String CustomTxtParserInputWizardPage_noTimestampGroup; - public static String CustomTxtParserInputWizardPage_preview; - public static String CustomTxtParserInputWizardPage_previewInput; - public static String CustomTxtParserInputWizardPage_previewLegend; - public static String CustomTxtParserInputWizardPage_regularExpression; - public static String CustomTxtParserInputWizardPage_regularExpressionHelp; - public static String CustomTxtParserInputWizardPage_removeGroup; - public static String CustomTxtParserInputWizardPage_removeLine; - public static String CustomTxtParserInputWizardPage_set; - public static String CustomTxtParserInputWizardPage_timestampFormat; - public static String CustomTxtParserInputWizardPage_uncapturedText; - public static String CustomTxtParserInputWizardPage_unidentifiedCaptureGroup; - public static String CustomTxtParserInputWizardPage_windowTitleEdit; - public static String CustomTxtParserInputWizardPage_windowTitleNew; - public static String CustomTxtParserOutputWizardPage_description; - public static String CustomTxtParserOutputWizardPage_moveAfter; - public static String CustomTxtParserOutputWizardPage_moveBefore; - public static String CustomTxtParserOutputWizardPage_visible; - public static String CustomXmlParserInputWizardPage_emptyLogTypeError; - public static String CustomXmlParserInputWizardPage_duplicatelogTypeError; - public static String CustomXmlParserInputWizardPage_noDocumentError; - public static String CustomXmlParserInputWizardPage_missingLogEntryError; - public static String CustomXmlParserInputWizardPage_missingTimestampFmtError; - public static String CustomXmlParserInputWizardPage_invalidTimestampFmtError; - public static String CustomXmlParserInputWizardPage_notimestamporAttributeError; - public static String CustomXmlParserInputWizardPage_missingDocumentElementError; - public static String CustomXmlParserInputWizardPage_timestampFormatPrompt; - public static String CustomXmlParserInputWizardPage_timestampElementPrompt; - public static String CustomXmlParserInputWizardPage_missingInputElementNameError; - public static String CustomXmlParserInputWizardPage_attributePrompt; - public static String CustomXmlParserInputWizardPage_missingAttribute; - public static String CustomXmlParserInputWizardPage_duplicateAttributeError; - public static String CustomXmlParserInputWizardPage_missingTimestampInFmtError; - public static String CustomXmlParserInputWizardPage_invalidTimestampInFmtError; - public static String CustomXmlParserInputWizardPage_missingDataGroupNameError; - public static String CustomXmlParserInputWizardPage_missingElementNameError; - public static String CustomXmlParserInputWizardPage_duplicateElementNameError; - public static String CustomXmlParserInputWizardPage_addAttribute; - public static String CustomXmlParserInputWizardPage_addChildElement; - public static String CustomXmlParserInputWizardPage_addDocumentEleemnt; - public static String CustomXmlParserInputWizardPage_addDocumentElement; - public static String CustomXmlParserInputWizardPage_addNextElement; - public static String CustomXmlParserInputWizardPage_append; - public static String CustomXmlParserInputWizardPage_appendWith; - public static String CustomXmlParserInputWizardPage_attibute; - public static String CustomXmlParserInputWizardPage_dateFormatHelp; - public static String CustomXmlParserInputWizardPage_descriptionEdit; - public static String CustomXmlParserInputWizardPage_descriptionNew; - public static String CustomXmlParserInputWizardPage_elementName; - public static String CustomXmlParserInputWizardPage_feelingLucky; - public static String CustomXmlParserInputWizardPage_format; - public static String CustomXmlParserInputWizardPage_logEntry; - public static String CustomXmlParserInputWizardPage_logType; - public static String CustomXmlParserInputWizardPage_moveDown; - public static String CustomXmlParserInputWizardPage_moveUp; - public static String CustomXmlParserInputWizardPage_name; - public static String CustomXmlParserInputWizardPage_newAttibute; - public static String CustomXmlParserInputWizardPage_noMatchingAttribute; - public static String CustomXmlParserInputWizardPage_noMatch; - public static String CustomXmlParserInputWizardPage_noMatchingElement; - public static String CustomXmlParserInputWizardPage_preview; - public static String CustomXmlParserInputWizardPage_previewInput; - public static String CustomXmlParserInputWizardPage_removeAttribute; - public static String CustomXmlParserInputWizardPage_removeElement; - public static String CustomXmlParserInputWizardPage_set; - public static String CustomXmlParserInputWizardPage_tagName; - public static String CustomXmlParserInputWizardPage_timestampFormat; - public static String CustomXmlParserInputWizardPage_titleEdit; - public static String CustomXmlParserInputWizardPage_titleNew; - public static String CustomXmlParserOutputWizardPage_description; - public static String CustomXmlParserOutputWizardPage_moveAfter; - public static String CustomXmlParserOutputWizardPage_moveBefore; - public static String CustomXmlParserOutputWizardPage_visible; - - public static String FilterDialog_FilterDialogTitle; - public static String FilterView_AddActionToolTipText; - public static String FilterView_DeleteActionToolTipText; - public static String FilterView_ExportActionToolTipText; - public static String FilterView_FileDialogFilterName; - public static String FilterView_ImportActionToolTipText; - public static String FilterView_SaveActionToolTipText; - public static String FilterViewer_EmptyTreeHintText; - public static String FilterViewer_CommonCategory; - public static String FilterViewer_AlphaButtonText; - public static String FilterViewer_DeleteActionText; - public static String FilterViewer_FieldLabel; - public static String FilterViewer_FilterNameHint; - public static String FilterViewer_IgnoreCaseButtonText; - public static String FilterViewer_NameLabel; - public static String FilterViewer_NewPrefix; - public static String FilterViewer_NotLabel; - public static String FilterViewer_NumButtonText; - public static String FilterViewer_RegexHint; - public static String FilterViewer_RegexLabel; - public static String FilterViewer_ResultLabel; - public static String FilterViewer_TimestampButtonText; - public static String FilterViewer_TypeLabel; - public static String FilterViewer_ValueHint; - public static String FilterViewer_ValueLabel; - - public static String TmfView_PinActionNameText; - public static String TmfView_PinActionToolTipText; - - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - } -} +package org.eclipse.linuxtools.internal.tmf.ui; + +import org.eclipse.osgi.util.NLS; + +public class Messages extends NLS { + private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.tmf.ui.messages"; //$NON-NLS-1$ + + public static String ManageCustomParsersDialog_DeleteButtonLabel; + public static String ManageCustomParsersDialog_DeleteConfirmation; + public static String ManageCustomParsersDialog_DeleteParserDialogHeader; + public static String ManageCustomParsersDialog_DialogHeader; + public static String ManageCustomParsersDialog_EditButtonLabel; + public static String ManageCustomParsersDialog_ExportButtonLabel; + public static String ManageCustomParsersDialog_ExportParserSelection; + public static String ManageCustomParsersDialog_ImportButtonLabel; + public static String ManageCustomParsersDialog_ImportParserSelection; + public static String ManageCustomParsersDialog_NewButtonLabel; + public static String ManageCustomParsersDialog_ParseButtonLabel; + public static String ManageCustomParsersDialog_ParseError; + public static String ManageCustomParsersDialog_TextButtonLabel; + public static String ManageCustomParsersDialog_TraceSelection; + + public static String CustomTraceDefinition_messageTag; + public static String CustomTraceDefinition_otherTag; + public static String CustomTraceDefinition_timestampTag; + public static String CustomTxtTraceDefinition_action; + public static String CustomTxtTraceDefinition_cardinality; + public static String CustomTxtTraceDefinition_definition; + public static String CustomTxtTraceDefinition_definitionRootElement; + public static String CustomTxtTraceDefinition_format; + public static String CustomTxtTraceDefinition_inputData; + public static String CustomTxtTraceDefinition_inputLine; + public static String CustomTxtTraceDefinition_max; + public static String CustomTxtTraceDefinition_min; + public static String CustomTxtTraceDefinition_name; + public static String CustomTxtTraceDefinition_outputColumn; + public static String CustomTxtTraceDefinition_regEx; + public static String CustomTxtTraceDefinition_timestampOutputFormat; + public static String CustomXmlTraceDefinition_action; + public static String CustomXmlTraceDefinition_attribute; + public static String CustomXmlTraceDefinition_definition; + public static String CustomXmlTraceDefinition_definitionRootElement; + public static String CustomXmlTraceDefinition_format; + public static String CustomXmlTraceDefinition_ignoreTag; + public static String CustomXmlTraceDefinition_inputData; + public static String CustomXmlTraceDefinition_inputElement; + public static String CustomXmlTraceDefinition_logEntry; + public static String CustomXmlTraceDefinition_name; + public static String CustomXmlTraceDefinition_outputColumn; + public static String CustomXmlTraceDefinition_timestampOutputFormat; + + public static String TmfEventsTable_AddBookmarkActionText; + public static String TmfEventsTable_AddBookmarkDialogText; + public static String TmfEventsTable_AddBookmarkDialogTitle; + public static String TmfEventsTable_ApplyPresetFilterMenuName; + public static String TmfEventsTable_ClearFiltersActionText; + public static String TmfEventsTable_ContentColumnHeader; + public static String TmfEventsTable_FilterHint; + public static String TmfEventsTable_HideRawActionText; + public static String TmfEventsTable_HideTableActionText; + public static String TmfEventsTable_ReferenceColumnHeader; + public static String TmfEventsTable_RemoveBookmarkActionText; + public static String TmfEventsTable_SearchHint; + public static String TmfEventsTable_SearchingJobName; + public static String TmfEventsTable_ShowFilterBarActionText; + public static String TmfEventsTable_ShowRawActionText; + public static String TmfEventsTable_ShowSearchBarActionText; + public static String TmfEventsTable_ShowTableActionText; + public static String TmfEventsTable_SourceColumnHeader; + public static String TmfEventsTable_TimestampColumnHeader; + public static String TmfEventsTable_TypeColumnHeader; + + public static String TmfTimeFilterDialog_EDIT_PROFILING_OPTIONS; + public static String TmfTimeFilterDialog_TRACE_FILTER; + public static String TmfTimeFilterDialog_TRACE_FILTER_DESC; + public static String TmfTimeFilterDialog_TRACE_ID; + public static String TmfTimeFilterDialog_TRACE_NAME; + public static String TmfTimeLegend_LEGEND; + public static String TmfTimeLegend_TRACE_STATES; + public static String TmfTimeLegend_TRACE_STATES_TITLE; + public static String TmfTimeLegend_WINDOW_TITLE; + public static String TmfTimeLegend_StateTypeName; + + public static String TmfTimeTipHandler_DURATION; + public static String TmfTimeTipHandler_TRACE_DATE; + public static String TmfTimeTipHandler_TRACE_EVENT_TIME; + public static String TmfTimeTipHandler_TRACE_START_TIME; + public static String TmfTimeTipHandler_TRACE_STATE; + public static String TmfTimeTipHandler_TRACE_STOP_TIME; + + public static String TmfTimeGraphViewer_ResetScaleActionNameText; + public static String TmfTimeGraphViewer_ResetScaleActionToolTipText; + public static String TmfTimeGraphViewer_LegendActionNameText; + public static String TmfTimeGraphViewer_LegendActionToolTipText; + public static String TmfTimeGraphViewer_NextEventActionNameText; + public static String TmfTimeGraphViewer_NextEventActionToolTipText; + public static String TmfTimeGraphViewer_PreviousEventActionNameText; + public static String TmfTimeGraphViewer_PreviousEventActionToolTipText; + public static String TmfTimeGraphViewer_NextItemActionNameText; + public static String TmfTimeGraphViewer_NextItemActionToolTipText; + public static String TmfTimeGraphViewer_PreviousItemActionNameText; + public static String TmfTimeGraphViewer_PreviousItemActionToolTipText; + public static String TmfTimeGraphViewer_ZoomInActionNameText; + public static String TmfTimeGraphViewer_ZoomInActionToolTipText; + public static String TmfTimeGraphViewer_ZoomOutActionNameText; + public static String TmfTimeGraphViewer_ZoomOutActionToolTipText; + + public static String ColorsView_AddActionToolTipText; + public static String ColorsView_BackgroundButtonText; + public static String ColorsView_BackgroundDialogText; + public static String ColorsView_DeleteActionToolTipText; + public static String ColorsView_ExportActionToolTipText; + public static String ColorsView_FilterButtonText; + public static String ColorsView_ForegroundButtonText; + public static String ColorsView_ForegroundDialogText; + public static String ColorsView_ImportActionToolTipText; + public static String ColorsView_ImportOverwriteDialogMessage1; + public static String ColorsView_ImportOverwriteDialogMessage2; + public static String ColorsView_ImportOverwriteDialogTitle; + public static String ColorsView_MoveDownActionToolTipText; + public static String ColorsView_MoveUpActionToolTipText; + public static String ColorsView_TickButtonText; + public static String TickColorDialog_TickColorDialogTitle; + + public static String CustomTxtParserInputWizardPage_addChildLine; + public static String CustomTxtParserInputWizardPage_addGroup; + public static String CustomTxtParserInputWizardPage_addNextLine; + public static String CustomTxtParserInputWizardPage_append; + public static String CustomTxtParserInputWizardPage_appendWith; + public static String CustomTxtParserInputWizardPage_capturedGroup; + public static String CustomTxtParserInputWizardPage_cardinality; + public static String CustomTxtParserInputWizardPage_dateFormatHelp; + public static String CustomTxtParserInputWizardPage_desccriptionEdit; + public static String CustomTxtParserInputWizardPage_descriptionNew; + public static String CustomTxtParserInputWizardPage_format; + public static String CustomTxtParserInputWizardPage_group; + public static String CustomTxtParserInputWizardPage_highlightAll; + public static String CustomTxtParserInputWizardPage_logType; + public static String CustomTxtParserInputWizardPage_matchingLineRoot; + public static String CustomTxtParserInputWizardPage_matchingOtherLine; + public static String CustomTxtParserInputWizardPage_matchingRootLine; + public static String CustomTxtParserInputWizardPage_max; + public static String CustomTxtParserInputWizardPage_min; + public static String CustomTxtParserInputWizardPage_moveDown; + public static String CustomTxtParserInputWizardPage_moveUp; + public static String CustomTxtParserInputWizardPage_name; + public static String CustomTxtParserInputWizardPage_newGroup; + public static String CustomTxtParserInputWizardPage_noMatch; + public static String CustomTxtParserInputWizardPage_noMatchingGroup; + public static String CustomTxtParserInputWizardPage_noMatchingLine; + public static String CustomTxtParserInputWizardPage_noMatchingTimestamp; + public static String CustomTxtParserInputWizardPage_noMathcingLine; + public static String CustomTxtParserInputWizardPage_nonMatchingLine; + public static String CustomTxtParserInputWizardPage_noTimestampGroup; + public static String CustomTxtParserInputWizardPage_preview; + public static String CustomTxtParserInputWizardPage_previewInput; + public static String CustomTxtParserInputWizardPage_previewLegend; + public static String CustomTxtParserInputWizardPage_regularExpression; + public static String CustomTxtParserInputWizardPage_regularExpressionHelp; + public static String CustomTxtParserInputWizardPage_removeGroup; + public static String CustomTxtParserInputWizardPage_removeLine; + public static String CustomTxtParserInputWizardPage_set; + public static String CustomTxtParserInputWizardPage_timestampFormat; + public static String CustomTxtParserInputWizardPage_uncapturedText; + public static String CustomTxtParserInputWizardPage_unidentifiedCaptureGroup; + public static String CustomTxtParserInputWizardPage_windowTitleEdit; + public static String CustomTxtParserInputWizardPage_windowTitleNew; + public static String CustomTxtParserOutputWizardPage_description; + public static String CustomTxtParserOutputWizardPage_moveAfter; + public static String CustomTxtParserOutputWizardPage_moveBefore; + public static String CustomTxtParserOutputWizardPage_visible; + public static String CustomXmlParserInputWizardPage_emptyLogTypeError; + public static String CustomXmlParserInputWizardPage_duplicatelogTypeError; + public static String CustomXmlParserInputWizardPage_noDocumentError; + public static String CustomXmlParserInputWizardPage_missingLogEntryError; + public static String CustomXmlParserInputWizardPage_missingTimestampFmtError; + public static String CustomXmlParserInputWizardPage_invalidTimestampFmtError; + public static String CustomXmlParserInputWizardPage_notimestamporAttributeError; + public static String CustomXmlParserInputWizardPage_missingDocumentElementError; + public static String CustomXmlParserInputWizardPage_timestampFormatPrompt; + public static String CustomXmlParserInputWizardPage_timestampElementPrompt; + public static String CustomXmlParserInputWizardPage_missingInputElementNameError; + public static String CustomXmlParserInputWizardPage_attributePrompt; + public static String CustomXmlParserInputWizardPage_missingAttribute; + public static String CustomXmlParserInputWizardPage_duplicateAttributeError; + public static String CustomXmlParserInputWizardPage_missingTimestampInFmtError; + public static String CustomXmlParserInputWizardPage_invalidTimestampInFmtError; + public static String CustomXmlParserInputWizardPage_missingDataGroupNameError; + public static String CustomXmlParserInputWizardPage_missingElementNameError; + public static String CustomXmlParserInputWizardPage_duplicateElementNameError; + public static String CustomXmlParserInputWizardPage_addAttribute; + public static String CustomXmlParserInputWizardPage_addChildElement; + public static String CustomXmlParserInputWizardPage_addDocumentEleemnt; + public static String CustomXmlParserInputWizardPage_addDocumentElement; + public static String CustomXmlParserInputWizardPage_addNextElement; + public static String CustomXmlParserInputWizardPage_append; + public static String CustomXmlParserInputWizardPage_appendWith; + public static String CustomXmlParserInputWizardPage_attibute; + public static String CustomXmlParserInputWizardPage_dateFormatHelp; + public static String CustomXmlParserInputWizardPage_descriptionEdit; + public static String CustomXmlParserInputWizardPage_descriptionNew; + public static String CustomXmlParserInputWizardPage_elementName; + public static String CustomXmlParserInputWizardPage_feelingLucky; + public static String CustomXmlParserInputWizardPage_format; + public static String CustomXmlParserInputWizardPage_logEntry; + public static String CustomXmlParserInputWizardPage_logType; + public static String CustomXmlParserInputWizardPage_moveDown; + public static String CustomXmlParserInputWizardPage_moveUp; + public static String CustomXmlParserInputWizardPage_name; + public static String CustomXmlParserInputWizardPage_newAttibute; + public static String CustomXmlParserInputWizardPage_noMatchingAttribute; + public static String CustomXmlParserInputWizardPage_noMatch; + public static String CustomXmlParserInputWizardPage_noMatchingElement; + public static String CustomXmlParserInputWizardPage_preview; + public static String CustomXmlParserInputWizardPage_previewInput; + public static String CustomXmlParserInputWizardPage_removeAttribute; + public static String CustomXmlParserInputWizardPage_removeElement; + public static String CustomXmlParserInputWizardPage_set; + public static String CustomXmlParserInputWizardPage_tagName; + public static String CustomXmlParserInputWizardPage_timestampFormat; + public static String CustomXmlParserInputWizardPage_titleEdit; + public static String CustomXmlParserInputWizardPage_titleNew; + public static String CustomXmlParserOutputWizardPage_description; + public static String CustomXmlParserOutputWizardPage_moveAfter; + public static String CustomXmlParserOutputWizardPage_moveBefore; + public static String CustomXmlParserOutputWizardPage_visible; + + public static String FilterDialog_FilterDialogTitle; + public static String FilterView_AddActionToolTipText; + public static String FilterView_DeleteActionToolTipText; + public static String FilterView_ExportActionToolTipText; + public static String FilterView_FileDialogFilterName; + public static String FilterView_ImportActionToolTipText; + public static String FilterView_SaveActionToolTipText; + public static String FilterViewer_EmptyTreeHintText; + public static String FilterViewer_CommonCategory; + public static String FilterViewer_AlphaButtonText; + public static String FilterViewer_DeleteActionText; + public static String FilterViewer_FieldLabel; + public static String FilterViewer_FilterNameHint; + public static String FilterViewer_IgnoreCaseButtonText; + public static String FilterViewer_NameLabel; + public static String FilterViewer_NewPrefix; + public static String FilterViewer_NotLabel; + public static String FilterViewer_NumButtonText; + public static String FilterViewer_RegexHint; + public static String FilterViewer_RegexLabel; + public static String FilterViewer_ResultLabel; + public static String FilterViewer_TimestampButtonText; + public static String FilterViewer_TypeLabel; + public static String FilterViewer_ValueHint; + public static String FilterViewer_ValueLabel; + + public static String TmfView_PinActionNameText; + public static String TmfView_PinActionToolTipText; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/TmfUiTracer.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/TmfUiTracer.java index 35ab206ef5..ac123c2225 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/TmfUiTracer.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/TmfUiTracer.java @@ -1,164 +1,164 @@ -package org.eclipse.linuxtools.internal.tmf.ui; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; - -import org.eclipse.core.runtime.Platform; - -@SuppressWarnings("nls") -public class TmfUiTracer { - - private static String pluginID = Activator.PLUGIN_ID; - - static Boolean ERROR = Boolean.FALSE; - static Boolean WARNING = Boolean.FALSE; - static Boolean INFO = Boolean.FALSE; - - static Boolean INDEX = Boolean.FALSE; - static Boolean DISPLAY = Boolean.FALSE; - static Boolean SORTING = Boolean.FALSE; - - private static String LOGNAME = "traceUI.log"; - private static BufferedWriter fTraceLog = null; - - private static BufferedWriter openLogFile(String filename) { - BufferedWriter outfile = null; - try { - outfile = new BufferedWriter(new FileWriter(filename)); - } catch (IOException e) { - Activator.getDefault().logError("Error creating log file " + LOGNAME, e); //$NON-NLS-1$ - } - return outfile; - } - - public static void init() { - - String traceKey; - boolean isTracing = false; - - traceKey = Platform.getDebugOption(pluginID + "/error"); - if (traceKey != null) { - ERROR = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= ERROR; - } - - traceKey = Platform.getDebugOption(pluginID + "/warning"); - if (traceKey != null) { - WARNING = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= WARNING; - } - - traceKey = Platform.getDebugOption(pluginID + "/info"); - if (traceKey != null) { - INFO = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= INFO; - } - - traceKey = Platform.getDebugOption(pluginID + "/updateindex"); - if (traceKey != null) { - INDEX = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= INDEX; - } - - traceKey = Platform.getDebugOption(pluginID + "/display"); - if (traceKey != null) { - DISPLAY = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= DISPLAY; - } - - traceKey = Platform.getDebugOption(pluginID + "/sorting"); - if (traceKey != null) { - SORTING = (Boolean.valueOf(traceKey)).booleanValue(); - isTracing |= SORTING; - } - - // Create trace log file if needed - if (isTracing) { - fTraceLog = openLogFile(LOGNAME); - } - } - - public static void stop() { - if (fTraceLog == null) - return; - - try { - fTraceLog.close(); - fTraceLog = null; - } catch (IOException e) { - Activator.getDefault().logError("Error closing log file " + LOGNAME, e); //$NON-NLS-1$ - } - } - - // Predicates - public static boolean isErrorTraced() { - return ERROR; - } - - public static boolean isIndexTraced() { - return INDEX; - } - - public static boolean isDisplayTraced() { - return DISPLAY; - } - - public static boolean isSortingTraced() { - return SORTING; - } - - // Tracers - public static void trace(String msg) { - long currentTime = System.currentTimeMillis(); - StringBuilder message = new StringBuilder("["); - message.append(currentTime / 1000); - message.append("."); - message.append(String.format("%1$03d", currentTime % 1000)); - message.append("] "); - message.append(msg); - - if (fTraceLog != null) { - try { - fTraceLog.write(message.toString()); - fTraceLog.newLine(); - fTraceLog.flush(); - } catch (IOException e) { - Activator.getDefault().logError("Error writing to log file " + LOGNAME, e); //$NON-NLS-1$ - } - } - } - - public static void traceIndex(String msg) { - String message = ("[INDEX] " + msg); - trace(message); - } - - public static void traceDisplay(String msg) { - String message = ("[DISPLAY]" + msg); - trace(message); - } - - public static void traceSorting(String msg) { - String message = ("[SORT] " + msg); - trace(message); - } - - public static void traceError(String msg) { - String message = ("[ERR] Thread=" + Thread.currentThread().getId() + " " + msg); - trace(message); - } - - public static void traceWarning(String msg) { - String message = ("[WARN] Thread=" + Thread.currentThread().getId() + " " + msg); - trace(message); - } - - public static void traceInfo(String msg) { - String message = ("[INF] Thread=" + Thread.currentThread().getId() + " " + msg); - trace(message); - } - - - -} +package org.eclipse.linuxtools.internal.tmf.ui; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; + +import org.eclipse.core.runtime.Platform; + +@SuppressWarnings("nls") +public class TmfUiTracer { + + private static String pluginID = Activator.PLUGIN_ID; + + static Boolean ERROR = Boolean.FALSE; + static Boolean WARNING = Boolean.FALSE; + static Boolean INFO = Boolean.FALSE; + + static Boolean INDEX = Boolean.FALSE; + static Boolean DISPLAY = Boolean.FALSE; + static Boolean SORTING = Boolean.FALSE; + + private static String LOGNAME = "traceUI.log"; + private static BufferedWriter fTraceLog = null; + + private static BufferedWriter openLogFile(String filename) { + BufferedWriter outfile = null; + try { + outfile = new BufferedWriter(new FileWriter(filename)); + } catch (IOException e) { + Activator.getDefault().logError("Error creating log file " + LOGNAME, e); //$NON-NLS-1$ + } + return outfile; + } + + public static void init() { + + String traceKey; + boolean isTracing = false; + + traceKey = Platform.getDebugOption(pluginID + "/error"); + if (traceKey != null) { + ERROR = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= ERROR; + } + + traceKey = Platform.getDebugOption(pluginID + "/warning"); + if (traceKey != null) { + WARNING = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= WARNING; + } + + traceKey = Platform.getDebugOption(pluginID + "/info"); + if (traceKey != null) { + INFO = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= INFO; + } + + traceKey = Platform.getDebugOption(pluginID + "/updateindex"); + if (traceKey != null) { + INDEX = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= INDEX; + } + + traceKey = Platform.getDebugOption(pluginID + "/display"); + if (traceKey != null) { + DISPLAY = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= DISPLAY; + } + + traceKey = Platform.getDebugOption(pluginID + "/sorting"); + if (traceKey != null) { + SORTING = (Boolean.valueOf(traceKey)).booleanValue(); + isTracing |= SORTING; + } + + // Create trace log file if needed + if (isTracing) { + fTraceLog = openLogFile(LOGNAME); + } + } + + public static void stop() { + if (fTraceLog == null) + return; + + try { + fTraceLog.close(); + fTraceLog = null; + } catch (IOException e) { + Activator.getDefault().logError("Error closing log file " + LOGNAME, e); //$NON-NLS-1$ + } + } + + // Predicates + public static boolean isErrorTraced() { + return ERROR; + } + + public static boolean isIndexTraced() { + return INDEX; + } + + public static boolean isDisplayTraced() { + return DISPLAY; + } + + public static boolean isSortingTraced() { + return SORTING; + } + + // Tracers + public static void trace(String msg) { + long currentTime = System.currentTimeMillis(); + StringBuilder message = new StringBuilder("["); + message.append(currentTime / 1000); + message.append("."); + message.append(String.format("%1$03d", currentTime % 1000)); + message.append("] "); + message.append(msg); + + if (fTraceLog != null) { + try { + fTraceLog.write(message.toString()); + fTraceLog.newLine(); + fTraceLog.flush(); + } catch (IOException e) { + Activator.getDefault().logError("Error writing to log file " + LOGNAME, e); //$NON-NLS-1$ + } + } + } + + public static void traceIndex(String msg) { + String message = ("[INDEX] " + msg); + trace(message); + } + + public static void traceDisplay(String msg) { + String message = ("[DISPLAY]" + msg); + trace(message); + } + + public static void traceSorting(String msg) { + String message = ("[SORT] " + msg); + trace(message); + } + + public static void traceError(String msg) { + String message = ("[ERR] Thread=" + Thread.currentThread().getId() + " " + msg); + trace(message); + } + + public static void traceWarning(String msg) { + String message = ("[WARN] Thread=" + Thread.currentThread().getId() + " " + msg); + trace(message); + } + + public static void traceInfo(String msg) { + String message = ("[INF] Thread=" + Thread.currentThread().getId() + " " + msg); + trace(message); + } + + + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java index 5d8db1fa3e..c03022ab68 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.commands; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.linuxtools.internal.tmf.ui.dialogs.ManageCustomParsersDialog; -import org.eclipse.swt.widgets.Display; - -public class ManageCustomParsersCommandHandler extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - ManageCustomParsersDialog dialog = new ManageCustomParsersDialog(Display.getDefault().getActiveShell()); - dialog.open(); - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.commands; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.linuxtools.internal.tmf.ui.dialogs.ManageCustomParsersDialog; +import org.eclipse.swt.widgets.Display; + +public class ManageCustomParsersCommandHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + ManageCustomParsersDialog dialog = new ManageCustomParsersDialog(Display.getDefault().getActiveShell()); + dialog.open(); + return null; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/dialogs/ManageCustomParsersDialog.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/dialogs/ManageCustomParsersDialog.java index fb80cfe12b..0eb3318a4c 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/dialogs/ManageCustomParsersDialog.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/dialogs/ManageCustomParsersDialog.java @@ -1,283 +1,283 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.dialogs; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.window.Window; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards.CustomTxtParserWizard; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards.CustomXmlParserWizard; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.List; -import org.eclipse.swt.widgets.Shell; - -public class ManageCustomParsersDialog extends Dialog { - - private static final Image image = Activator.getDefault().getImageFromPath("/icons/etool16/customparser_wizard.gif"); //$NON-NLS-1$ - - Button txtButton; - Button xmlButton; - List parserList; - Button newButton; - Button editButton; - Button deleteButton; - Button importButton; - Button exportButton; - - public ManageCustomParsersDialog(Shell parent) { - super(parent); - setShellStyle(SWT.RESIZE | SWT.MAX | getShellStyle()); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Control createDialogArea(Composite parent) { - getShell().setText(Messages.ManageCustomParsersDialog_DialogHeader); - getShell().setImage(image); - - Composite composite = (Composite) super.createDialogArea(parent); - composite.setLayout(new GridLayout(2, false)); - - Composite listContainer = new Composite(composite, SWT.NONE); - listContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - GridLayout lcgl = new GridLayout(); - lcgl.marginHeight = 0; - lcgl.marginWidth = 0; - listContainer.setLayout(lcgl); - - Composite radioContainer = new Composite(listContainer, SWT.NONE); - GridLayout rcgl = new GridLayout(2, true); - rcgl.marginHeight = 0; - rcgl.marginWidth = 0; - radioContainer.setLayout(rcgl); - - txtButton = new Button(radioContainer, SWT.RADIO); - txtButton.setText(Messages.ManageCustomParsersDialog_TextButtonLabel); - txtButton.setSelection(true); - txtButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - fillParserList(); - }}); - - xmlButton = new Button(radioContainer, SWT.RADIO); - xmlButton.setText("XML"); //$NON-NLS-1$ - xmlButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - fillParserList(); - }}); - - parserList = new List(listContainer, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); - parserList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - parserList.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - if (parserList.getSelectionCount() == 0) { - editButton.setEnabled(false); - deleteButton.setEnabled(false); - exportButton.setEnabled(false); - } else { - editButton.setEnabled(true); - deleteButton.setEnabled(true); - exportButton.setEnabled(true); - } - }}); - - Composite buttonContainer = new Composite(composite, SWT.NULL); - buttonContainer.setLayout(new GridLayout()); - buttonContainer.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false)); - - newButton = new Button(buttonContainer, SWT.PUSH); - newButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - newButton.setText(Messages.ManageCustomParsersDialog_NewButtonLabel); - newButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - WizardDialog dialog = null; - if (txtButton.getSelection()) { - dialog = new WizardDialog(getShell(), new CustomTxtParserWizard()); - } else if (xmlButton.getSelection()) { - dialog = new WizardDialog(getShell(), new CustomXmlParserWizard()); - } - if (dialog != null) { - dialog.open(); - if (dialog.getReturnCode() == Window.OK) { - fillParserList(); - } - } - }}); - - editButton = new Button(buttonContainer, SWT.PUSH); - editButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - editButton.setText(Messages.ManageCustomParsersDialog_EditButtonLabel); - editButton.setEnabled(false); - editButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - WizardDialog dialog = null; - if (txtButton.getSelection()) { - dialog = new WizardDialog(getShell(), - new CustomTxtParserWizard(CustomTxtTraceDefinition.load(parserList.getSelection()[0]))); - } else if (xmlButton.getSelection()) { - dialog = new WizardDialog(getShell(), - new CustomXmlParserWizard(CustomXmlTraceDefinition.load(parserList.getSelection()[0]))); - } - if (dialog != null) { - dialog.open(); - if (dialog.getReturnCode() == Window.OK) { - fillParserList(); - } - } - }}); - - deleteButton = new Button(buttonContainer, SWT.PUSH); - deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - deleteButton.setText(Messages.ManageCustomParsersDialog_DeleteButtonLabel); - deleteButton.setEnabled(false); - deleteButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - boolean confirm = MessageDialog.openQuestion( - getShell(), - Messages.ManageCustomParsersDialog_DeleteParserDialogHeader, - Messages.ManageCustomParsersDialog_DeleteConfirmation + parserList.getSelection()[0] + "?"); //$NON-NLS-1$ - if (confirm) { - if (txtButton.getSelection()) { - CustomTxtTraceDefinition.delete(parserList.getSelection()[0]); - } else if (xmlButton.getSelection()) { - CustomXmlTraceDefinition.delete(parserList.getSelection()[0]); - } - fillParserList(); - } - }}); - - new Label(buttonContainer, SWT.NONE); // filler - - importButton = new Button(buttonContainer, SWT.PUSH); - importButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - importButton.setText(Messages.ManageCustomParsersDialog_ImportButtonLabel); - importButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.OPEN); - dialog.setText(Messages.ManageCustomParsersDialog_ImportParserSelection); - dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ - String path = dialog.open(); - if (path != null) { - CustomTraceDefinition[] defs = null; - if (txtButton.getSelection()) { - defs = CustomTxtTraceDefinition.loadAll(path); - } else if (xmlButton.getSelection()) { - defs = CustomXmlTraceDefinition.loadAll(path); - } - if (defs != null && defs.length > 0) { - for (CustomTraceDefinition def : defs) { - def.save(); - } - fillParserList(); - } - } - }}); - - exportButton = new Button(buttonContainer, SWT.PUSH); - exportButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - exportButton.setText(Messages.ManageCustomParsersDialog_ExportButtonLabel); - exportButton.setEnabled(false); - exportButton.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); - dialog.setText(Messages.ManageCustomParsersDialog_ExportParserSelection + parserList.getSelection()[0]); - dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ - String path = dialog.open(); - if (path != null) { - CustomTraceDefinition def = null; - if (txtButton.getSelection()) { - def = CustomTxtTraceDefinition.load(parserList.getSelection()[0]); - } else if (xmlButton.getSelection()) { - def = CustomXmlTraceDefinition.load(parserList.getSelection()[0]); - } - if (def != null) { - def.save(path); - } - } - }}); - - fillParserList(); - - getShell().setMinimumSize(300, 275); - return composite; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite) - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.CLOSE_LABEL, false); - } - - private void fillParserList() { - parserList.removeAll(); - if (txtButton.getSelection()) { - for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { - parserList.add(def.definitionName); - } - } else if (xmlButton.getSelection()) { - for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { - parserList.add(def.definitionName); - } - } - editButton.setEnabled(false); - deleteButton.setEnabled(false); - exportButton.setEnabled(false); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.dialogs; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards.CustomTxtParserWizard; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards.CustomXmlParserWizard; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Shell; + +public class ManageCustomParsersDialog extends Dialog { + + private static final Image image = Activator.getDefault().getImageFromPath("/icons/etool16/customparser_wizard.gif"); //$NON-NLS-1$ + + Button txtButton; + Button xmlButton; + List parserList; + Button newButton; + Button editButton; + Button deleteButton; + Button importButton; + Button exportButton; + + public ManageCustomParsersDialog(Shell parent) { + super(parent); + setShellStyle(SWT.RESIZE | SWT.MAX | getShellStyle()); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + @Override + protected Control createDialogArea(Composite parent) { + getShell().setText(Messages.ManageCustomParsersDialog_DialogHeader); + getShell().setImage(image); + + Composite composite = (Composite) super.createDialogArea(parent); + composite.setLayout(new GridLayout(2, false)); + + Composite listContainer = new Composite(composite, SWT.NONE); + listContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout lcgl = new GridLayout(); + lcgl.marginHeight = 0; + lcgl.marginWidth = 0; + listContainer.setLayout(lcgl); + + Composite radioContainer = new Composite(listContainer, SWT.NONE); + GridLayout rcgl = new GridLayout(2, true); + rcgl.marginHeight = 0; + rcgl.marginWidth = 0; + radioContainer.setLayout(rcgl); + + txtButton = new Button(radioContainer, SWT.RADIO); + txtButton.setText(Messages.ManageCustomParsersDialog_TextButtonLabel); + txtButton.setSelection(true); + txtButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + fillParserList(); + }}); + + xmlButton = new Button(radioContainer, SWT.RADIO); + xmlButton.setText("XML"); //$NON-NLS-1$ + xmlButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + fillParserList(); + }}); + + parserList = new List(listContainer, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); + parserList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + parserList.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + if (parserList.getSelectionCount() == 0) { + editButton.setEnabled(false); + deleteButton.setEnabled(false); + exportButton.setEnabled(false); + } else { + editButton.setEnabled(true); + deleteButton.setEnabled(true); + exportButton.setEnabled(true); + } + }}); + + Composite buttonContainer = new Composite(composite, SWT.NULL); + buttonContainer.setLayout(new GridLayout()); + buttonContainer.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false)); + + newButton = new Button(buttonContainer, SWT.PUSH); + newButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + newButton.setText(Messages.ManageCustomParsersDialog_NewButtonLabel); + newButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + WizardDialog dialog = null; + if (txtButton.getSelection()) { + dialog = new WizardDialog(getShell(), new CustomTxtParserWizard()); + } else if (xmlButton.getSelection()) { + dialog = new WizardDialog(getShell(), new CustomXmlParserWizard()); + } + if (dialog != null) { + dialog.open(); + if (dialog.getReturnCode() == Window.OK) { + fillParserList(); + } + } + }}); + + editButton = new Button(buttonContainer, SWT.PUSH); + editButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + editButton.setText(Messages.ManageCustomParsersDialog_EditButtonLabel); + editButton.setEnabled(false); + editButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + WizardDialog dialog = null; + if (txtButton.getSelection()) { + dialog = new WizardDialog(getShell(), + new CustomTxtParserWizard(CustomTxtTraceDefinition.load(parserList.getSelection()[0]))); + } else if (xmlButton.getSelection()) { + dialog = new WizardDialog(getShell(), + new CustomXmlParserWizard(CustomXmlTraceDefinition.load(parserList.getSelection()[0]))); + } + if (dialog != null) { + dialog.open(); + if (dialog.getReturnCode() == Window.OK) { + fillParserList(); + } + } + }}); + + deleteButton = new Button(buttonContainer, SWT.PUSH); + deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + deleteButton.setText(Messages.ManageCustomParsersDialog_DeleteButtonLabel); + deleteButton.setEnabled(false); + deleteButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + boolean confirm = MessageDialog.openQuestion( + getShell(), + Messages.ManageCustomParsersDialog_DeleteParserDialogHeader, + Messages.ManageCustomParsersDialog_DeleteConfirmation + parserList.getSelection()[0] + "?"); //$NON-NLS-1$ + if (confirm) { + if (txtButton.getSelection()) { + CustomTxtTraceDefinition.delete(parserList.getSelection()[0]); + } else if (xmlButton.getSelection()) { + CustomXmlTraceDefinition.delete(parserList.getSelection()[0]); + } + fillParserList(); + } + }}); + + new Label(buttonContainer, SWT.NONE); // filler + + importButton = new Button(buttonContainer, SWT.PUSH); + importButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + importButton.setText(Messages.ManageCustomParsersDialog_ImportButtonLabel); + importButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.OPEN); + dialog.setText(Messages.ManageCustomParsersDialog_ImportParserSelection); + dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ + String path = dialog.open(); + if (path != null) { + CustomTraceDefinition[] defs = null; + if (txtButton.getSelection()) { + defs = CustomTxtTraceDefinition.loadAll(path); + } else if (xmlButton.getSelection()) { + defs = CustomXmlTraceDefinition.loadAll(path); + } + if (defs != null && defs.length > 0) { + for (CustomTraceDefinition def : defs) { + def.save(); + } + fillParserList(); + } + } + }}); + + exportButton = new Button(buttonContainer, SWT.PUSH); + exportButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + exportButton.setText(Messages.ManageCustomParsersDialog_ExportButtonLabel); + exportButton.setEnabled(false); + exportButton.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); + dialog.setText(Messages.ManageCustomParsersDialog_ExportParserSelection + parserList.getSelection()[0]); + dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ + String path = dialog.open(); + if (path != null) { + CustomTraceDefinition def = null; + if (txtButton.getSelection()) { + def = CustomTxtTraceDefinition.load(parserList.getSelection()[0]); + } else if (xmlButton.getSelection()) { + def = CustomXmlTraceDefinition.load(parserList.getSelection()[0]); + } + if (def != null) { + def.save(path); + } + } + }}); + + fillParserList(); + + getShell().setMinimumSize(300, 275); + return composite; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite) + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.CLOSE_LABEL, false); + } + + private void fillParserList() { + parserList.removeAll(); + if (txtButton.getSelection()) { + for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { + parserList.add(def.definitionName); + } + } else if (xmlButton.getSelection()) { + for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { + parserList.add(def.definitionName); + } + } + editButton.setEnabled(false); + deleteButton.setEnabled(false); + exportButton.setEnabled(false); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/editors/handlers/AddBookmarkHandler.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/editors/handlers/AddBookmarkHandler.java index 35011cace0..1793371b3a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/editors/handlers/AddBookmarkHandler.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/editors/handlers/AddBookmarkHandler.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.editors.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.linuxtools.tmf.ui.editors.TmfEventsEditor; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PlatformUI; - -public class AddBookmarkHandler extends AbstractHandler { - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - IWorkbench wb = PlatformUI.getWorkbench(); - IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); - IEditorPart activeEditor = activePage.getActiveEditor(); - if (activeEditor instanceof TmfEventsEditor) { - TmfEventsEditor editor = (TmfEventsEditor) activeEditor; - editor.addBookmark(); - } - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.editors.handlers; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.linuxtools.tmf.ui.editors.TmfEventsEditor; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; + +public class AddBookmarkHandler extends AbstractHandler { + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + IWorkbench wb = PlatformUI.getWorkbench(); + IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); + IEditorPart activeEditor = activePage.getActiveEditor(); + if (activeEditor instanceof TmfEventsEditor) { + TmfEventsEditor editor = (TmfEventsEditor) activeEditor; + editor.addBookmark(); + } + return null; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/messages.properties b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/messages.properties index a3db451b19..36367fe508 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/messages.properties +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/messages.properties @@ -1,258 +1,258 @@ -# org.eclipse.linuxtools.tmf.ui.dialogs -ManageCustomParsersDialog_DeleteButtonLabel=Delete -ManageCustomParsersDialog_DeleteConfirmation=Are you sure you want to delete -ManageCustomParsersDialog_DeleteParserDialogHeader=Delete Custom Parser -ManageCustomParsersDialog_DialogHeader=Manage Custom Parsers -ManageCustomParsersDialog_EditButtonLabel=Edit... -ManageCustomParsersDialog_ExportButtonLabel=Export... -ManageCustomParsersDialog_ExportParserSelection=Select file to export -ManageCustomParsersDialog_ImportButtonLabel=Import... -ManageCustomParsersDialog_ImportParserSelection=Select custom parser file to import -ManageCustomParsersDialog_NewButtonLabel=New... -ManageCustomParsersDialog_ParseButtonLabel=Parse... -ManageCustomParsersDialog_ParseError=Parse Error -ManageCustomParsersDialog_TextButtonLabel=Text -ManageCustomParsersDialog_TraceSelection=Select log file to parse using - -# org.eclipse.linuxtools.tmf.ui.parsers.custom -CustomTraceDefinition_messageTag=Message -CustomTraceDefinition_otherTag=Other -CustomTraceDefinition_timestampTag=Time Stamp -CustomTxtTraceDefinition_action=action -CustomTxtTraceDefinition_cardinality=Cardinality -CustomTxtTraceDefinition_definition=Definition -CustomTxtTraceDefinition_definitionRootElement=CustomTxtTraceDefinitionList -CustomTxtTraceDefinition_format=format -CustomTxtTraceDefinition_inputData=InputData -CustomTxtTraceDefinition_inputLine=InputLine -CustomTxtTraceDefinition_max=max -CustomTxtTraceDefinition_min=min -CustomTxtTraceDefinition_name=name -CustomTxtTraceDefinition_outputColumn=OutputColumn -CustomTxtTraceDefinition_regEx=RegEx -CustomTxtTraceDefinition_timestampOutputFormat=TimeStampOutputFormat -CustomXmlTraceDefinition_action=action -CustomXmlTraceDefinition_attribute=Attribute -CustomXmlTraceDefinition_definition=Definition -CustomXmlTraceDefinition_definitionRootElement=CustomXMLTraceDefinitionList -CustomXmlTraceDefinition_format=format -CustomXmlTraceDefinition_ignoreTag=Ignore -CustomXmlTraceDefinition_inputData=InputData -CustomXmlTraceDefinition_inputElement=InputElement -CustomXmlTraceDefinition_logEntry=logentry -CustomXmlTraceDefinition_name=name -CustomXmlTraceDefinition_outputColumn=OutputColumn -CustomXmlTraceDefinition_timestampOutputFormat=TimeStampOutputFormat - -# org.eclipse.linuxtools.tmf.ui.viewers.events -TmfEventsTable_AddBookmarkActionText=Add Bookmark... -TmfEventsTable_AddBookmarkDialogText=Enter Bookmark name: -TmfEventsTable_AddBookmarkDialogTitle=Add Bookmark -TmfEventsTable_ApplyPresetFilterMenuName=Apply preset filter... -TmfEventsTable_ClearFiltersActionText=Clear Filters -TmfEventsTable_ContentColumnHeader=Content -TmfEventsTable_FilterHint= -TmfEventsTable_HideRawActionText=Hide Raw -TmfEventsTable_HideTableActionText=Hide Table -TmfEventsTable_ReferenceColumnHeader=File -TmfEventsTable_RemoveBookmarkActionText=Remove Bookmark -TmfEventsTable_SearchHint= -TmfEventsTable_SearchingJobName=Searching... -TmfEventsTable_ShowFilterBarActionText=Show Filter Bar -TmfEventsTable_ShowRawActionText=Show Raw -TmfEventsTable_ShowSearchBarActionText=Show Search Bar -TmfEventsTable_ShowTableActionText=Show Table -TmfEventsTable_SourceColumnHeader=Source -TmfEventsTable_TimestampColumnHeader=Timestamp -TmfEventsTable_TypeColumnHeader=Type - -# org.eclipse.linuxtools.tmf.ui.viewers.timegraph.dialogs -TmfTimeFilterDialog_EDIT_PROFILING_OPTIONS=Edit Profiling Options -TmfTimeFilterDialog_TRACE_FILTER=Trace Filter -TmfTimeFilterDialog_TRACE_FILTER_DESC=Define the filter set -TmfTimeFilterDialog_TRACE_ID=Trace Id -TmfTimeFilterDialog_TRACE_NAME=Trace Name -TmfTimeLegend_LEGEND=Legend -TmfTimeLegend_TRACE_STATES=Trace states -TmfTimeLegend_TRACE_STATES_TITLE=States Transition Visualizer -TmfTimeLegend_WINDOW_TITLE=Trace Visualizer's Legend -TmfTimeLegend_StateTypeName=States - -# org.eclipse.linuxtools.tmf.ui.viewers.timegraph.widgets -TmfTimeTipHandler_DURATION=Duration -TmfTimeTipHandler_TRACE_DATE=Date -TmfTimeTipHandler_TRACE_EVENT_TIME=Event Time -TmfTimeTipHandler_TRACE_START_TIME=Start Time -TmfTimeTipHandler_TRACE_STATE=State -TmfTimeTipHandler_TRACE_STOP_TIME=Stop Time - - -TmfTimeGraphViewer_ResetScaleActionNameText=Reset -TmfTimeGraphViewer_ResetScaleActionToolTipText=Reset the Time Scale to Default -TmfTimeGraphViewer_LegendActionNameText=Legend -TmfTimeGraphViewer_LegendActionToolTipText=Show Legend -TmfTimeGraphViewer_NextEventActionNameText=Next Event -TmfTimeGraphViewer_NextEventActionToolTipText=Select Next Event -TmfTimeGraphViewer_PreviousEventActionNameText=Previous Event -TmfTimeGraphViewer_PreviousEventActionToolTipText=Select Previous Event -TmfTimeGraphViewer_NextItemActionNameText=Next Item -TmfTimeGraphViewer_NextItemActionToolTipText=Select Next Item -TmfTimeGraphViewer_PreviousItemActionNameText=Previous Item -TmfTimeGraphViewer_PreviousItemActionToolTipText=Select Previous Item -TmfTimeGraphViewer_ZoomInActionNameText=Zoom In -TmfTimeGraphViewer_ZoomInActionToolTipText=Zoom In -TmfTimeGraphViewer_ZoomOutActionNameText=Zoom Out -TmfTimeGraphViewer_ZoomOutActionToolTipText=Zoom Out - -# org.eclipse.linuxtools.tmf.ui.views.colors -ColorsView_AddActionToolTipText=Insert new color setting -ColorsView_BackgroundButtonText=BG -ColorsView_BackgroundDialogText=Set background color -ColorsView_DeleteActionToolTipText=Delete color setting -ColorsView_ExportActionToolTipText=Export color settings -ColorsView_FilterButtonText=Filter... -ColorsView_ForegroundButtonText=FG -ColorsView_ForegroundDialogText=Set foreground color -ColorsView_ImportActionToolTipText=Import color settings -ColorsView_ImportOverwriteDialogMessage1=Do you want to overwrite the current color settings?\n -ColorsView_ImportOverwriteDialogMessage2=Answering No will insert the imported settings above the current selection. -ColorsView_ImportOverwriteDialogTitle=Overwrite current settings -ColorsView_MoveDownActionToolTipText=Decrease priority -ColorsView_MoveUpActionToolTipText=Increase priority -ColorsView_TickButtonText=Tick -TickColorDialog_TickColorDialogTitle=Choose tick color - -# org.eclipse.linuxtools.tmf.ui.wizards -CustomTxtParserInputWizardPage_addChildLine=Add child line -CustomTxtParserInputWizardPage_addGroup=Add group -CustomTxtParserInputWizardPage_addNextLine=Add next line -CustomTxtParserInputWizardPage_append=Append -CustomTxtParserInputWizardPage_appendWith=Append with | -CustomTxtParserInputWizardPage_capturedGroup=Captured group -CustomTxtParserInputWizardPage_cardinality=Cardinality: -CustomTxtParserInputWizardPage_dateFormatHelp=Date Format Help -CustomTxtParserInputWizardPage_desccriptionEdit=Edit an existing custom parser for text log files -CustomTxtParserInputWizardPage_descriptionNew=Create a new custom parser for text log files -CustomTxtParserInputWizardPage_format=format: -CustomTxtParserInputWizardPage_group=Group -CustomTxtParserInputWizardPage_highlightAll=Highlight All -CustomTxtParserInputWizardPage_logType=Log type: -CustomTxtParserInputWizardPage_matchingLineRoot=Matching root line : -CustomTxtParserInputWizardPage_matchingOtherLine=Matching other line: -CustomTxtParserInputWizardPage_matchingRootLine=matchingRootLine -CustomTxtParserInputWizardPage_max=max: -CustomTxtParserInputWizardPage_min=min: -CustomTxtParserInputWizardPage_moveDown=Move down -CustomTxtParserInputWizardPage_moveUp=Move up -CustomTxtParserInputWizardPage_name=name: -CustomTxtParserInputWizardPage_newGroup=New group -CustomTxtParserInputWizardPage_noMatch=*no match* -CustomTxtParserInputWizardPage_noMatchingGroup=*no matching group* -CustomTxtParserInputWizardPage_noMatchingLine=*no matching line* -CustomTxtParserInputWizardPage_noMatchingTimestamp=*no matching timestamp* -CustomTxtParserInputWizardPage_noMathcingLine=*no matching line* -CustomTxtParserInputWizardPage_nonMatchingLine=Non-matching line\n -CustomTxtParserInputWizardPage_noTimestampGroup=*no timestamp group* -CustomTxtParserInputWizardPage_preview=Preview: -CustomTxtParserInputWizardPage_previewInput=Preview input -CustomTxtParserInputWizardPage_previewLegend=Preview Legend -CustomTxtParserInputWizardPage_regularExpression=Regular expression: -CustomTxtParserInputWizardPage_regularExpressionHelp=Regular Expression Help -CustomTxtParserInputWizardPage_removeGroup=Remove group -CustomTxtParserInputWizardPage_removeLine=Remove line -CustomTxtParserInputWizardPage_set=Set -CustomTxtParserInputWizardPage_timestampFormat=Time Stamp format: -CustomTxtParserInputWizardPage_uncapturedText=Uncaptured text -CustomTxtParserInputWizardPage_unidentifiedCaptureGroup=Unidentified captured group -CustomTxtParserInputWizardPage_windowTitleEdit=Edit Custom Text Parser -CustomTxtParserInputWizardPage_windowTitleNew=New Custom Text Parser -CustomTxtParserOutputWizardPage_description=Customize the output of the parser -CustomTxtParserOutputWizardPage_moveAfter=Move After -CustomTxtParserOutputWizardPage_moveBefore=Move Before -CustomTxtParserOutputWizardPage_visible=Visible -CustomXmlParserInputWizardPage_emptyLogTypeError=Enter a name for the new log type. -CustomXmlParserInputWizardPage_duplicatelogTypeError=The log type name already exists. -CustomXmlParserInputWizardPage_noDocumentError=Add a document element. -CustomXmlParserInputWizardPage_missingLogEntryError=Identify a Log Entry element. -CustomXmlParserInputWizardPage_missingTimestampFmtError=Enter the output format for the Time Stamp field. -CustomXmlParserInputWizardPage_invalidTimestampFmtError=Enter a valid output format for the Time Stamp field. -CustomXmlParserInputWizardPage_notimestamporAttributeError=*no time stamp element or attribute* -CustomXmlParserInputWizardPage_missingDocumentElementError=Enter a name for the document element. -CustomXmlParserInputWizardPage_timestampElementPrompt=Element -CustomXmlParserInputWizardPage_timestampFormatPrompt=Enter the input format for the Time Stamp -CustomXmlParserInputWizardPage_missingInputElementNameError=Enter a name for the input -CustomXmlParserInputWizardPage_attributePrompt=Attribute -CustomXmlParserInputWizardPage_missingAttribute=Enter a name for the attribute -CustomXmlParserInputWizardPage_duplicateAttributeError=Duplicate attribute names -CustomXmlParserInputWizardPage_missingTimestampInFmtError=Enter the input format for the Time Stamp -CustomXmlParserInputWizardPage_invalidTimestampInFmtError=Enter a valid input format for the Time Stamp -CustomXmlParserInputWizardPage_missingDataGroupNameError=Enter a name for the data group -CustomXmlParserInputWizardPage_missingElementNameError=Enter a name for the element -CustomXmlParserInputWizardPage_duplicateElementNameError=Duplicate element names -CustomXmlParserInputWizardPage_addAttribute=Add attribute -CustomXmlParserInputWizardPage_addChildElement=Add child element -CustomXmlParserInputWizardPage_addDocumentEleemnt=Add document element -CustomXmlParserInputWizardPage_addDocumentElement=Add document element -CustomXmlParserInputWizardPage_addNextElement=Add next element -CustomXmlParserInputWizardPage_append=Append -CustomXmlParserInputWizardPage_appendWith=Append with | -CustomXmlParserInputWizardPage_attibute=Attribute -CustomXmlParserInputWizardPage_dateFormatHelp=Date Format Help -CustomXmlParserInputWizardPage_descriptionEdit=Edit an existing custom parser for XML log files -CustomXmlParserInputWizardPage_descriptionNew=Create a new custom parser for XML log files -CustomXmlParserInputWizardPage_elementName=Element name: -CustomXmlParserInputWizardPage_feelingLucky=Feeling lucky -CustomXmlParserInputWizardPage_format=format: -CustomXmlParserInputWizardPage_logEntry=Log Entry -CustomXmlParserInputWizardPage_logType=Log type: -CustomXmlParserInputWizardPage_moveDown=Move down -CustomXmlParserInputWizardPage_moveUp=Move up -CustomXmlParserInputWizardPage_name=name: -CustomXmlParserInputWizardPage_newAttibute=New attribute -CustomXmlParserInputWizardPage_noMatch=*no match* -CustomXmlParserInputWizardPage_noMatchingAttribute=*no matching attribute* -CustomXmlParserInputWizardPage_noMatchingElement=*no matching element* -CustomXmlParserInputWizardPage_preview=Preview: -CustomXmlParserInputWizardPage_previewInput=Preview input -CustomXmlParserInputWizardPage_removeAttribute=Remove attribute -CustomXmlParserInputWizardPage_removeElement=Remove element -CustomXmlParserInputWizardPage_set=Set -CustomXmlParserInputWizardPage_tagName=tag name: -CustomXmlParserInputWizardPage_timestampFormat=Time Stamp format: -CustomXmlParserInputWizardPage_titleEdit=Edit Custom XML Parser -CustomXmlParserInputWizardPage_titleNew=New Custom XML Parser -CustomXmlParserOutputWizardPage_description=Customize the output of the parser -CustomXmlParserOutputWizardPage_moveAfter=Move After -CustomXmlParserOutputWizardPage_moveBefore=Move Before -CustomXmlParserOutputWizardPage_visible=Visible - -# org.eclipse.linuxtools.tmf.ui.views.filter -FilterDialog_FilterDialogTitle=Edit filter -FilterView_AddActionToolTipText=Add new filter -FilterView_DeleteActionToolTipText=Delete filter node -FilterView_ExportActionToolTipText=Export filters -FilterView_FileDialogFilterName=TMF Filter files -FilterView_ImportActionToolTipText=Import filters -FilterView_SaveActionToolTipText=Save filters -FilterViewer_EmptyTreeHintText= -FilterViewer_CommonCategory=[common] -FilterViewer_AlphaButtonText=Alpha -FilterViewer_DeleteActionText=Delete -FilterViewer_FieldLabel=field: -FilterViewer_FilterNameHint=type filter name -FilterViewer_IgnoreCaseButtonText=ignore case -FilterViewer_NameLabel=name: -FilterViewer_NewPrefix=New -FilterViewer_NotLabel=not: -FilterViewer_NumButtonText=Num -FilterViewer_RegexHint=type regular expression -FilterViewer_RegexLabel=regex: -FilterViewer_ResultLabel=result: -FilterViewer_TimestampButtonText=Timestamp -FilterViewer_TypeLabel=type: -FilterViewer_ValueHint=type value -FilterViewer_ValueLabel=value: - -TmfView_PinActionNameText=Pin View -TmfView_PinActionToolTipText=Pin View - +# org.eclipse.linuxtools.tmf.ui.dialogs +ManageCustomParsersDialog_DeleteButtonLabel=Delete +ManageCustomParsersDialog_DeleteConfirmation=Are you sure you want to delete +ManageCustomParsersDialog_DeleteParserDialogHeader=Delete Custom Parser +ManageCustomParsersDialog_DialogHeader=Manage Custom Parsers +ManageCustomParsersDialog_EditButtonLabel=Edit... +ManageCustomParsersDialog_ExportButtonLabel=Export... +ManageCustomParsersDialog_ExportParserSelection=Select file to export +ManageCustomParsersDialog_ImportButtonLabel=Import... +ManageCustomParsersDialog_ImportParserSelection=Select custom parser file to import +ManageCustomParsersDialog_NewButtonLabel=New... +ManageCustomParsersDialog_ParseButtonLabel=Parse... +ManageCustomParsersDialog_ParseError=Parse Error +ManageCustomParsersDialog_TextButtonLabel=Text +ManageCustomParsersDialog_TraceSelection=Select log file to parse using + +# org.eclipse.linuxtools.tmf.ui.parsers.custom +CustomTraceDefinition_messageTag=Message +CustomTraceDefinition_otherTag=Other +CustomTraceDefinition_timestampTag=Time Stamp +CustomTxtTraceDefinition_action=action +CustomTxtTraceDefinition_cardinality=Cardinality +CustomTxtTraceDefinition_definition=Definition +CustomTxtTraceDefinition_definitionRootElement=CustomTxtTraceDefinitionList +CustomTxtTraceDefinition_format=format +CustomTxtTraceDefinition_inputData=InputData +CustomTxtTraceDefinition_inputLine=InputLine +CustomTxtTraceDefinition_max=max +CustomTxtTraceDefinition_min=min +CustomTxtTraceDefinition_name=name +CustomTxtTraceDefinition_outputColumn=OutputColumn +CustomTxtTraceDefinition_regEx=RegEx +CustomTxtTraceDefinition_timestampOutputFormat=TimeStampOutputFormat +CustomXmlTraceDefinition_action=action +CustomXmlTraceDefinition_attribute=Attribute +CustomXmlTraceDefinition_definition=Definition +CustomXmlTraceDefinition_definitionRootElement=CustomXMLTraceDefinitionList +CustomXmlTraceDefinition_format=format +CustomXmlTraceDefinition_ignoreTag=Ignore +CustomXmlTraceDefinition_inputData=InputData +CustomXmlTraceDefinition_inputElement=InputElement +CustomXmlTraceDefinition_logEntry=logentry +CustomXmlTraceDefinition_name=name +CustomXmlTraceDefinition_outputColumn=OutputColumn +CustomXmlTraceDefinition_timestampOutputFormat=TimeStampOutputFormat + +# org.eclipse.linuxtools.tmf.ui.viewers.events +TmfEventsTable_AddBookmarkActionText=Add Bookmark... +TmfEventsTable_AddBookmarkDialogText=Enter Bookmark name: +TmfEventsTable_AddBookmarkDialogTitle=Add Bookmark +TmfEventsTable_ApplyPresetFilterMenuName=Apply preset filter... +TmfEventsTable_ClearFiltersActionText=Clear Filters +TmfEventsTable_ContentColumnHeader=Content +TmfEventsTable_FilterHint= +TmfEventsTable_HideRawActionText=Hide Raw +TmfEventsTable_HideTableActionText=Hide Table +TmfEventsTable_ReferenceColumnHeader=File +TmfEventsTable_RemoveBookmarkActionText=Remove Bookmark +TmfEventsTable_SearchHint= +TmfEventsTable_SearchingJobName=Searching... +TmfEventsTable_ShowFilterBarActionText=Show Filter Bar +TmfEventsTable_ShowRawActionText=Show Raw +TmfEventsTable_ShowSearchBarActionText=Show Search Bar +TmfEventsTable_ShowTableActionText=Show Table +TmfEventsTable_SourceColumnHeader=Source +TmfEventsTable_TimestampColumnHeader=Timestamp +TmfEventsTable_TypeColumnHeader=Type + +# org.eclipse.linuxtools.tmf.ui.viewers.timegraph.dialogs +TmfTimeFilterDialog_EDIT_PROFILING_OPTIONS=Edit Profiling Options +TmfTimeFilterDialog_TRACE_FILTER=Trace Filter +TmfTimeFilterDialog_TRACE_FILTER_DESC=Define the filter set +TmfTimeFilterDialog_TRACE_ID=Trace Id +TmfTimeFilterDialog_TRACE_NAME=Trace Name +TmfTimeLegend_LEGEND=Legend +TmfTimeLegend_TRACE_STATES=Trace states +TmfTimeLegend_TRACE_STATES_TITLE=States Transition Visualizer +TmfTimeLegend_WINDOW_TITLE=Trace Visualizer's Legend +TmfTimeLegend_StateTypeName=States + +# org.eclipse.linuxtools.tmf.ui.viewers.timegraph.widgets +TmfTimeTipHandler_DURATION=Duration +TmfTimeTipHandler_TRACE_DATE=Date +TmfTimeTipHandler_TRACE_EVENT_TIME=Event Time +TmfTimeTipHandler_TRACE_START_TIME=Start Time +TmfTimeTipHandler_TRACE_STATE=State +TmfTimeTipHandler_TRACE_STOP_TIME=Stop Time + + +TmfTimeGraphViewer_ResetScaleActionNameText=Reset +TmfTimeGraphViewer_ResetScaleActionToolTipText=Reset the Time Scale to Default +TmfTimeGraphViewer_LegendActionNameText=Legend +TmfTimeGraphViewer_LegendActionToolTipText=Show Legend +TmfTimeGraphViewer_NextEventActionNameText=Next Event +TmfTimeGraphViewer_NextEventActionToolTipText=Select Next Event +TmfTimeGraphViewer_PreviousEventActionNameText=Previous Event +TmfTimeGraphViewer_PreviousEventActionToolTipText=Select Previous Event +TmfTimeGraphViewer_NextItemActionNameText=Next Item +TmfTimeGraphViewer_NextItemActionToolTipText=Select Next Item +TmfTimeGraphViewer_PreviousItemActionNameText=Previous Item +TmfTimeGraphViewer_PreviousItemActionToolTipText=Select Previous Item +TmfTimeGraphViewer_ZoomInActionNameText=Zoom In +TmfTimeGraphViewer_ZoomInActionToolTipText=Zoom In +TmfTimeGraphViewer_ZoomOutActionNameText=Zoom Out +TmfTimeGraphViewer_ZoomOutActionToolTipText=Zoom Out + +# org.eclipse.linuxtools.tmf.ui.views.colors +ColorsView_AddActionToolTipText=Insert new color setting +ColorsView_BackgroundButtonText=BG +ColorsView_BackgroundDialogText=Set background color +ColorsView_DeleteActionToolTipText=Delete color setting +ColorsView_ExportActionToolTipText=Export color settings +ColorsView_FilterButtonText=Filter... +ColorsView_ForegroundButtonText=FG +ColorsView_ForegroundDialogText=Set foreground color +ColorsView_ImportActionToolTipText=Import color settings +ColorsView_ImportOverwriteDialogMessage1=Do you want to overwrite the current color settings?\n +ColorsView_ImportOverwriteDialogMessage2=Answering No will insert the imported settings above the current selection. +ColorsView_ImportOverwriteDialogTitle=Overwrite current settings +ColorsView_MoveDownActionToolTipText=Decrease priority +ColorsView_MoveUpActionToolTipText=Increase priority +ColorsView_TickButtonText=Tick +TickColorDialog_TickColorDialogTitle=Choose tick color + +# org.eclipse.linuxtools.tmf.ui.wizards +CustomTxtParserInputWizardPage_addChildLine=Add child line +CustomTxtParserInputWizardPage_addGroup=Add group +CustomTxtParserInputWizardPage_addNextLine=Add next line +CustomTxtParserInputWizardPage_append=Append +CustomTxtParserInputWizardPage_appendWith=Append with | +CustomTxtParserInputWizardPage_capturedGroup=Captured group +CustomTxtParserInputWizardPage_cardinality=Cardinality: +CustomTxtParserInputWizardPage_dateFormatHelp=Date Format Help +CustomTxtParserInputWizardPage_desccriptionEdit=Edit an existing custom parser for text log files +CustomTxtParserInputWizardPage_descriptionNew=Create a new custom parser for text log files +CustomTxtParserInputWizardPage_format=format: +CustomTxtParserInputWizardPage_group=Group +CustomTxtParserInputWizardPage_highlightAll=Highlight All +CustomTxtParserInputWizardPage_logType=Log type: +CustomTxtParserInputWizardPage_matchingLineRoot=Matching root line : +CustomTxtParserInputWizardPage_matchingOtherLine=Matching other line: +CustomTxtParserInputWizardPage_matchingRootLine=matchingRootLine +CustomTxtParserInputWizardPage_max=max: +CustomTxtParserInputWizardPage_min=min: +CustomTxtParserInputWizardPage_moveDown=Move down +CustomTxtParserInputWizardPage_moveUp=Move up +CustomTxtParserInputWizardPage_name=name: +CustomTxtParserInputWizardPage_newGroup=New group +CustomTxtParserInputWizardPage_noMatch=*no match* +CustomTxtParserInputWizardPage_noMatchingGroup=*no matching group* +CustomTxtParserInputWizardPage_noMatchingLine=*no matching line* +CustomTxtParserInputWizardPage_noMatchingTimestamp=*no matching timestamp* +CustomTxtParserInputWizardPage_noMathcingLine=*no matching line* +CustomTxtParserInputWizardPage_nonMatchingLine=Non-matching line\n +CustomTxtParserInputWizardPage_noTimestampGroup=*no timestamp group* +CustomTxtParserInputWizardPage_preview=Preview: +CustomTxtParserInputWizardPage_previewInput=Preview input +CustomTxtParserInputWizardPage_previewLegend=Preview Legend +CustomTxtParserInputWizardPage_regularExpression=Regular expression: +CustomTxtParserInputWizardPage_regularExpressionHelp=Regular Expression Help +CustomTxtParserInputWizardPage_removeGroup=Remove group +CustomTxtParserInputWizardPage_removeLine=Remove line +CustomTxtParserInputWizardPage_set=Set +CustomTxtParserInputWizardPage_timestampFormat=Time Stamp format: +CustomTxtParserInputWizardPage_uncapturedText=Uncaptured text +CustomTxtParserInputWizardPage_unidentifiedCaptureGroup=Unidentified captured group +CustomTxtParserInputWizardPage_windowTitleEdit=Edit Custom Text Parser +CustomTxtParserInputWizardPage_windowTitleNew=New Custom Text Parser +CustomTxtParserOutputWizardPage_description=Customize the output of the parser +CustomTxtParserOutputWizardPage_moveAfter=Move After +CustomTxtParserOutputWizardPage_moveBefore=Move Before +CustomTxtParserOutputWizardPage_visible=Visible +CustomXmlParserInputWizardPage_emptyLogTypeError=Enter a name for the new log type. +CustomXmlParserInputWizardPage_duplicatelogTypeError=The log type name already exists. +CustomXmlParserInputWizardPage_noDocumentError=Add a document element. +CustomXmlParserInputWizardPage_missingLogEntryError=Identify a Log Entry element. +CustomXmlParserInputWizardPage_missingTimestampFmtError=Enter the output format for the Time Stamp field. +CustomXmlParserInputWizardPage_invalidTimestampFmtError=Enter a valid output format for the Time Stamp field. +CustomXmlParserInputWizardPage_notimestamporAttributeError=*no time stamp element or attribute* +CustomXmlParserInputWizardPage_missingDocumentElementError=Enter a name for the document element. +CustomXmlParserInputWizardPage_timestampElementPrompt=Element +CustomXmlParserInputWizardPage_timestampFormatPrompt=Enter the input format for the Time Stamp +CustomXmlParserInputWizardPage_missingInputElementNameError=Enter a name for the input +CustomXmlParserInputWizardPage_attributePrompt=Attribute +CustomXmlParserInputWizardPage_missingAttribute=Enter a name for the attribute +CustomXmlParserInputWizardPage_duplicateAttributeError=Duplicate attribute names +CustomXmlParserInputWizardPage_missingTimestampInFmtError=Enter the input format for the Time Stamp +CustomXmlParserInputWizardPage_invalidTimestampInFmtError=Enter a valid input format for the Time Stamp +CustomXmlParserInputWizardPage_missingDataGroupNameError=Enter a name for the data group +CustomXmlParserInputWizardPage_missingElementNameError=Enter a name for the element +CustomXmlParserInputWizardPage_duplicateElementNameError=Duplicate element names +CustomXmlParserInputWizardPage_addAttribute=Add attribute +CustomXmlParserInputWizardPage_addChildElement=Add child element +CustomXmlParserInputWizardPage_addDocumentEleemnt=Add document element +CustomXmlParserInputWizardPage_addDocumentElement=Add document element +CustomXmlParserInputWizardPage_addNextElement=Add next element +CustomXmlParserInputWizardPage_append=Append +CustomXmlParserInputWizardPage_appendWith=Append with | +CustomXmlParserInputWizardPage_attibute=Attribute +CustomXmlParserInputWizardPage_dateFormatHelp=Date Format Help +CustomXmlParserInputWizardPage_descriptionEdit=Edit an existing custom parser for XML log files +CustomXmlParserInputWizardPage_descriptionNew=Create a new custom parser for XML log files +CustomXmlParserInputWizardPage_elementName=Element name: +CustomXmlParserInputWizardPage_feelingLucky=Feeling lucky +CustomXmlParserInputWizardPage_format=format: +CustomXmlParserInputWizardPage_logEntry=Log Entry +CustomXmlParserInputWizardPage_logType=Log type: +CustomXmlParserInputWizardPage_moveDown=Move down +CustomXmlParserInputWizardPage_moveUp=Move up +CustomXmlParserInputWizardPage_name=name: +CustomXmlParserInputWizardPage_newAttibute=New attribute +CustomXmlParserInputWizardPage_noMatch=*no match* +CustomXmlParserInputWizardPage_noMatchingAttribute=*no matching attribute* +CustomXmlParserInputWizardPage_noMatchingElement=*no matching element* +CustomXmlParserInputWizardPage_preview=Preview: +CustomXmlParserInputWizardPage_previewInput=Preview input +CustomXmlParserInputWizardPage_removeAttribute=Remove attribute +CustomXmlParserInputWizardPage_removeElement=Remove element +CustomXmlParserInputWizardPage_set=Set +CustomXmlParserInputWizardPage_tagName=tag name: +CustomXmlParserInputWizardPage_timestampFormat=Time Stamp format: +CustomXmlParserInputWizardPage_titleEdit=Edit Custom XML Parser +CustomXmlParserInputWizardPage_titleNew=New Custom XML Parser +CustomXmlParserOutputWizardPage_description=Customize the output of the parser +CustomXmlParserOutputWizardPage_moveAfter=Move After +CustomXmlParserOutputWizardPage_moveBefore=Move Before +CustomXmlParserOutputWizardPage_visible=Visible + +# org.eclipse.linuxtools.tmf.ui.views.filter +FilterDialog_FilterDialogTitle=Edit filter +FilterView_AddActionToolTipText=Add new filter +FilterView_DeleteActionToolTipText=Delete filter node +FilterView_ExportActionToolTipText=Export filters +FilterView_FileDialogFilterName=TMF Filter files +FilterView_ImportActionToolTipText=Import filters +FilterView_SaveActionToolTipText=Save filters +FilterViewer_EmptyTreeHintText= +FilterViewer_CommonCategory=[common] +FilterViewer_AlphaButtonText=Alpha +FilterViewer_DeleteActionText=Delete +FilterViewer_FieldLabel=field: +FilterViewer_FilterNameHint=type filter name +FilterViewer_IgnoreCaseButtonText=ignore case +FilterViewer_NameLabel=name: +FilterViewer_NewPrefix=New +FilterViewer_NotLabel=not: +FilterViewer_NumButtonText=Num +FilterViewer_RegexHint=type regular expression +FilterViewer_RegexLabel=regex: +FilterViewer_ResultLabel=result: +FilterViewer_TimestampButtonText=Timestamp +FilterViewer_TypeLabel=type: +FilterViewer_ValueHint=type value +FilterViewer_ValueLabel=value: + +TmfView_PinActionNameText=Pin View +TmfView_PinActionToolTipText=Pin View + diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEvent.java index 631003e0b8..6c70b15436 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEvent.java @@ -1,136 +1,136 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; -import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; -import org.eclipse.linuxtools.tmf.core.event.TmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEventField; -import org.eclipse.linuxtools.tmf.core.event.TmfEventType; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -public class CustomEvent extends TmfEvent { - - protected static final String TIMESTAMP_INPUT_FORMAT_KEY = "CE_TS_I_F"; //$NON-NLS-1$ - protected static final String NO_MESSAGE = ""; //$NON-NLS-1$ - public static final byte TIMESTAMP_SCALE = -3; - - protected CustomTraceDefinition fDefinition; - protected Map fData; - private TmfEventField[] fColumnData; - - public CustomEvent(CustomTraceDefinition definition) { - fDefinition = definition; - fData = new HashMap(); - } - - public CustomEvent(CustomTraceDefinition definition, TmfEvent other) { - super(other); - fDefinition = definition; - fData = new HashMap(); - } - - public CustomEvent(CustomTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { - super(parentTrace, timestamp, source, type, null, reference); - fDefinition = definition; - fData = new HashMap(); - } - - @Override - public ITmfTimestamp getTimestamp() { - if (fData != null) processData(); - return super.getTimestamp(); - } - - public TmfEventField[] extractItemFields() { - if (fData != null) processData(); - return Arrays.copyOf(fColumnData, fColumnData.length); - } - - private void processData() { - String timeStampString = fData.get(CustomTraceDefinition.TAG_TIMESTAMP); - String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); - Date date = null; - if (timeStampInputFormat != null && timeStampString != null) { - SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampInputFormat); - try { - date = dateFormat.parse(timeStampString); - setTimestamp(new TmfTimestamp(date.getTime(), TIMESTAMP_SCALE)); - } catch (ParseException e) { - setTimestamp(TmfTimestamp.ZERO); - } - } else { - setTimestamp(TmfTimestamp.ZERO); - } - - int i = 0; - fColumnData = new TmfEventField[fDefinition.outputs.size()]; - for (OutputColumn outputColumn : fDefinition.outputs) { - String value = fData.get(outputColumn.name); - if (outputColumn.name.equals(CustomTraceDefinition.TAG_TIMESTAMP) && date != null) { - SimpleDateFormat dateFormat = new SimpleDateFormat(fDefinition.timeStampOutputFormat); - fColumnData[i++] = new TmfEventField(outputColumn.name, dateFormat.format(date)); - } else { - fColumnData[i++] = new TmfEventField(outputColumn.name, (value != null ? value : "")); //$NON-NLS-1$ - } - } - CustomEventContent content = (CustomEventContent) getContent(); - content.setFields(fColumnData); - fData = null; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((fDefinition == null) ? 0 : fDefinition.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof CustomEvent)) { - return false; - } - CustomEvent other = (CustomEvent) obj; - if (fDefinition == null) { - if (other.fDefinition != null) { - return false; - } - } else if (!fDefinition.equals(other.fDefinition)) { - return false; - } - return true; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; +import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; +import org.eclipse.linuxtools.tmf.core.event.TmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEventField; +import org.eclipse.linuxtools.tmf.core.event.TmfEventType; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +public class CustomEvent extends TmfEvent { + + protected static final String TIMESTAMP_INPUT_FORMAT_KEY = "CE_TS_I_F"; //$NON-NLS-1$ + protected static final String NO_MESSAGE = ""; //$NON-NLS-1$ + public static final byte TIMESTAMP_SCALE = -3; + + protected CustomTraceDefinition fDefinition; + protected Map fData; + private TmfEventField[] fColumnData; + + public CustomEvent(CustomTraceDefinition definition) { + fDefinition = definition; + fData = new HashMap(); + } + + public CustomEvent(CustomTraceDefinition definition, TmfEvent other) { + super(other); + fDefinition = definition; + fData = new HashMap(); + } + + public CustomEvent(CustomTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { + super(parentTrace, timestamp, source, type, null, reference); + fDefinition = definition; + fData = new HashMap(); + } + + @Override + public ITmfTimestamp getTimestamp() { + if (fData != null) processData(); + return super.getTimestamp(); + } + + public TmfEventField[] extractItemFields() { + if (fData != null) processData(); + return Arrays.copyOf(fColumnData, fColumnData.length); + } + + private void processData() { + String timeStampString = fData.get(CustomTraceDefinition.TAG_TIMESTAMP); + String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); + Date date = null; + if (timeStampInputFormat != null && timeStampString != null) { + SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampInputFormat); + try { + date = dateFormat.parse(timeStampString); + setTimestamp(new TmfTimestamp(date.getTime(), TIMESTAMP_SCALE)); + } catch (ParseException e) { + setTimestamp(TmfTimestamp.ZERO); + } + } else { + setTimestamp(TmfTimestamp.ZERO); + } + + int i = 0; + fColumnData = new TmfEventField[fDefinition.outputs.size()]; + for (OutputColumn outputColumn : fDefinition.outputs) { + String value = fData.get(outputColumn.name); + if (outputColumn.name.equals(CustomTraceDefinition.TAG_TIMESTAMP) && date != null) { + SimpleDateFormat dateFormat = new SimpleDateFormat(fDefinition.timeStampOutputFormat); + fColumnData[i++] = new TmfEventField(outputColumn.name, dateFormat.format(date)); + } else { + fColumnData[i++] = new TmfEventField(outputColumn.name, (value != null ? value : "")); //$NON-NLS-1$ + } + } + CustomEventContent content = (CustomEventContent) getContent(); + content.setFields(fColumnData); + fData = null; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((fDefinition == null) ? 0 : fDefinition.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof CustomEvent)) { + return false; + } + CustomEvent other = (CustomEvent) obj; + if (fDefinition == null) { + if (other.fDefinition != null) { + return false; + } + } else if (!fDefinition.equals(other.fDefinition)) { + return false; + } + return true; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventContent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventContent.java index 9d21c3113a..1b0c3ca72c 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventContent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventContent.java @@ -1,41 +1,41 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; -import org.eclipse.linuxtools.tmf.core.event.TmfEventField; - -public class CustomEventContent extends TmfEventField { - - public CustomEventContent(CustomEvent parent, StringBuffer content) { - super(ITmfEventField.ROOT_FIELD_ID, content); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return super.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof CustomEventContent)) { - return false; - } - return true; - } - - public void setFields(ITmfEventField[] fields) { - super.setValue(getValue(), fields); - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; +import org.eclipse.linuxtools.tmf.core.event.TmfEventField; + +public class CustomEventContent extends TmfEventField { + + public CustomEventContent(CustomEvent parent, StringBuffer content) { + super(ITmfEventField.ROOT_FIELD_ID, content); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return super.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof CustomEventContent)) { + return false; + } + return true; + } + + public void setFields(ITmfEventField[] fields) { + super.setValue(getValue(), fields); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventType.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventType.java index 4a5026b380..326a76d568 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventType.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventType.java @@ -1,24 +1,24 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; -import org.eclipse.linuxtools.tmf.core.event.TmfEventField; -import org.eclipse.linuxtools.tmf.core.event.TmfEventType; - -public abstract class CustomEventType extends TmfEventType { - - private static String CONTEXT_ID = "CustomEventType"; //$NON-NLS-1$ - - public CustomEventType(CustomTraceDefinition definition) { - super(CONTEXT_ID, definition.definitionName, getRootField(definition)); - } - - private static ITmfEventField getRootField(CustomTraceDefinition definition) { - ITmfEventField[] fields = new ITmfEventField[definition.outputs.size()]; - for (int i = 0; i < fields.length; i++) { - fields[i] = new TmfEventField(definition.outputs.get(i).name, null); - } - ITmfEventField rootField = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, fields); - return rootField; - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; +import org.eclipse.linuxtools.tmf.core.event.TmfEventField; +import org.eclipse.linuxtools.tmf.core.event.TmfEventType; + +public abstract class CustomEventType extends TmfEventType { + + private static String CONTEXT_ID = "CustomEventType"; //$NON-NLS-1$ + + public CustomEventType(CustomTraceDefinition definition) { + super(CONTEXT_ID, definition.definitionName, getRootField(definition)); + } + + private static ITmfEventField getRootField(CustomTraceDefinition definition) { + ITmfEventField[] fields = new ITmfEventField[definition.outputs.size()]; + for (int i = 0; i < fields.length; i++) { + fields[i] = new TmfEventField(definition.outputs.get(i).name, null); + } + ITmfEventField rootField = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, fields); + return rootField; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventsTable.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventsTable.java index 19163e1718..5b166fa209 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventsTable.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomEventsTable.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.util.LinkedList; -import java.util.List; - -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEventField; -import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; -import org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; - -public class CustomEventsTable extends TmfEventsTable { - - private final CustomTraceDefinition fDefinition; - - public CustomEventsTable(CustomTraceDefinition definition, Composite parent, int cacheSize) { - super(parent, cacheSize, new ColumnData[0]); - fDefinition = definition; - createColumnHeaders(); - } - - protected void createColumnHeaders() { - if (fDefinition == null) { - return; - } - List columnData = new LinkedList(); - for (OutputColumn outputColumn : fDefinition.outputs) { - ColumnData column = new ColumnData(outputColumn.name, 0, SWT.LEFT); - columnData.add(column); - } - setColumnHeaders(columnData.toArray(new ColumnData[0])); - } - - @Override - public TmfEventField[] extractItemFields(ITmfEvent event) { - if (event instanceof CustomEvent) { - TmfEventField[] fields = ((CustomEvent) event).extractItemFields(); -// String[] labels = new String[fields.length]; -// for (int i = 0; i < fields.length; i++) { -// labels[i] = (String) fields[i].getValue(); -// } - return fields; - } - return new TmfEventField[0]; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEventField; +import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; +import org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; + +public class CustomEventsTable extends TmfEventsTable { + + private final CustomTraceDefinition fDefinition; + + public CustomEventsTable(CustomTraceDefinition definition, Composite parent, int cacheSize) { + super(parent, cacheSize, new ColumnData[0]); + fDefinition = definition; + createColumnHeaders(); + } + + protected void createColumnHeaders() { + if (fDefinition == null) { + return; + } + List columnData = new LinkedList(); + for (OutputColumn outputColumn : fDefinition.outputs) { + ColumnData column = new ColumnData(outputColumn.name, 0, SWT.LEFT); + columnData.add(column); + } + setColumnHeaders(columnData.toArray(new ColumnData[0])); + } + + @Override + public TmfEventField[] extractItemFields(ITmfEvent event) { + if (event instanceof CustomEvent) { + TmfEventField[] fields = ((CustomEvent) event).extractItemFields(); +// String[] labels = new String[fields.length]; +// for (int i = 0; i < fields.length; i++) { +// labels[i] = (String) fields[i].getValue(); +// } + return fields; + } + return new TmfEventField[0]; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTraceDefinition.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTraceDefinition.java index 539d0e1caa..ef94775758 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTraceDefinition.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTraceDefinition.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.text.SimpleDateFormat; -import java.util.List; - -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; - - -public abstract class CustomTraceDefinition { - - public static final int ACTION_SET = 0; - public static final int ACTION_APPEND = 1; - public static final int ACTION_APPEND_WITH_SEPARATOR = 2; - - public static final String TAG_TIMESTAMP = Messages.CustomTraceDefinition_timestampTag; - public static final String TAG_MESSAGE = Messages.CustomTraceDefinition_messageTag; - public static final String TAG_OTHER = Messages.CustomTraceDefinition_otherTag; - - public String definitionName; - public List outputs; - public String timeStampOutputFormat; - - public static class OutputColumn { - public String name; - - public OutputColumn() {} - - public OutputColumn(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - } - - public String formatTimeStamp(TmfTimestamp timestamp) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeStampOutputFormat); - return simpleDateFormat.format(timestamp.getValue()); - } - - public abstract void save(); - public abstract void save(String path); -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.text.SimpleDateFormat; +import java.util.List; + +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; + + +public abstract class CustomTraceDefinition { + + public static final int ACTION_SET = 0; + public static final int ACTION_APPEND = 1; + public static final int ACTION_APPEND_WITH_SEPARATOR = 2; + + public static final String TAG_TIMESTAMP = Messages.CustomTraceDefinition_timestampTag; + public static final String TAG_MESSAGE = Messages.CustomTraceDefinition_messageTag; + public static final String TAG_OTHER = Messages.CustomTraceDefinition_otherTag; + + public String definitionName; + public List outputs; + public String timeStampOutputFormat; + + public static class OutputColumn { + public String name; + + public OutputColumn() {} + + public OutputColumn(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + } + + public String formatTimeStamp(TmfTimestamp timestamp) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeStampOutputFormat); + return simpleDateFormat.format(timestamp.getValue()); + } + + public abstract void save(); + public abstract void save(String path); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEvent.java index 745a449266..9f2012db56 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEvent.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.util.regex.Matcher; - -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputData; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; -import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; -import org.eclipse.linuxtools.tmf.core.event.TmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEventType; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -public class CustomTxtEvent extends CustomEvent { - - public CustomTxtEvent(CustomTxtTraceDefinition definition) { - super(definition); - setType(new CustomTxtEventType(definition)); - } - - public CustomTxtEvent(CustomTxtTraceDefinition definition, TmfEvent other) { - super(definition, other); - } - - public CustomTxtEvent(CustomTxtTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { - super(definition, parentTrace, timestamp, source, type, reference); - } - - @Override - public void setContent(ITmfEventField content) { - super.setContent(content); - } - - public void processGroups(InputLine input, Matcher matcher) { - if (input.columns == null) { - return; - } - for (int i = 0; i < input.columns.size(); i++) { - InputData column = input.columns.get(i); - if (i < matcher.groupCount() && matcher.group(i + 1) != null) { - String value = matcher.group(i + 1).trim(); - if (value.length() == 0) { - continue; - } - String name = column.name; - if (column.action == CustomTraceDefinition.ACTION_SET) { - fData.put(name, value); - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); - } - } else if (column.action == CustomTraceDefinition.ACTION_APPEND) { - String s = fData.get(name); - if (s != null) { - fData.put(name, s + value); - } else { - fData.put(name, value); - } - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); - if (timeStampInputFormat != null) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + column.format); - } else { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); - } - } - } else if (column.action == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { - String s = fData.get(name); - if (s != null) { - fData.put(name, s + " | " + value); //$NON-NLS-1$ - } else { - fData.put(name, value); - } - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); - if (timeStampInputFormat != null) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + " | " + column.format); //$NON-NLS-1$ - } else { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); - } - } - } - } - } - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.util.regex.Matcher; + +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputData; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; +import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; +import org.eclipse.linuxtools.tmf.core.event.TmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEventType; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +public class CustomTxtEvent extends CustomEvent { + + public CustomTxtEvent(CustomTxtTraceDefinition definition) { + super(definition); + setType(new CustomTxtEventType(definition)); + } + + public CustomTxtEvent(CustomTxtTraceDefinition definition, TmfEvent other) { + super(definition, other); + } + + public CustomTxtEvent(CustomTxtTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { + super(definition, parentTrace, timestamp, source, type, reference); + } + + @Override + public void setContent(ITmfEventField content) { + super.setContent(content); + } + + public void processGroups(InputLine input, Matcher matcher) { + if (input.columns == null) { + return; + } + for (int i = 0; i < input.columns.size(); i++) { + InputData column = input.columns.get(i); + if (i < matcher.groupCount() && matcher.group(i + 1) != null) { + String value = matcher.group(i + 1).trim(); + if (value.length() == 0) { + continue; + } + String name = column.name; + if (column.action == CustomTraceDefinition.ACTION_SET) { + fData.put(name, value); + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); + } + } else if (column.action == CustomTraceDefinition.ACTION_APPEND) { + String s = fData.get(name); + if (s != null) { + fData.put(name, s + value); + } else { + fData.put(name, value); + } + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); + if (timeStampInputFormat != null) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + column.format); + } else { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); + } + } + } else if (column.action == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { + String s = fData.get(name); + if (s != null) { + fData.put(name, s + " | " + value); //$NON-NLS-1$ + } else { + fData.put(name, value); + } + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); + if (timeStampInputFormat != null) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + " | " + column.format); //$NON-NLS-1$ + } else { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, column.format); + } + } + } + } + } + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEventType.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEventType.java index 0615ba8621..b2b1eedc10 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEventType.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtEventType.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -public class CustomTxtEventType extends CustomEventType { - - public CustomTxtEventType(CustomTxtTraceDefinition definition) { - super(definition); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +public class CustomTxtEventType extends CustomEventType { + + public CustomTxtEventType(CustomTxtTraceDefinition definition) { + super(definition); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTrace.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTrace.java index c6e731fe1f..4f3ddcc67e 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTrace.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTrace.java @@ -1,348 +1,348 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.regex.Matcher; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; -import org.eclipse.linuxtools.tmf.core.io.BufferedRandomAccessFile; -import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; -import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; -import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfContext; -import org.eclipse.linuxtools.tmf.core.trace.TmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; - -public class CustomTxtTrace extends TmfTrace implements ITmfEventParser { - - private static final TmfLocation NULL_LOCATION = new TmfLocation((Long) null); - private static final int DEFAULT_CACHE_SIZE = 100; - - private final CustomTxtTraceDefinition fDefinition; - private final CustomTxtEventType fEventType; - private BufferedRandomAccessFile fFile; - - public CustomTxtTrace(final CustomTxtTraceDefinition definition) { - fDefinition = definition; - fEventType = new CustomTxtEventType(fDefinition); - setCacheSize(DEFAULT_CACHE_SIZE); - } - - public CustomTxtTrace(final IResource resource, final CustomTxtTraceDefinition definition, final String path, final int cacheSize) throws TmfTraceException { - this(definition); - setCacheSize((cacheSize > 0) ? cacheSize : DEFAULT_CACHE_SIZE); - initTrace(resource, path, CustomTxtEvent.class); - } - - @Override - public void initTrace(final IResource resource, final String path, final Class eventType) throws TmfTraceException { - super.initTrace(resource, path, eventType); - try { - fFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$ - } catch (IOException e) { - throw new TmfTraceException(e.getMessage(), e); - } - indexTrace(false); - } - - @Override - public synchronized void dispose() { - super.dispose(); - if (fFile != null) { - try { - fFile.close(); - } catch (IOException e) { - } finally { - fFile = null; - } - } - } - - @Override - public synchronized TmfContext seekEvent(final ITmfLocation location) { - final CustomTxtTraceContext context = new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - if (NULL_LOCATION.equals(location) || fFile == null) { - return context; - } - try { - if (location == null) { - fFile.seek(0); - } else if (location.getLocation() instanceof Long) { - fFile.seek((Long) location.getLocation()); - } - String line; - long rawPos = fFile.getFilePointer(); - while ((line = fFile.getNextLine()) != null) { - for (final InputLine input : getFirstLines()) { - final Matcher matcher = input.getPattern().matcher(line); - if (matcher.find()) { - context.setLocation(new TmfLocation(rawPos)); - context.firstLineMatcher = matcher; - context.firstLine = line; - context.nextLineLocation = fFile.getFilePointer(); - context.inputLine = input; - return context; - } - } - rawPos = fFile.getFilePointer(); - } - return context; - } catch (final FileNotFoundException e) { - Activator.getDefault().logError("Error seeking event. File not found: " + getPath(), e); //$NON-NLS-1$ - return context; - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - return context; - } - - } - - @Override - public synchronized TmfContext seekEvent(final double ratio) { - if (fFile == null) { - return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - } - try { - long pos = (long) (ratio * fFile.length()); - while (pos > 0) { - fFile.seek(pos - 1); - if (fFile.read() == '\n') { - break; - } - pos--; - } - final ITmfLocation location = new TmfLocation(pos); - final TmfContext context = seekEvent(location); - context.setRank(ITmfContext.UNKNOWN_RANK); - return context; - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - } - } - - @Override - public synchronized double getLocationRatio(final ITmfLocation location) { - if (fFile == null) { - return 0; - } - try { - if (location.getLocation() instanceof Long) { - return (double) ((Long) location.getLocation()) / fFile.length(); - } - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - } - return 0; - } - - @Override - public ITmfLocation getCurrentLocation() { - // TODO Auto-generated method stub - return null; - } - - @Override - public synchronized CustomTxtEvent parseEvent(final ITmfContext tmfContext) { - ITmfContext context = seekEvent(tmfContext.getLocation()); - return parse(context); - } - - @Override - public synchronized CustomTxtEvent getNext(final ITmfContext context) { - final ITmfContext savedContext = context.clone(); - final CustomTxtEvent event = parse(context); - if (event != null) { - updateAttributes(savedContext, event.getTimestamp()); - context.increaseRank(); - } - return event; - } - - private synchronized CustomTxtEvent parse(final ITmfContext tmfContext) { - if (fFile == null) { - return null; - } - if (!(tmfContext instanceof CustomTxtTraceContext)) { - return null; - } - - final CustomTxtTraceContext context = (CustomTxtTraceContext) tmfContext; - if (!(context.getLocation().getLocation() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) { - return null; - } - - CustomTxtEvent event = parseFirstLine(context); - - final HashMap countMap = new HashMap(); - InputLine currentInput = null; - if (context.inputLine.childrenInputs != null && context.inputLine.childrenInputs.size() > 0) { - currentInput = context.inputLine.childrenInputs.get(0); - countMap.put(currentInput, 0); - } - - try { - if (fFile.getFilePointer() != context.nextLineLocation) { - fFile.seek(context.nextLineLocation); - } - String line; - long rawPos = fFile.getFilePointer(); - while ((line = fFile.getNextLine()) != null) { - boolean processed = false; - if (currentInput == null) { - for (final InputLine input : getFirstLines()) { - final Matcher matcher = input.getPattern().matcher(line); - if (matcher.find()) { - context.setLocation(new TmfLocation(rawPos)); - context.firstLineMatcher = matcher; - context.firstLine = line; - context.nextLineLocation = fFile.getFilePointer(); - context.inputLine = input; - return event; - } - } - } else { - if (countMap.get(currentInput) >= currentInput.getMinCount()) { - final List nextInputs = currentInput.getNextInputs(countMap); - if (nextInputs.size() == 0 || nextInputs.get(nextInputs.size() - 1).getMinCount() == 0) { - for (final InputLine input : getFirstLines()) { - final Matcher matcher = input.getPattern().matcher(line); - if (matcher.find()) { - context.setLocation(new TmfLocation(rawPos)); - context.firstLineMatcher = matcher; - context.firstLine = line; - context.nextLineLocation = fFile.getFilePointer(); - context.inputLine = input; - return event; - } - } - } - for (final InputLine input : nextInputs) { - final Matcher matcher = input.getPattern().matcher(line); - if (matcher.find()) { - event.processGroups(input, matcher); - currentInput = input; - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 1); - } else { - countMap.put(currentInput, countMap.get(currentInput) + 1); - } - Iterator iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - final InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { - currentInput = currentInput.childrenInputs.get(0); - countMap.put(currentInput, 0); - } else if (countMap.get(currentInput) >= currentInput.getMaxCount()) { - if (currentInput.getNextInputs(countMap).size() > 0) { - currentInput = currentInput.getNextInputs(countMap).get(0); - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 0); - } - iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - final InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - } else { - currentInput = null; - } - } - processed = true; - break; - } - } - } - if (! processed) { - final Matcher matcher = currentInput.getPattern().matcher(line); - if (matcher.find()) { - event.processGroups(currentInput, matcher); - countMap.put(currentInput, countMap.get(currentInput) + 1); - if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { - currentInput = currentInput.childrenInputs.get(0); - countMap.put(currentInput, 0); - } else if (countMap.get(currentInput) >= currentInput.getMaxCount()) { - if (currentInput.getNextInputs(countMap).size() > 0) { - currentInput = currentInput.getNextInputs(countMap).get(0); - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 0); - } - final Iterator iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - final InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - } else { - currentInput = null; - } - } - } - ((StringBuffer) event.getContent().getValue()).append("\n").append(line); //$NON-NLS-1$ - } - } - rawPos = fFile.getFilePointer(); - } - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - } - for (final Entry entry : countMap.entrySet()) { - if (entry.getValue() < entry.getKey().getMinCount()) { - event = null; - } - } - context.setLocation(NULL_LOCATION); - return event; - } - - public List getFirstLines() { - return fDefinition.inputs; - } - - public CustomTxtEvent parseFirstLine(final CustomTxtTraceContext context) { - final CustomTxtEvent event = new CustomTxtEvent(fDefinition, this, TmfTimestamp.ZERO, "", fEventType, ""); //$NON-NLS-1$ //$NON-NLS-2$ - event.processGroups(context.inputLine, context.firstLineMatcher); - event.setContent(new CustomEventContent(event, new StringBuffer(context.firstLine))); - return event; - } - - public CustomTraceDefinition getDefinition() { - return fDefinition; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#validate(org.eclipse.core.resources.IProject, java.lang.String) - */ - @Override - public boolean validate(IProject project, String path) { - return fileExists(path); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.regex.Matcher; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; +import org.eclipse.linuxtools.tmf.core.io.BufferedRandomAccessFile; +import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; +import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; +import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfContext; +import org.eclipse.linuxtools.tmf.core.trace.TmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; + +public class CustomTxtTrace extends TmfTrace implements ITmfEventParser { + + private static final TmfLocation NULL_LOCATION = new TmfLocation((Long) null); + private static final int DEFAULT_CACHE_SIZE = 100; + + private final CustomTxtTraceDefinition fDefinition; + private final CustomTxtEventType fEventType; + private BufferedRandomAccessFile fFile; + + public CustomTxtTrace(final CustomTxtTraceDefinition definition) { + fDefinition = definition; + fEventType = new CustomTxtEventType(fDefinition); + setCacheSize(DEFAULT_CACHE_SIZE); + } + + public CustomTxtTrace(final IResource resource, final CustomTxtTraceDefinition definition, final String path, final int cacheSize) throws TmfTraceException { + this(definition); + setCacheSize((cacheSize > 0) ? cacheSize : DEFAULT_CACHE_SIZE); + initTrace(resource, path, CustomTxtEvent.class); + } + + @Override + public void initTrace(final IResource resource, final String path, final Class eventType) throws TmfTraceException { + super.initTrace(resource, path, eventType); + try { + fFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$ + } catch (IOException e) { + throw new TmfTraceException(e.getMessage(), e); + } + indexTrace(false); + } + + @Override + public synchronized void dispose() { + super.dispose(); + if (fFile != null) { + try { + fFile.close(); + } catch (IOException e) { + } finally { + fFile = null; + } + } + } + + @Override + public synchronized TmfContext seekEvent(final ITmfLocation location) { + final CustomTxtTraceContext context = new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + if (NULL_LOCATION.equals(location) || fFile == null) { + return context; + } + try { + if (location == null) { + fFile.seek(0); + } else if (location.getLocation() instanceof Long) { + fFile.seek((Long) location.getLocation()); + } + String line; + long rawPos = fFile.getFilePointer(); + while ((line = fFile.getNextLine()) != null) { + for (final InputLine input : getFirstLines()) { + final Matcher matcher = input.getPattern().matcher(line); + if (matcher.find()) { + context.setLocation(new TmfLocation(rawPos)); + context.firstLineMatcher = matcher; + context.firstLine = line; + context.nextLineLocation = fFile.getFilePointer(); + context.inputLine = input; + return context; + } + } + rawPos = fFile.getFilePointer(); + } + return context; + } catch (final FileNotFoundException e) { + Activator.getDefault().logError("Error seeking event. File not found: " + getPath(), e); //$NON-NLS-1$ + return context; + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + return context; + } + + } + + @Override + public synchronized TmfContext seekEvent(final double ratio) { + if (fFile == null) { + return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + } + try { + long pos = (long) (ratio * fFile.length()); + while (pos > 0) { + fFile.seek(pos - 1); + if (fFile.read() == '\n') { + break; + } + pos--; + } + final ITmfLocation location = new TmfLocation(pos); + final TmfContext context = seekEvent(location); + context.setRank(ITmfContext.UNKNOWN_RANK); + return context; + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + } + } + + @Override + public synchronized double getLocationRatio(final ITmfLocation location) { + if (fFile == null) { + return 0; + } + try { + if (location.getLocation() instanceof Long) { + return (double) ((Long) location.getLocation()) / fFile.length(); + } + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + } + return 0; + } + + @Override + public ITmfLocation getCurrentLocation() { + // TODO Auto-generated method stub + return null; + } + + @Override + public synchronized CustomTxtEvent parseEvent(final ITmfContext tmfContext) { + ITmfContext context = seekEvent(tmfContext.getLocation()); + return parse(context); + } + + @Override + public synchronized CustomTxtEvent getNext(final ITmfContext context) { + final ITmfContext savedContext = context.clone(); + final CustomTxtEvent event = parse(context); + if (event != null) { + updateAttributes(savedContext, event.getTimestamp()); + context.increaseRank(); + } + return event; + } + + private synchronized CustomTxtEvent parse(final ITmfContext tmfContext) { + if (fFile == null) { + return null; + } + if (!(tmfContext instanceof CustomTxtTraceContext)) { + return null; + } + + final CustomTxtTraceContext context = (CustomTxtTraceContext) tmfContext; + if (!(context.getLocation().getLocation() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) { + return null; + } + + CustomTxtEvent event = parseFirstLine(context); + + final HashMap countMap = new HashMap(); + InputLine currentInput = null; + if (context.inputLine.childrenInputs != null && context.inputLine.childrenInputs.size() > 0) { + currentInput = context.inputLine.childrenInputs.get(0); + countMap.put(currentInput, 0); + } + + try { + if (fFile.getFilePointer() != context.nextLineLocation) { + fFile.seek(context.nextLineLocation); + } + String line; + long rawPos = fFile.getFilePointer(); + while ((line = fFile.getNextLine()) != null) { + boolean processed = false; + if (currentInput == null) { + for (final InputLine input : getFirstLines()) { + final Matcher matcher = input.getPattern().matcher(line); + if (matcher.find()) { + context.setLocation(new TmfLocation(rawPos)); + context.firstLineMatcher = matcher; + context.firstLine = line; + context.nextLineLocation = fFile.getFilePointer(); + context.inputLine = input; + return event; + } + } + } else { + if (countMap.get(currentInput) >= currentInput.getMinCount()) { + final List nextInputs = currentInput.getNextInputs(countMap); + if (nextInputs.size() == 0 || nextInputs.get(nextInputs.size() - 1).getMinCount() == 0) { + for (final InputLine input : getFirstLines()) { + final Matcher matcher = input.getPattern().matcher(line); + if (matcher.find()) { + context.setLocation(new TmfLocation(rawPos)); + context.firstLineMatcher = matcher; + context.firstLine = line; + context.nextLineLocation = fFile.getFilePointer(); + context.inputLine = input; + return event; + } + } + } + for (final InputLine input : nextInputs) { + final Matcher matcher = input.getPattern().matcher(line); + if (matcher.find()) { + event.processGroups(input, matcher); + currentInput = input; + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 1); + } else { + countMap.put(currentInput, countMap.get(currentInput) + 1); + } + Iterator iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + final InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { + currentInput = currentInput.childrenInputs.get(0); + countMap.put(currentInput, 0); + } else if (countMap.get(currentInput) >= currentInput.getMaxCount()) { + if (currentInput.getNextInputs(countMap).size() > 0) { + currentInput = currentInput.getNextInputs(countMap).get(0); + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 0); + } + iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + final InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + } else { + currentInput = null; + } + } + processed = true; + break; + } + } + } + if (! processed) { + final Matcher matcher = currentInput.getPattern().matcher(line); + if (matcher.find()) { + event.processGroups(currentInput, matcher); + countMap.put(currentInput, countMap.get(currentInput) + 1); + if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { + currentInput = currentInput.childrenInputs.get(0); + countMap.put(currentInput, 0); + } else if (countMap.get(currentInput) >= currentInput.getMaxCount()) { + if (currentInput.getNextInputs(countMap).size() > 0) { + currentInput = currentInput.getNextInputs(countMap).get(0); + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 0); + } + final Iterator iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + final InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + } else { + currentInput = null; + } + } + } + ((StringBuffer) event.getContent().getValue()).append("\n").append(line); //$NON-NLS-1$ + } + } + rawPos = fFile.getFilePointer(); + } + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + } + for (final Entry entry : countMap.entrySet()) { + if (entry.getValue() < entry.getKey().getMinCount()) { + event = null; + } + } + context.setLocation(NULL_LOCATION); + return event; + } + + public List getFirstLines() { + return fDefinition.inputs; + } + + public CustomTxtEvent parseFirstLine(final CustomTxtTraceContext context) { + final CustomTxtEvent event = new CustomTxtEvent(fDefinition, this, TmfTimestamp.ZERO, "", fEventType, ""); //$NON-NLS-1$ //$NON-NLS-2$ + event.processGroups(context.inputLine, context.firstLineMatcher); + event.setContent(new CustomEventContent(event, new StringBuffer(context.firstLine))); + return event; + } + + public CustomTraceDefinition getDefinition() { + return fDefinition; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#validate(org.eclipse.core.resources.IProject, java.lang.String) + */ + @Override + public boolean validate(IProject project, String path) { + return fileExists(path); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceContext.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceContext.java index 89c17ce73e..556bfbd650 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceContext.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceContext.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.util.regex.Matcher; - -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; -import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfContext; - -public class CustomTxtTraceContext extends TmfContext { - public Matcher firstLineMatcher; - public String firstLine; - public long nextLineLocation; - public InputLine inputLine; - - public CustomTxtTraceContext(ITmfLocation location, long rank) { - super(location, rank); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((firstLine == null) ? 0 : firstLine.hashCode()); - result = prime * result + ((firstLineMatcher == null) ? 0 : firstLineMatcher.hashCode()); - result = prime * result + ((inputLine == null) ? 0 : inputLine.hashCode()); - result = prime * result + (int) (nextLineLocation ^ (nextLineLocation >>> 32)); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof CustomTxtTraceContext)) { - return false; - } - CustomTxtTraceContext other = (CustomTxtTraceContext) obj; - if (firstLine == null) { - if (other.firstLine != null) { - return false; - } - } else if (!firstLine.equals(other.firstLine)) { - return false; - } - if (firstLineMatcher == null) { - if (other.firstLineMatcher != null) { - return false; - } - } else if (!firstLineMatcher.equals(other.firstLineMatcher)) { - return false; - } - if (inputLine == null) { - if (other.inputLine != null) { - return false; - } - } else if (!inputLine.equals(other.inputLine)) { - return false; - } - if (nextLineLocation != other.nextLineLocation) { - return false; - } - return true; - } - +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.util.regex.Matcher; + +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; +import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfContext; + +public class CustomTxtTraceContext extends TmfContext { + public Matcher firstLineMatcher; + public String firstLine; + public long nextLineLocation; + public InputLine inputLine; + + public CustomTxtTraceContext(ITmfLocation location, long rank) { + super(location, rank); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((firstLine == null) ? 0 : firstLine.hashCode()); + result = prime * result + ((firstLineMatcher == null) ? 0 : firstLineMatcher.hashCode()); + result = prime * result + ((inputLine == null) ? 0 : inputLine.hashCode()); + result = prime * result + (int) (nextLineLocation ^ (nextLineLocation >>> 32)); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof CustomTxtTraceContext)) { + return false; + } + CustomTxtTraceContext other = (CustomTxtTraceContext) obj; + if (firstLine == null) { + if (other.firstLine != null) { + return false; + } + } else if (!firstLine.equals(other.firstLine)) { + return false; + } + if (firstLineMatcher == null) { + if (other.firstLineMatcher != null) { + return false; + } + } else if (!firstLineMatcher.equals(other.firstLineMatcher)) { + return false; + } + if (inputLine == null) { + if (other.inputLine != null) { + return false; + } + } else if (!inputLine.equals(other.inputLine)) { + return false; + } + if (nextLineLocation != other.nextLineLocation) { + return false; + } + return true; + } + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceDefinition.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceDefinition.java index 8c19d20fc8..f353121d24 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceDefinition.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomTxtTraceDefinition.java @@ -1,672 +1,672 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public class CustomTxtTraceDefinition extends CustomTraceDefinition { - - protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME = "custom_txt_parsers.xml"; //$NON-NLS-1$ - protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME = - Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME).toString(); - - private static final String CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomTxtTraceDefinition_definitionRootElement; - private static final String DEFINITION_ELEMENT = Messages.CustomTxtTraceDefinition_definition; - private static final String NAME_ATTRIBUTE = Messages.CustomTxtTraceDefinition_name; - private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomTxtTraceDefinition_timestampOutputFormat; - private static final String INPUT_LINE_ELEMENT = Messages.CustomTxtTraceDefinition_inputLine; - private static final String CARDINALITY_ELEMENT = Messages.CustomTxtTraceDefinition_cardinality; - private static final String MIN_ATTRIBUTE = Messages.CustomTxtTraceDefinition_min; - private static final String MAX_ATTRIBUTE = Messages.CustomTxtTraceDefinition_max; - private static final String REGEX_ELEMENT = Messages.CustomTxtTraceDefinition_regEx; - private static final String INPUT_DATA_ELEMENT = Messages.CustomTxtTraceDefinition_inputData; - private static final String ACTION_ATTRIBUTE = Messages.CustomTxtTraceDefinition_action; - private static final String FORMAT_ATTRIBUTE = Messages.CustomTxtTraceDefinition_format; - private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomTxtTraceDefinition_outputColumn; - - public List inputs; - - public CustomTxtTraceDefinition() { - this("", new ArrayList(0), new ArrayList(0), ""); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public CustomTxtTraceDefinition(String logtype, List inputs, List outputs, String timeStampOutputFormat) { - this.definitionName = logtype; - this.inputs = inputs; - this.outputs = outputs; - this.timeStampOutputFormat = timeStampOutputFormat; - } - - public static class InputLine { - public List columns; - public Cardinality cardinality; - private String regex; - private Pattern pattern; - public InputLine parentInput; - public int level; - public InputLine nextInput; - public List childrenInputs; - - public InputLine() {} - - public InputLine(Cardinality cardinality, String regex, List columns) { - this.cardinality = cardinality; - this.regex = regex; - this.columns = columns; - } - - public void setRegex(String regex) { - this.regex = regex; - this.pattern = null; - } - - public String getRegex() { - return regex; - } - - public Pattern getPattern() throws PatternSyntaxException { - if (pattern == null) { - pattern = Pattern.compile(regex); - } - return pattern; - } - - public void addChild(InputLine input) { - if (childrenInputs == null) { - childrenInputs = new ArrayList(1); - } else if (childrenInputs.size() > 0) { - InputLine last = childrenInputs.get(childrenInputs.size() - 1); - last.nextInput = input; - } - childrenInputs.add(input); - input.parentInput = this; - input.level = this.level + 1; - } - - public void addNext(InputLine input) { - if (parentInput != null) { - int index = parentInput.childrenInputs.indexOf(this); - parentInput.childrenInputs.add(index + 1, input); - InputLine next = nextInput; - nextInput = input; - input.nextInput = next; - } - input.parentInput = this.parentInput; - input.level = this.level; - } - - public void moveUp() { - if (parentInput != null) { - int index = parentInput.childrenInputs.indexOf(this); - if (index > 0) { - parentInput.childrenInputs.add(index - 1 , parentInput.childrenInputs.remove(index)); - parentInput.childrenInputs.get(index).nextInput = nextInput; - nextInput = parentInput.childrenInputs.get(index); - } - } - } - - public void moveDown() { - if (parentInput != null) { - int index = parentInput.childrenInputs.indexOf(this); - if (index < parentInput.childrenInputs.size() - 1) { - parentInput.childrenInputs.add(index + 1 , parentInput.childrenInputs.remove(index)); - nextInput = parentInput.childrenInputs.get(index).nextInput; - parentInput.childrenInputs.get(index).nextInput = this; - } - } - } - - public void addColumn(InputData column) { - if (columns == null) { - columns = new ArrayList(1); - } - columns.add(column); - } - - public List getNextInputs(Map countMap) { - List nextInputs = new ArrayList(); - InputLine next = nextInput; - while (next != null) { - nextInputs.add(next); - if (next.cardinality.min > 0) { - return nextInputs; - } - next = next.nextInput; - } - if (parentInput != null && parentInput.level > 0) { - int parentCount = countMap.get(parentInput); - if (parentCount < parentInput.getMaxCount()) { - nextInputs.add(parentInput); - } - if (parentCount < parentInput.getMinCount()) { - return nextInputs; - } - nextInputs.addAll(parentInput.getNextInputs(countMap)); - } - return nextInputs; - } - - public int getMinCount() { - return cardinality.min; - } - - public int getMaxCount() { - return cardinality.max; - } - - @Override - public String toString() { - return regex + " " + cardinality; //$NON-NLS-1$ - } - - } - - public static class InputData { - public String name; - public int action; - public String format; - - public InputData() {} - - public InputData(String name, int action, String format) { - this.name = name; - this.action = action; - this.format = format; - } - - public InputData(String name, int action) { - this.name = name; - this.action = action; - } - } - - public static class Cardinality { - public final static int INF = Integer.MAX_VALUE; - public final static Cardinality ONE = new Cardinality(1, 1); - public final static Cardinality ONE_OR_MORE = new Cardinality(1, INF); - public final static Cardinality ZERO_OR_ONE = new Cardinality(0, 1); - public final static Cardinality ZERO_OR_MORE = new Cardinality(0, INF); - - private final int min; - private final int max; - - public Cardinality(int min, int max) { - this.min = min; - this.max = max; - } - - @Override - public String toString() { - return "(" + (min >= 0 ? min : "?") + "," + (max == INF ? "\u221E" : (max >= 0 ? max : "?")) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + max; - result = prime * result + min; - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof Cardinality)) { - return false; - } - Cardinality other = (Cardinality) obj; - return (this.min == other.min && this.max == other.max); - } - } - - @Override - public void save() { - save(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); - } - - @Override - public void save(String path) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - Document doc = null; - File file = new File(path); - if (file.canRead()) { - doc = db.parse(file); - if (! doc.getDocumentElement().getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { - return; - } - } else { - doc = db.newDocument(); - Node node = doc.createElement(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT); - doc.appendChild(node); - } - - Element root = doc.getDocumentElement(); - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - root.removeChild(node); - } - } - Element definitionElement = doc.createElement(DEFINITION_ELEMENT); - root.appendChild(definitionElement); - definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName); - - Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT); - definitionElement.appendChild(formatElement); - formatElement.appendChild(doc.createTextNode(timeStampOutputFormat)); - - if (inputs != null) { - for (InputLine inputLine : inputs) { - definitionElement.appendChild(createInputLineElement(inputLine, doc)); - } - } - - if (outputs != null) { - for (OutputColumn output : outputs) { - Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT); - definitionElement.appendChild(outputColumnElement); - outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name); - } - } - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ - - //initialize StreamResult with File object to save to file - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(doc); - transformer.transform(source, result); - String xmlString = result.getWriter().toString(); - - FileWriter writer = new FileWriter(file); - writer.write(xmlString); - writer.close(); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerConfigurationException e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerFactoryConfigurationError e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerException e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } - } - - private Element createInputLineElement(InputLine inputLine, Document doc) { - Element inputLineElement = doc.createElement(INPUT_LINE_ELEMENT); - - Element cardinalityElement = doc.createElement(CARDINALITY_ELEMENT); - inputLineElement.appendChild(cardinalityElement); - cardinalityElement.setAttribute(MIN_ATTRIBUTE, Integer.toString(inputLine.cardinality.min)); - cardinalityElement.setAttribute(MAX_ATTRIBUTE, Integer.toString(inputLine.cardinality.max)); - - Element regexElement = doc.createElement(REGEX_ELEMENT); - inputLineElement.appendChild(regexElement); - regexElement.appendChild(doc.createTextNode(inputLine.regex)); - - if (inputLine.columns != null) { - for (InputData inputData : inputLine.columns) { - Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); - inputLineElement.appendChild(inputDataElement); - inputDataElement.setAttribute(NAME_ATTRIBUTE, inputData.name); - inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputData.action)); - if (inputData.format != null) { - inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputData.format); - } - } - } - - if (inputLine.childrenInputs != null) { - for (InputLine childInputLine : inputLine.childrenInputs) { - inputLineElement.appendChild(createInputLineElement(childInputLine, doc)); - } - } - - return inputLineElement; - } - - public static CustomTxtTraceDefinition[] loadAll() { - return loadAll(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); - } - - public static CustomTxtTraceDefinition[] loadAll(String path) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(path); - if (!file.canRead()) { - return new CustomTxtTraceDefinition[0]; - } - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { - return new CustomTxtTraceDefinition[0]; - } - - ArrayList defList = new ArrayList(); - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) { - CustomTxtTraceDefinition def = extractDefinition((Element) node); - if (def != null) { - defList.add(def); - } - } - } - return defList.toArray(new CustomTxtTraceDefinition[0]); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } - return new CustomTxtTraceDefinition[0]; - } - - public static CustomTxtTraceDefinition load(String definitionName) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { - return null; - } - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - return extractDefinition((Element) node); - } - } - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } - return null; - } - - public static CustomTxtTraceDefinition extractDefinition(Element definitionElement) { - CustomTxtTraceDefinition def = new CustomTxtTraceDefinition(); - - def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE); - if (def.definitionName == null) { - return null; - } - - NodeList nodeList = definitionElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String nodeName = node.getNodeName(); - if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) { - Element formatElement = (Element) node; - def.timeStampOutputFormat = formatElement.getTextContent(); - } else if (nodeName.equals(INPUT_LINE_ELEMENT)) { - InputLine inputLine = extractInputLine((Element) node); - if (inputLine != null) { - def.inputs.add(inputLine); - } - } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) { - Element outputColumnElement = (Element) node; - OutputColumn outputColumn = new OutputColumn(); - outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE); - def.outputs.add(outputColumn); - } - } - return def; - } - - private static InputLine extractInputLine(Element inputLineElement) { - InputLine inputLine = new InputLine(); - NodeList nodeList = inputLineElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String nodeName = node.getNodeName(); - if (nodeName.equals(CARDINALITY_ELEMENT)) { - Element cardinalityElement = (Element) node; - try { - int min = Integer.parseInt(cardinalityElement.getAttribute(MIN_ATTRIBUTE)); - int max = Integer.parseInt(cardinalityElement.getAttribute(MAX_ATTRIBUTE)); - inputLine.cardinality = new Cardinality(min, max); - } catch (NumberFormatException e) { - return null; - } - } else if (nodeName.equals(REGEX_ELEMENT)) { - Element regexElement = (Element) node; - inputLine.regex = regexElement.getTextContent(); - } else if (nodeName.equals(INPUT_DATA_ELEMENT)) { - Element inputDataElement = (Element) node; - InputData inputData = new InputData(); - inputData.name = inputDataElement.getAttribute(NAME_ATTRIBUTE); - inputData.action = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); - inputData.format = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); - inputLine.addColumn(inputData); - } else if (nodeName.equals(INPUT_LINE_ELEMENT)) { - Element childInputLineElement = (Element) node; - InputLine childInputLine = extractInputLine(childInputLineElement); - if (childInputLine != null) { - inputLine.addChild(childInputLine); - } - } - } - return inputLine; - } - - public static void delete(String definitionName) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { - return; - } - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - root.removeChild(node); - } - } - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ - - //initialize StreamResult with File object to save to file - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(doc); - transformer.transform(source, result); - String xmlString = result.getWriter().toString(); - - FileWriter writer = new FileWriter(file); - writer.write(xmlString); - writer.close(); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ - } catch (TransformerConfigurationException e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ - } catch (TransformerFactoryConfigurationError e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ - } catch (TransformerException e) { - Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ - } - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class CustomTxtTraceDefinition extends CustomTraceDefinition { + + protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME = "custom_txt_parsers.xml"; //$NON-NLS-1$ + protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME = + Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME).toString(); + + private static final String CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomTxtTraceDefinition_definitionRootElement; + private static final String DEFINITION_ELEMENT = Messages.CustomTxtTraceDefinition_definition; + private static final String NAME_ATTRIBUTE = Messages.CustomTxtTraceDefinition_name; + private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomTxtTraceDefinition_timestampOutputFormat; + private static final String INPUT_LINE_ELEMENT = Messages.CustomTxtTraceDefinition_inputLine; + private static final String CARDINALITY_ELEMENT = Messages.CustomTxtTraceDefinition_cardinality; + private static final String MIN_ATTRIBUTE = Messages.CustomTxtTraceDefinition_min; + private static final String MAX_ATTRIBUTE = Messages.CustomTxtTraceDefinition_max; + private static final String REGEX_ELEMENT = Messages.CustomTxtTraceDefinition_regEx; + private static final String INPUT_DATA_ELEMENT = Messages.CustomTxtTraceDefinition_inputData; + private static final String ACTION_ATTRIBUTE = Messages.CustomTxtTraceDefinition_action; + private static final String FORMAT_ATTRIBUTE = Messages.CustomTxtTraceDefinition_format; + private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomTxtTraceDefinition_outputColumn; + + public List inputs; + + public CustomTxtTraceDefinition() { + this("", new ArrayList(0), new ArrayList(0), ""); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public CustomTxtTraceDefinition(String logtype, List inputs, List outputs, String timeStampOutputFormat) { + this.definitionName = logtype; + this.inputs = inputs; + this.outputs = outputs; + this.timeStampOutputFormat = timeStampOutputFormat; + } + + public static class InputLine { + public List columns; + public Cardinality cardinality; + private String regex; + private Pattern pattern; + public InputLine parentInput; + public int level; + public InputLine nextInput; + public List childrenInputs; + + public InputLine() {} + + public InputLine(Cardinality cardinality, String regex, List columns) { + this.cardinality = cardinality; + this.regex = regex; + this.columns = columns; + } + + public void setRegex(String regex) { + this.regex = regex; + this.pattern = null; + } + + public String getRegex() { + return regex; + } + + public Pattern getPattern() throws PatternSyntaxException { + if (pattern == null) { + pattern = Pattern.compile(regex); + } + return pattern; + } + + public void addChild(InputLine input) { + if (childrenInputs == null) { + childrenInputs = new ArrayList(1); + } else if (childrenInputs.size() > 0) { + InputLine last = childrenInputs.get(childrenInputs.size() - 1); + last.nextInput = input; + } + childrenInputs.add(input); + input.parentInput = this; + input.level = this.level + 1; + } + + public void addNext(InputLine input) { + if (parentInput != null) { + int index = parentInput.childrenInputs.indexOf(this); + parentInput.childrenInputs.add(index + 1, input); + InputLine next = nextInput; + nextInput = input; + input.nextInput = next; + } + input.parentInput = this.parentInput; + input.level = this.level; + } + + public void moveUp() { + if (parentInput != null) { + int index = parentInput.childrenInputs.indexOf(this); + if (index > 0) { + parentInput.childrenInputs.add(index - 1 , parentInput.childrenInputs.remove(index)); + parentInput.childrenInputs.get(index).nextInput = nextInput; + nextInput = parentInput.childrenInputs.get(index); + } + } + } + + public void moveDown() { + if (parentInput != null) { + int index = parentInput.childrenInputs.indexOf(this); + if (index < parentInput.childrenInputs.size() - 1) { + parentInput.childrenInputs.add(index + 1 , parentInput.childrenInputs.remove(index)); + nextInput = parentInput.childrenInputs.get(index).nextInput; + parentInput.childrenInputs.get(index).nextInput = this; + } + } + } + + public void addColumn(InputData column) { + if (columns == null) { + columns = new ArrayList(1); + } + columns.add(column); + } + + public List getNextInputs(Map countMap) { + List nextInputs = new ArrayList(); + InputLine next = nextInput; + while (next != null) { + nextInputs.add(next); + if (next.cardinality.min > 0) { + return nextInputs; + } + next = next.nextInput; + } + if (parentInput != null && parentInput.level > 0) { + int parentCount = countMap.get(parentInput); + if (parentCount < parentInput.getMaxCount()) { + nextInputs.add(parentInput); + } + if (parentCount < parentInput.getMinCount()) { + return nextInputs; + } + nextInputs.addAll(parentInput.getNextInputs(countMap)); + } + return nextInputs; + } + + public int getMinCount() { + return cardinality.min; + } + + public int getMaxCount() { + return cardinality.max; + } + + @Override + public String toString() { + return regex + " " + cardinality; //$NON-NLS-1$ + } + + } + + public static class InputData { + public String name; + public int action; + public String format; + + public InputData() {} + + public InputData(String name, int action, String format) { + this.name = name; + this.action = action; + this.format = format; + } + + public InputData(String name, int action) { + this.name = name; + this.action = action; + } + } + + public static class Cardinality { + public final static int INF = Integer.MAX_VALUE; + public final static Cardinality ONE = new Cardinality(1, 1); + public final static Cardinality ONE_OR_MORE = new Cardinality(1, INF); + public final static Cardinality ZERO_OR_ONE = new Cardinality(0, 1); + public final static Cardinality ZERO_OR_MORE = new Cardinality(0, INF); + + private final int min; + private final int max; + + public Cardinality(int min, int max) { + this.min = min; + this.max = max; + } + + @Override + public String toString() { + return "(" + (min >= 0 ? min : "?") + "," + (max == INF ? "\u221E" : (max >= 0 ? max : "?")) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + max; + result = prime * result + min; + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Cardinality)) { + return false; + } + Cardinality other = (Cardinality) obj; + return (this.min == other.min && this.max == other.max); + } + } + + @Override + public void save() { + save(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); + } + + @Override + public void save(String path) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + Document doc = null; + File file = new File(path); + if (file.canRead()) { + doc = db.parse(file); + if (! doc.getDocumentElement().getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { + return; + } + } else { + doc = db.newDocument(); + Node node = doc.createElement(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT); + doc.appendChild(node); + } + + Element root = doc.getDocumentElement(); + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + root.removeChild(node); + } + } + Element definitionElement = doc.createElement(DEFINITION_ELEMENT); + root.appendChild(definitionElement); + definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName); + + Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT); + definitionElement.appendChild(formatElement); + formatElement.appendChild(doc.createTextNode(timeStampOutputFormat)); + + if (inputs != null) { + for (InputLine inputLine : inputs) { + definitionElement.appendChild(createInputLineElement(inputLine, doc)); + } + } + + if (outputs != null) { + for (OutputColumn output : outputs) { + Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT); + definitionElement.appendChild(outputColumnElement); + outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name); + } + } + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + + //initialize StreamResult with File object to save to file + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + String xmlString = result.getWriter().toString(); + + FileWriter writer = new FileWriter(file); + writer.write(xmlString); + writer.close(); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerConfigurationException e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerFactoryConfigurationError e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerException e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } + } + + private Element createInputLineElement(InputLine inputLine, Document doc) { + Element inputLineElement = doc.createElement(INPUT_LINE_ELEMENT); + + Element cardinalityElement = doc.createElement(CARDINALITY_ELEMENT); + inputLineElement.appendChild(cardinalityElement); + cardinalityElement.setAttribute(MIN_ATTRIBUTE, Integer.toString(inputLine.cardinality.min)); + cardinalityElement.setAttribute(MAX_ATTRIBUTE, Integer.toString(inputLine.cardinality.max)); + + Element regexElement = doc.createElement(REGEX_ELEMENT); + inputLineElement.appendChild(regexElement); + regexElement.appendChild(doc.createTextNode(inputLine.regex)); + + if (inputLine.columns != null) { + for (InputData inputData : inputLine.columns) { + Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); + inputLineElement.appendChild(inputDataElement); + inputDataElement.setAttribute(NAME_ATTRIBUTE, inputData.name); + inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputData.action)); + if (inputData.format != null) { + inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputData.format); + } + } + } + + if (inputLine.childrenInputs != null) { + for (InputLine childInputLine : inputLine.childrenInputs) { + inputLineElement.appendChild(createInputLineElement(childInputLine, doc)); + } + } + + return inputLineElement; + } + + public static CustomTxtTraceDefinition[] loadAll() { + return loadAll(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); + } + + public static CustomTxtTraceDefinition[] loadAll(String path) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(path); + if (!file.canRead()) { + return new CustomTxtTraceDefinition[0]; + } + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { + return new CustomTxtTraceDefinition[0]; + } + + ArrayList defList = new ArrayList(); + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) { + CustomTxtTraceDefinition def = extractDefinition((Element) node); + if (def != null) { + defList.add(def); + } + } + } + return defList.toArray(new CustomTxtTraceDefinition[0]); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } + return new CustomTxtTraceDefinition[0]; + } + + public static CustomTxtTraceDefinition load(String definitionName) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { + return null; + } + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + return extractDefinition((Element) node); + } + } + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } + return null; + } + + public static CustomTxtTraceDefinition extractDefinition(Element definitionElement) { + CustomTxtTraceDefinition def = new CustomTxtTraceDefinition(); + + def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE); + if (def.definitionName == null) { + return null; + } + + NodeList nodeList = definitionElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String nodeName = node.getNodeName(); + if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) { + Element formatElement = (Element) node; + def.timeStampOutputFormat = formatElement.getTextContent(); + } else if (nodeName.equals(INPUT_LINE_ELEMENT)) { + InputLine inputLine = extractInputLine((Element) node); + if (inputLine != null) { + def.inputs.add(inputLine); + } + } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) { + Element outputColumnElement = (Element) node; + OutputColumn outputColumn = new OutputColumn(); + outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE); + def.outputs.add(outputColumn); + } + } + return def; + } + + private static InputLine extractInputLine(Element inputLineElement) { + InputLine inputLine = new InputLine(); + NodeList nodeList = inputLineElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String nodeName = node.getNodeName(); + if (nodeName.equals(CARDINALITY_ELEMENT)) { + Element cardinalityElement = (Element) node; + try { + int min = Integer.parseInt(cardinalityElement.getAttribute(MIN_ATTRIBUTE)); + int max = Integer.parseInt(cardinalityElement.getAttribute(MAX_ATTRIBUTE)); + inputLine.cardinality = new Cardinality(min, max); + } catch (NumberFormatException e) { + return null; + } + } else if (nodeName.equals(REGEX_ELEMENT)) { + Element regexElement = (Element) node; + inputLine.regex = regexElement.getTextContent(); + } else if (nodeName.equals(INPUT_DATA_ELEMENT)) { + Element inputDataElement = (Element) node; + InputData inputData = new InputData(); + inputData.name = inputDataElement.getAttribute(NAME_ATTRIBUTE); + inputData.action = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); + inputData.format = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); + inputLine.addColumn(inputData); + } else if (nodeName.equals(INPUT_LINE_ELEMENT)) { + Element childInputLineElement = (Element) node; + InputLine childInputLine = extractInputLine(childInputLineElement); + if (childInputLine != null) { + inputLine.addChild(childInputLine); + } + } + } + return inputLine; + } + + public static void delete(String definitionName) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) { + return; + } + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + root.removeChild(node); + } + } + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + + //initialize StreamResult with File object to save to file + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + String xmlString = result.getWriter().toString(); + + FileWriter writer = new FileWriter(file); + writer.write(xmlString); + writer.close(); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ + } catch (TransformerConfigurationException e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ + } catch (TransformerFactoryConfigurationError e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ + } catch (TransformerException e) { + Activator.getDefault().logError("Error deleting CustomTxtTraceDefinition: definitionName= " + definitionName, e); //$NON-NLS-1$ + } + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEvent.java index 04704d64d8..ac9eb0ce6d 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEvent.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; -import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; -import org.eclipse.linuxtools.tmf.core.event.TmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEventType; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -public class CustomXmlEvent extends CustomEvent { - - public CustomXmlEvent(CustomXmlTraceDefinition definition) { - super(definition); - setType(new CustomXmlEventType(definition)); - } - - public CustomXmlEvent(CustomXmlTraceDefinition definition, TmfEvent other) { - super(definition, other); - } - - public CustomXmlEvent(CustomXmlTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { - super(definition, parentTrace, timestamp, source, type, reference); - } - - @Override - public void setContent(ITmfEventField content) { - super.setContent(content); - } - - public void parseInput(String value, String name, int inputAction, String inputFormat) { - if (value.length() == 0) { - return; - } - if (inputAction == CustomTraceDefinition.ACTION_SET) { - fData.put(name, value); - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); - } - } else if (inputAction == CustomTraceDefinition.ACTION_APPEND) { - String s = fData.get(name); - if (s != null) { - fData.put(name, s + value); - } else { - fData.put(name, value); - } - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); - if (timeStampInputFormat != null) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + inputFormat); - } else { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); - } - } - } else if (inputAction == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { - String s = fData.get(name); - if (s != null) { - fData.put(name, s + " | " + value); //$NON-NLS-1$ - } else { - fData.put(name, value); - } - if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); - if (timeStampInputFormat != null) { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + " | " + inputFormat); //$NON-NLS-1$ - } else { - fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); - } - } - } - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; +import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; +import org.eclipse.linuxtools.tmf.core.event.TmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEventType; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +public class CustomXmlEvent extends CustomEvent { + + public CustomXmlEvent(CustomXmlTraceDefinition definition) { + super(definition); + setType(new CustomXmlEventType(definition)); + } + + public CustomXmlEvent(CustomXmlTraceDefinition definition, TmfEvent other) { + super(definition, other); + } + + public CustomXmlEvent(CustomXmlTraceDefinition definition, ITmfTrace parentTrace, ITmfTimestamp timestamp, String source, TmfEventType type, String reference) { + super(definition, parentTrace, timestamp, source, type, reference); + } + + @Override + public void setContent(ITmfEventField content) { + super.setContent(content); + } + + public void parseInput(String value, String name, int inputAction, String inputFormat) { + if (value.length() == 0) { + return; + } + if (inputAction == CustomTraceDefinition.ACTION_SET) { + fData.put(name, value); + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); + } + } else if (inputAction == CustomTraceDefinition.ACTION_APPEND) { + String s = fData.get(name); + if (s != null) { + fData.put(name, s + value); + } else { + fData.put(name, value); + } + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); + if (timeStampInputFormat != null) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + inputFormat); + } else { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); + } + } + } else if (inputAction == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { + String s = fData.get(name); + if (s != null) { + fData.put(name, s + " | " + value); //$NON-NLS-1$ + } else { + fData.put(name, value); + } + if (name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); + if (timeStampInputFormat != null) { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, timeStampInputFormat + " | " + inputFormat); //$NON-NLS-1$ + } else { + fData.put(TIMESTAMP_INPUT_FORMAT_KEY, inputFormat); + } + } + } + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEventType.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEventType.java index d4e8b6636d..5c86752dec 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEventType.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlEventType.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -public class CustomXmlEventType extends CustomEventType { - - public CustomXmlEventType(CustomXmlTraceDefinition definition) { - super(definition); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +public class CustomXmlEventType extends CustomEventType { + + public CustomXmlEventType(CustomXmlTraceDefinition definition) { + super(definition); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTrace.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTrace.java index fb13a4c0cf..418487c308 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTrace.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTrace.java @@ -1,436 +1,436 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.RandomAccessFile; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputAttribute; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputElement; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; -import org.eclipse.linuxtools.tmf.core.io.BufferedRandomAccessFile; -import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; -import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; -import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfContext; -import org.eclipse.linuxtools.tmf.core.trace.TmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public class CustomXmlTrace extends TmfTrace implements ITmfEventParser { - - private static final TmfLocation NULL_LOCATION = new TmfLocation((Long) null); - private static final int DEFAULT_CACHE_SIZE = 100; - - private final CustomXmlTraceDefinition fDefinition; - private final CustomXmlEventType fEventType; - private final InputElement fRecordInputElement; - private BufferedRandomAccessFile fFile; - - public CustomXmlTrace(final CustomXmlTraceDefinition definition) { - fDefinition = definition; - fEventType = new CustomXmlEventType(fDefinition); - fRecordInputElement = getRecordInputElement(fDefinition.rootInputElement); - setCacheSize(DEFAULT_CACHE_SIZE); - } - - public CustomXmlTrace(final IResource resource, final CustomXmlTraceDefinition definition, final String path, final int pageSize) throws TmfTraceException { - this(definition); - setCacheSize((pageSize > 0) ? pageSize : DEFAULT_CACHE_SIZE); - initTrace(resource, path, CustomXmlEvent.class); - } - - @Override - public void initTrace(final IResource resource, final String path, final Class eventType) throws TmfTraceException { - super.initTrace(resource, path, eventType); - try { - fFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$ - } catch (IOException e) { - throw new TmfTraceException(e.getMessage(), e); - } - indexTrace(false); - } - - @Override - public synchronized void dispose() { - super.dispose(); - if (fFile != null) { - try { - fFile.close(); - } catch (IOException e) { - } finally { - fFile = null; - } - } - } - - @Override - public synchronized TmfContext seekEvent(final ITmfLocation location) { - final CustomXmlTraceContext context = new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - if (NULL_LOCATION.equals(location) || fFile == null) { - return context; - } - try { - if (location == null) { - fFile.seek(0); - } else if (location.getLocation() instanceof Long) { - fFile.seek((Long) location.getLocation()); - } - String line; - final String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$ - long rawPos = fFile.getFilePointer(); - - while ((line = fFile.getNextLine()) != null) { - final int idx = line.indexOf(recordElementStart); - if (idx != -1) { - context.setLocation(new TmfLocation(rawPos + idx)); - return context; - } - rawPos = fFile.getFilePointer(); - } - return context; - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - return context; - } - - } - - @Override - public synchronized TmfContext seekEvent(final double ratio) { - if (fFile == null) { - return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - } - try { - long pos = (long) (ratio * fFile.length()); - while (pos > 0) { - fFile.seek(pos - 1); - if (fFile.read() == '\n') { - break; - } - pos--; - } - final ITmfLocation location = new TmfLocation(pos); - final TmfContext context = seekEvent(location); - context.setRank(ITmfContext.UNKNOWN_RANK); - return context; - } catch (final IOException e) { - Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ - return new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); - } - } - - @Override - public synchronized double getLocationRatio(final ITmfLocation location) { - if (fFile == null) { - return 0; - } - try { - if (location.getLocation() instanceof Long) { - return (double) ((Long) location.getLocation()) / fFile.length(); - } - } catch (final IOException e) { - Activator.getDefault().logError("Error getting location ration. File: " + getPath(), e); //$NON-NLS-1$ - } - return 0; - } - - @Override - public ITmfLocation getCurrentLocation() { - // TODO Auto-generated method stub - return null; - } - - @Override - public synchronized CustomXmlEvent parseEvent(final ITmfContext tmfContext) { - ITmfContext context = seekEvent(tmfContext.getLocation()); - return parse(context); - } - - @Override - public synchronized CustomXmlEvent getNext(final ITmfContext context) { - final ITmfContext savedContext = context.clone(); - final CustomXmlEvent event = parse(context); - if (event != null) { - updateAttributes(savedContext, event.getTimestamp()); - context.increaseRank(); - } - return event; - } - - private synchronized CustomXmlEvent parse(final ITmfContext tmfContext) { - if (fFile == null) { - return null; - } - if (!(tmfContext instanceof CustomXmlTraceContext)) { - return null; - } - - final CustomXmlTraceContext context = (CustomXmlTraceContext) tmfContext; - if (!(context.getLocation().getLocation() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) { - return null; - } - - CustomXmlEvent event = null; - try { - if (fFile.getFilePointer() != (Long)context.getLocation().getLocation() + 1) - { - fFile.seek((Long)context.getLocation().getLocation() + 1); // +1 is for the < - } - final StringBuffer elementBuffer = new StringBuffer("<"); //$NON-NLS-1$ - readElement(elementBuffer, fFile); - final Element element = parseElementBuffer(elementBuffer); - - event = extractEvent(element, fRecordInputElement); - ((StringBuffer) event.getContent().getValue()).append(elementBuffer); - - String line; - final String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$ - long rawPos = fFile.getFilePointer(); - - while ((line = fFile.getNextLine()) != null) { - final int idx = line.indexOf(recordElementStart); - if (idx != -1) { - context.setLocation(new TmfLocation(rawPos + idx)); - return event; - } - rawPos = fFile.getFilePointer(); - } - } catch (final IOException e) { - Activator.getDefault().logError("Error parsing event. File: " + getPath(), e); //$NON-NLS-1$ - - } - context.setLocation(NULL_LOCATION); - return event; - } - - private Element parseElementBuffer(final StringBuffer elementBuffer) { - try { - final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - final DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - final EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (final String publicId, final String systemId) { - final String empty = ""; //$NON-NLS-1$ - final ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(final SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(final SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(final SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - final Document doc = db.parse(new ByteArrayInputStream(elementBuffer.toString().getBytes())); - return doc.getDocumentElement(); - } catch (final ParserConfigurationException e) { - Activator.getDefault().logError("Error parsing element buffer. File:" + getPath(), e); //$NON-NLS-1$ - } catch (final SAXException e) { - Activator.getDefault().logError("Error parsing element buffer. File:" + getPath(), e); //$NON-NLS-1$ - } catch (final IOException e) { - Activator.getDefault().logError("Error parsing element buffer. File: " + getPath(), e); //$NON-NLS-1$ - } - return null; - } - - private void readElement(final StringBuffer buffer, final RandomAccessFile raFile) { - try { - int numRead = 0; - boolean startTagClosed = false; - int i; - while ((i = raFile.read()) != -1) { - numRead++; - final char c = (char)i; - buffer.append(c); - if (c == '"') { - readQuote(buffer, raFile, '"'); - } else if (c == '\'') { - readQuote(buffer, raFile, '\''); - } else if (c == '<') { - readElement(buffer, raFile); - } else if (c == '/' && numRead == 1) { - break; // found "') { - if (buffer.charAt(buffer.length() - 2) == '/') { - break; // found "/>" - } else if (startTagClosed) { - break; // found "<...>..." - } - else { - startTagClosed = true; // found "<...>" - } - } - } - return; - } catch (final IOException e) { - return; - } - } - - private static void readQuote(final StringBuffer buffer, - final RandomAccessFile raFile, final char eq) { - try { - int i; - while ((i = raFile.read()) != -1) { - final char c = (char)i; - buffer.append(c); - if (c == eq) - { - break; // found matching end-quote - } - } - return; - } catch (final IOException e) { - return; - } - } - - private static void readComment(final StringBuffer buffer, - final RandomAccessFile raFile) { - try { - int numRead = 0; - int i; - while ((i = raFile.read()) != -1) { - numRead++; - final char c = (char)i; - buffer.append(c); - if (c == '>' && numRead >= 2 && buffer.substring(buffer.length() - 3, buffer.length() - 1).equals("--")) //$NON-NLS-1$ - { - break; // found "-->" - } - } - return; - } catch (final IOException e) { - return; - } - } - - public static StringBuffer parseElement(final Element parentElement, final StringBuffer buffer) { - final NodeList nodeList = parentElement.getChildNodes(); - String separator = null; - for (int i = 0; i < nodeList.getLength(); i++) { - final Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (separator == null) { - separator = " | "; //$NON-NLS-1$ - } else { - buffer.append(separator); - } - final Element element = (Element) node; - if (!element.hasChildNodes()) { - buffer.append(element.getNodeName()); - } else if (element.getChildNodes().getLength() == 1 && element.getFirstChild().getNodeType() == Node.TEXT_NODE) { - buffer.append(element.getNodeName() + ":" + element.getFirstChild().getNodeValue().trim()); //$NON-NLS-1$ - } else { - buffer.append(element.getNodeName()); - buffer.append(" [ "); //$NON-NLS-1$ - parseElement(element, buffer); - buffer.append(" ]"); //$NON-NLS-1$ - } - } else if (node.getNodeType() == Node.TEXT_NODE) { - if (node.getNodeValue().trim().length() != 0) { - buffer.append(node.getNodeValue().trim()); - } - } - } - return buffer; - } - - public InputElement getRecordInputElement(final InputElement inputElement) { - if (inputElement.logEntry) { - return inputElement; - } else if (inputElement.childElements != null) { - for (final InputElement childInputElement : inputElement.childElements) { - final InputElement recordInputElement = getRecordInputElement(childInputElement); - if (recordInputElement != null) { - return recordInputElement; - } - } - } - return null; - } - - public CustomXmlEvent extractEvent(final Element element, final InputElement inputElement) { - final CustomXmlEvent event = new CustomXmlEvent(fDefinition, this, TmfTimestamp.ZERO, "", fEventType,""); //$NON-NLS-1$ //$NON-NLS-2$ - event.setContent(new CustomEventContent(event, new StringBuffer())); - parseElement(element, event, inputElement); - return event; - } - - private void parseElement(final Element element, final CustomXmlEvent event, final InputElement inputElement) { - if (inputElement.inputName != null && !inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { - event.parseInput(parseElement(element, new StringBuffer()).toString(), inputElement.inputName, inputElement.inputAction, inputElement.inputFormat); - } - if (inputElement.attributes != null) { - for (final InputAttribute attribute : inputElement.attributes) { - event.parseInput(element.getAttribute(attribute.attributeName), attribute.inputName, attribute.inputAction, attribute.inputFormat); - } - } - final NodeList childNodes = element.getChildNodes(); - if (inputElement.childElements != null) { - for (int i = 0; i < childNodes.getLength(); i++) { - final Node node = childNodes.item(i); - if (node instanceof Element) { - for (final InputElement child : inputElement.childElements) { - if (node.getNodeName().equals(child.elementName)) { - parseElement((Element) node, event, child); - break; - } - } - } - } - } - return; - } - - public CustomTraceDefinition getDefinition() { - return fDefinition; - } - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#validate(org.eclipse.core.resources.IProject, java.lang.String) - */ - @Override - public boolean validate(IProject project, String path) { - return fileExists(path); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.RandomAccessFile; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputAttribute; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputElement; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; +import org.eclipse.linuxtools.tmf.core.io.BufferedRandomAccessFile; +import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; +import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; +import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfContext; +import org.eclipse.linuxtools.tmf.core.trace.TmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class CustomXmlTrace extends TmfTrace implements ITmfEventParser { + + private static final TmfLocation NULL_LOCATION = new TmfLocation((Long) null); + private static final int DEFAULT_CACHE_SIZE = 100; + + private final CustomXmlTraceDefinition fDefinition; + private final CustomXmlEventType fEventType; + private final InputElement fRecordInputElement; + private BufferedRandomAccessFile fFile; + + public CustomXmlTrace(final CustomXmlTraceDefinition definition) { + fDefinition = definition; + fEventType = new CustomXmlEventType(fDefinition); + fRecordInputElement = getRecordInputElement(fDefinition.rootInputElement); + setCacheSize(DEFAULT_CACHE_SIZE); + } + + public CustomXmlTrace(final IResource resource, final CustomXmlTraceDefinition definition, final String path, final int pageSize) throws TmfTraceException { + this(definition); + setCacheSize((pageSize > 0) ? pageSize : DEFAULT_CACHE_SIZE); + initTrace(resource, path, CustomXmlEvent.class); + } + + @Override + public void initTrace(final IResource resource, final String path, final Class eventType) throws TmfTraceException { + super.initTrace(resource, path, eventType); + try { + fFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$ + } catch (IOException e) { + throw new TmfTraceException(e.getMessage(), e); + } + indexTrace(false); + } + + @Override + public synchronized void dispose() { + super.dispose(); + if (fFile != null) { + try { + fFile.close(); + } catch (IOException e) { + } finally { + fFile = null; + } + } + } + + @Override + public synchronized TmfContext seekEvent(final ITmfLocation location) { + final CustomXmlTraceContext context = new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + if (NULL_LOCATION.equals(location) || fFile == null) { + return context; + } + try { + if (location == null) { + fFile.seek(0); + } else if (location.getLocation() instanceof Long) { + fFile.seek((Long) location.getLocation()); + } + String line; + final String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$ + long rawPos = fFile.getFilePointer(); + + while ((line = fFile.getNextLine()) != null) { + final int idx = line.indexOf(recordElementStart); + if (idx != -1) { + context.setLocation(new TmfLocation(rawPos + idx)); + return context; + } + rawPos = fFile.getFilePointer(); + } + return context; + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + return context; + } + + } + + @Override + public synchronized TmfContext seekEvent(final double ratio) { + if (fFile == null) { + return new CustomTxtTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + } + try { + long pos = (long) (ratio * fFile.length()); + while (pos > 0) { + fFile.seek(pos - 1); + if (fFile.read() == '\n') { + break; + } + pos--; + } + final ITmfLocation location = new TmfLocation(pos); + final TmfContext context = seekEvent(location); + context.setRank(ITmfContext.UNKNOWN_RANK); + return context; + } catch (final IOException e) { + Activator.getDefault().logError("Error seeking event. File: " + getPath(), e); //$NON-NLS-1$ + return new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); + } + } + + @Override + public synchronized double getLocationRatio(final ITmfLocation location) { + if (fFile == null) { + return 0; + } + try { + if (location.getLocation() instanceof Long) { + return (double) ((Long) location.getLocation()) / fFile.length(); + } + } catch (final IOException e) { + Activator.getDefault().logError("Error getting location ration. File: " + getPath(), e); //$NON-NLS-1$ + } + return 0; + } + + @Override + public ITmfLocation getCurrentLocation() { + // TODO Auto-generated method stub + return null; + } + + @Override + public synchronized CustomXmlEvent parseEvent(final ITmfContext tmfContext) { + ITmfContext context = seekEvent(tmfContext.getLocation()); + return parse(context); + } + + @Override + public synchronized CustomXmlEvent getNext(final ITmfContext context) { + final ITmfContext savedContext = context.clone(); + final CustomXmlEvent event = parse(context); + if (event != null) { + updateAttributes(savedContext, event.getTimestamp()); + context.increaseRank(); + } + return event; + } + + private synchronized CustomXmlEvent parse(final ITmfContext tmfContext) { + if (fFile == null) { + return null; + } + if (!(tmfContext instanceof CustomXmlTraceContext)) { + return null; + } + + final CustomXmlTraceContext context = (CustomXmlTraceContext) tmfContext; + if (!(context.getLocation().getLocation() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) { + return null; + } + + CustomXmlEvent event = null; + try { + if (fFile.getFilePointer() != (Long)context.getLocation().getLocation() + 1) + { + fFile.seek((Long)context.getLocation().getLocation() + 1); // +1 is for the < + } + final StringBuffer elementBuffer = new StringBuffer("<"); //$NON-NLS-1$ + readElement(elementBuffer, fFile); + final Element element = parseElementBuffer(elementBuffer); + + event = extractEvent(element, fRecordInputElement); + ((StringBuffer) event.getContent().getValue()).append(elementBuffer); + + String line; + final String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$ + long rawPos = fFile.getFilePointer(); + + while ((line = fFile.getNextLine()) != null) { + final int idx = line.indexOf(recordElementStart); + if (idx != -1) { + context.setLocation(new TmfLocation(rawPos + idx)); + return event; + } + rawPos = fFile.getFilePointer(); + } + } catch (final IOException e) { + Activator.getDefault().logError("Error parsing event. File: " + getPath(), e); //$NON-NLS-1$ + + } + context.setLocation(NULL_LOCATION); + return event; + } + + private Element parseElementBuffer(final StringBuffer elementBuffer) { + try { + final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + final DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + final EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (final String publicId, final String systemId) { + final String empty = ""; //$NON-NLS-1$ + final ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(final SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(final SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(final SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + final Document doc = db.parse(new ByteArrayInputStream(elementBuffer.toString().getBytes())); + return doc.getDocumentElement(); + } catch (final ParserConfigurationException e) { + Activator.getDefault().logError("Error parsing element buffer. File:" + getPath(), e); //$NON-NLS-1$ + } catch (final SAXException e) { + Activator.getDefault().logError("Error parsing element buffer. File:" + getPath(), e); //$NON-NLS-1$ + } catch (final IOException e) { + Activator.getDefault().logError("Error parsing element buffer. File: " + getPath(), e); //$NON-NLS-1$ + } + return null; + } + + private void readElement(final StringBuffer buffer, final RandomAccessFile raFile) { + try { + int numRead = 0; + boolean startTagClosed = false; + int i; + while ((i = raFile.read()) != -1) { + numRead++; + final char c = (char)i; + buffer.append(c); + if (c == '"') { + readQuote(buffer, raFile, '"'); + } else if (c == '\'') { + readQuote(buffer, raFile, '\''); + } else if (c == '<') { + readElement(buffer, raFile); + } else if (c == '/' && numRead == 1) { + break; // found "') { + if (buffer.charAt(buffer.length() - 2) == '/') { + break; // found "/>" + } else if (startTagClosed) { + break; // found "<...>..." + } + else { + startTagClosed = true; // found "<...>" + } + } + } + return; + } catch (final IOException e) { + return; + } + } + + private static void readQuote(final StringBuffer buffer, + final RandomAccessFile raFile, final char eq) { + try { + int i; + while ((i = raFile.read()) != -1) { + final char c = (char)i; + buffer.append(c); + if (c == eq) + { + break; // found matching end-quote + } + } + return; + } catch (final IOException e) { + return; + } + } + + private static void readComment(final StringBuffer buffer, + final RandomAccessFile raFile) { + try { + int numRead = 0; + int i; + while ((i = raFile.read()) != -1) { + numRead++; + final char c = (char)i; + buffer.append(c); + if (c == '>' && numRead >= 2 && buffer.substring(buffer.length() - 3, buffer.length() - 1).equals("--")) //$NON-NLS-1$ + { + break; // found "-->" + } + } + return; + } catch (final IOException e) { + return; + } + } + + public static StringBuffer parseElement(final Element parentElement, final StringBuffer buffer) { + final NodeList nodeList = parentElement.getChildNodes(); + String separator = null; + for (int i = 0; i < nodeList.getLength(); i++) { + final Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (separator == null) { + separator = " | "; //$NON-NLS-1$ + } else { + buffer.append(separator); + } + final Element element = (Element) node; + if (!element.hasChildNodes()) { + buffer.append(element.getNodeName()); + } else if (element.getChildNodes().getLength() == 1 && element.getFirstChild().getNodeType() == Node.TEXT_NODE) { + buffer.append(element.getNodeName() + ":" + element.getFirstChild().getNodeValue().trim()); //$NON-NLS-1$ + } else { + buffer.append(element.getNodeName()); + buffer.append(" [ "); //$NON-NLS-1$ + parseElement(element, buffer); + buffer.append(" ]"); //$NON-NLS-1$ + } + } else if (node.getNodeType() == Node.TEXT_NODE) { + if (node.getNodeValue().trim().length() != 0) { + buffer.append(node.getNodeValue().trim()); + } + } + } + return buffer; + } + + public InputElement getRecordInputElement(final InputElement inputElement) { + if (inputElement.logEntry) { + return inputElement; + } else if (inputElement.childElements != null) { + for (final InputElement childInputElement : inputElement.childElements) { + final InputElement recordInputElement = getRecordInputElement(childInputElement); + if (recordInputElement != null) { + return recordInputElement; + } + } + } + return null; + } + + public CustomXmlEvent extractEvent(final Element element, final InputElement inputElement) { + final CustomXmlEvent event = new CustomXmlEvent(fDefinition, this, TmfTimestamp.ZERO, "", fEventType,""); //$NON-NLS-1$ //$NON-NLS-2$ + event.setContent(new CustomEventContent(event, new StringBuffer())); + parseElement(element, event, inputElement); + return event; + } + + private void parseElement(final Element element, final CustomXmlEvent event, final InputElement inputElement) { + if (inputElement.inputName != null && !inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { + event.parseInput(parseElement(element, new StringBuffer()).toString(), inputElement.inputName, inputElement.inputAction, inputElement.inputFormat); + } + if (inputElement.attributes != null) { + for (final InputAttribute attribute : inputElement.attributes) { + event.parseInput(element.getAttribute(attribute.attributeName), attribute.inputName, attribute.inputAction, attribute.inputFormat); + } + } + final NodeList childNodes = element.getChildNodes(); + if (inputElement.childElements != null) { + for (int i = 0; i < childNodes.getLength(); i++) { + final Node node = childNodes.item(i); + if (node instanceof Element) { + for (final InputElement child : inputElement.childElements) { + if (node.getNodeName().equals(child.elementName)) { + parseElement((Element) node, event, child); + break; + } + } + } + } + } + return; + } + + public CustomTraceDefinition getDefinition() { + return fDefinition; + } + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#validate(org.eclipse.core.resources.IProject, java.lang.String) + */ + @Override + public boolean validate(IProject project, String path) { + return fileExists(path); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceContext.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceContext.java index 19c91f4323..42c69591b6 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceContext.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceContext.java @@ -1,49 +1,49 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.TmfContext; - -public class CustomXmlTraceContext extends TmfContext { - - public CustomXmlTraceContext(ITmfLocation location, long rank) { - super(location, rank); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return super.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof CustomXmlTraceContext)) { - return false; - } - return true; - } - +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfContext; + +public class CustomXmlTraceContext extends TmfContext { + + public CustomXmlTraceContext(ITmfLocation location, long rank) { + super(location, rank); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return super.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (!(obj instanceof CustomXmlTraceContext)) { + return false; + } + return true; + } + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceDefinition.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceDefinition.java index aa22b3ec33..6b49db56d8 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceDefinition.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/custom/CustomXmlTraceDefinition.java @@ -1,580 +1,580 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public class CustomXmlTraceDefinition extends CustomTraceDefinition { - - protected static final String CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME = "custom_xml_parsers.xml"; //$NON-NLS-1$ - protected static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME = - Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString(); - - public static final String TAG_IGNORE = Messages.CustomXmlTraceDefinition_ignoreTag; - - private static final String CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomXmlTraceDefinition_definitionRootElement; - private static final String DEFINITION_ELEMENT = Messages.CustomXmlTraceDefinition_definition; - private static final String NAME_ATTRIBUTE = Messages.CustomXmlTraceDefinition_name; - private static final String LOG_ENTRY_ATTRIBUTE = Messages.CustomXmlTraceDefinition_logEntry; - private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomXmlTraceDefinition_timestampOutputFormat; - private static final String INPUT_ELEMENT_ELEMENT = Messages.CustomXmlTraceDefinition_inputElement; - private static final String ATTRIBUTE_ELEMENT = Messages.CustomXmlTraceDefinition_attribute; - private static final String INPUT_DATA_ELEMENT = Messages.CustomXmlTraceDefinition_inputData; - private static final String ACTION_ATTRIBUTE = Messages.CustomXmlTraceDefinition_action; - private static final String FORMAT_ATTRIBUTE = Messages.CustomXmlTraceDefinition_format; - private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomXmlTraceDefinition_outputColumn; - - public InputElement rootInputElement; - - public CustomXmlTraceDefinition() { - this("", null, new ArrayList(), ""); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public CustomXmlTraceDefinition(String logtype, InputElement rootElement, List outputs, String timeStampOutputFormat) { - this.definitionName = logtype; - this.rootInputElement = rootElement; - this.outputs = outputs; - this.timeStampOutputFormat = timeStampOutputFormat; - } - - public static class InputElement { - public String elementName; - public boolean logEntry; - public String inputName; - public int inputAction; - public String inputFormat; - public List attributes; - public InputElement parentElement; - public InputElement nextElement; - public List childElements; - - public InputElement() {} - - public InputElement(String elementName, boolean logEntry, String inputName, int inputAction, String inputFormat, List attributes) { - this.elementName = elementName; - this.logEntry = logEntry; - this.inputName = inputName; - this.inputAction = inputAction; - this.inputFormat = inputFormat; - this.attributes = attributes; - } - - public void addAttribute(InputAttribute attribute) { - if (attributes == null) { - attributes = new ArrayList(1); - } - attributes.add(attribute); - } - - public void addChild(InputElement input) { - if (childElements == null) { - childElements = new ArrayList(1); - } else if (childElements.size() > 0) { - InputElement last = childElements.get(childElements.size() - 1); - last.nextElement = input; - } - childElements.add(input); - input.parentElement = this; - } - - public void addNext(InputElement input) { - if (parentElement != null) { - int index = parentElement.childElements.indexOf(this); - parentElement.childElements.add(index + 1, input); - InputElement next = nextElement; - nextElement = input; - input.nextElement = next; - } - input.parentElement = this.parentElement; - } - - public void moveUp() { - if (parentElement != null) { - int index = parentElement.childElements.indexOf(this); - if (index > 0) { - parentElement.childElements.add(index - 1 , parentElement.childElements.remove(index)); - parentElement.childElements.get(index).nextElement = nextElement; - nextElement = parentElement.childElements.get(index); - } - } - } - - public void moveDown() { - if (parentElement != null) { - int index = parentElement.childElements.indexOf(this); - if (index < parentElement.childElements.size() - 1) { - parentElement.childElements.add(index + 1 , parentElement.childElements.remove(index)); - nextElement = parentElement.childElements.get(index).nextElement; - parentElement.childElements.get(index).nextElement = this; - } - } - } - - } - - public static class InputAttribute { - public String attributeName; - public String inputName; - public int inputAction; - public String inputFormat; - - public InputAttribute() {} - - public InputAttribute(String attributeName, String inputName, int inputAction, String inputFormat) { - this.attributeName = attributeName; - this.inputName = inputName; - this.inputAction = inputAction; - this.inputFormat = inputFormat; - } - } - - @Override - public void save() { - save(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); - } - - @Override - public void save(String path) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - Document doc = null; - File file = new File(path); - if (file.canRead()) { - doc = db.parse(file); - if (! doc.getDocumentElement().getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { - return; - } - } else { - doc = db.newDocument(); - Node node = doc.createElement(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT); - doc.appendChild(node); - } - - Element root = doc.getDocumentElement(); - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - root.removeChild(node); - } - } - Element definitionElement = doc.createElement(DEFINITION_ELEMENT); - root.appendChild(definitionElement); - definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName); - - Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT); - definitionElement.appendChild(formatElement); - formatElement.appendChild(doc.createTextNode(timeStampOutputFormat)); - - if (rootInputElement != null) { - definitionElement.appendChild(createInputElementElement(rootInputElement, doc)); - } - - if (outputs != null) { - for (OutputColumn output : outputs) { - Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT); - definitionElement.appendChild(outputColumnElement); - outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name); - } - } - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ - - //initialize StreamResult with File object to save to file - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(doc); - transformer.transform(source, result); - String xmlString = result.getWriter().toString(); - - FileWriter writer = new FileWriter(file); - writer.write(xmlString); - writer.close(); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerConfigurationException e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerFactoryConfigurationError e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (TransformerException e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } - } - - private Element createInputElementElement(InputElement inputElement, Document doc) { - Element inputElementElement = doc.createElement(INPUT_ELEMENT_ELEMENT); - inputElementElement.setAttribute(NAME_ATTRIBUTE, inputElement.elementName); - - if (inputElement.logEntry) { - inputElementElement.setAttribute(LOG_ENTRY_ATTRIBUTE, Boolean.toString(inputElement.logEntry)); - } - - if (inputElement.parentElement != null) { - Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); - inputElementElement.appendChild(inputDataElement); - inputDataElement.setAttribute(NAME_ATTRIBUTE, inputElement.inputName); - inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputElement.inputAction)); - if (inputElement.inputFormat != null) { - inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputElement.inputFormat); - } - } - - if (inputElement.attributes != null) { - for (InputAttribute attribute : inputElement.attributes) { - Element inputAttributeElement = doc.createElement(ATTRIBUTE_ELEMENT); - inputElementElement.appendChild(inputAttributeElement); - inputAttributeElement.setAttribute(NAME_ATTRIBUTE, attribute.attributeName); - Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); - inputAttributeElement.appendChild(inputDataElement); - inputDataElement.setAttribute(NAME_ATTRIBUTE, attribute.inputName); - inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(attribute.inputAction)); - if (attribute.inputFormat != null) { - inputDataElement.setAttribute(FORMAT_ATTRIBUTE, attribute.inputFormat); - } - } - } - - if (inputElement.childElements != null) { - for (InputElement childInputElement : inputElement.childElements) { - inputElementElement.appendChild(createInputElementElement(childInputElement, doc)); - } - } - - return inputElementElement; - } - - public static CustomXmlTraceDefinition[] loadAll() { - return loadAll(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); - } - - public static CustomXmlTraceDefinition[] loadAll(String path) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(path); - if (!file.canRead()) { - return new CustomXmlTraceDefinition[0]; - } - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { - return new CustomXmlTraceDefinition[0]; - } - - ArrayList defList = new ArrayList(); - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) { - CustomXmlTraceDefinition def = extractDefinition((Element) node); - if (def != null) { - defList.add(def); - } - } - } - return defList.toArray(new CustomXmlTraceDefinition[0]); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ - } - return new CustomXmlTraceDefinition[0]; - } - - public static CustomXmlTraceDefinition load(String definitionName) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { - return null; - } - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - return extractDefinition((Element) node); - } - } - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } - return null; - } - - public static CustomXmlTraceDefinition extractDefinition(Element definitionElement) { - CustomXmlTraceDefinition def = new CustomXmlTraceDefinition(); - - def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE); - if (def.definitionName == null) { - return null; - } - - NodeList nodeList = definitionElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String nodeName = node.getNodeName(); - if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) { - Element formatElement = (Element) node; - def.timeStampOutputFormat = formatElement.getTextContent(); - } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) { - InputElement inputElement = extractInputElement((Element) node); - if (inputElement != null) { - if (def.rootInputElement == null) { - def.rootInputElement = inputElement; - } else { - return null; - } - } - } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) { - Element outputColumnElement = (Element) node; - OutputColumn outputColumn = new OutputColumn(); - outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE); - def.outputs.add(outputColumn); - } - } - return def; - } - - private static InputElement extractInputElement(Element inputElementElement) { - InputElement inputElement = new InputElement(); - inputElement.elementName = inputElementElement.getAttribute(NAME_ATTRIBUTE); - inputElement.logEntry = (Boolean.toString(true).equals(inputElementElement.getAttribute(LOG_ENTRY_ATTRIBUTE))) ? true : false; - NodeList nodeList = inputElementElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String nodeName = node.getNodeName(); - if (nodeName.equals(INPUT_DATA_ELEMENT)) { - Element inputDataElement = (Element) node; - inputElement.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE); - inputElement.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); - inputElement.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); - } else if (nodeName.equals(ATTRIBUTE_ELEMENT)) { - Element attributeElement = (Element) node; - InputAttribute attribute = new InputAttribute(); - attribute.attributeName = attributeElement.getAttribute(NAME_ATTRIBUTE); - NodeList attributeNodeList = attributeElement.getChildNodes(); - for (int j = 0; j < attributeNodeList.getLength(); j++) { - Node attributeNode = attributeNodeList.item(j); - String attributeNodeName = attributeNode.getNodeName(); - if (attributeNodeName.equals(INPUT_DATA_ELEMENT)) { - Element inputDataElement = (Element) attributeNode; - attribute.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE); - attribute.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); - attribute.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); - } - } - inputElement.addAttribute(attribute); - } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) { - Element childInputElementElement = (Element) node; - InputElement childInputElement = extractInputElement(childInputElementElement); - if (childInputElement != null) { - inputElement.addChild(childInputElement); - } - } - } - return inputElement; - } - - public static void delete(String definitionName) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver () { - @Override - public InputSource resolveEntity (String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler(){ - @Override - public void error(SAXParseException saxparseexception) throws SAXException {} - @Override - public void warning(SAXParseException saxparseexception) throws SAXException {} - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - throw saxparseexception; - }}); - - File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); - Document doc = db.parse(file); - - Element root = doc.getDocumentElement(); - if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { - return; - } - - NodeList nodeList = root.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element && - node.getNodeName().equals(DEFINITION_ELEMENT) && - definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { - root.removeChild(node); - } - } - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ - - //initialize StreamResult with File object to save to file - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(doc); - transformer.transform(source, result); - String xmlString = result.getWriter().toString(); - - FileWriter writer = new FileWriter(file); - writer.write(xmlString); - writer.close(); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (TransformerConfigurationException e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (TransformerFactoryConfigurationError e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } catch (TransformerException e) { - Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ - } - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.parsers.custom; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class CustomXmlTraceDefinition extends CustomTraceDefinition { + + protected static final String CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME = "custom_xml_parsers.xml"; //$NON-NLS-1$ + protected static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME = + Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString(); + + public static final String TAG_IGNORE = Messages.CustomXmlTraceDefinition_ignoreTag; + + private static final String CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomXmlTraceDefinition_definitionRootElement; + private static final String DEFINITION_ELEMENT = Messages.CustomXmlTraceDefinition_definition; + private static final String NAME_ATTRIBUTE = Messages.CustomXmlTraceDefinition_name; + private static final String LOG_ENTRY_ATTRIBUTE = Messages.CustomXmlTraceDefinition_logEntry; + private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomXmlTraceDefinition_timestampOutputFormat; + private static final String INPUT_ELEMENT_ELEMENT = Messages.CustomXmlTraceDefinition_inputElement; + private static final String ATTRIBUTE_ELEMENT = Messages.CustomXmlTraceDefinition_attribute; + private static final String INPUT_DATA_ELEMENT = Messages.CustomXmlTraceDefinition_inputData; + private static final String ACTION_ATTRIBUTE = Messages.CustomXmlTraceDefinition_action; + private static final String FORMAT_ATTRIBUTE = Messages.CustomXmlTraceDefinition_format; + private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomXmlTraceDefinition_outputColumn; + + public InputElement rootInputElement; + + public CustomXmlTraceDefinition() { + this("", null, new ArrayList(), ""); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public CustomXmlTraceDefinition(String logtype, InputElement rootElement, List outputs, String timeStampOutputFormat) { + this.definitionName = logtype; + this.rootInputElement = rootElement; + this.outputs = outputs; + this.timeStampOutputFormat = timeStampOutputFormat; + } + + public static class InputElement { + public String elementName; + public boolean logEntry; + public String inputName; + public int inputAction; + public String inputFormat; + public List attributes; + public InputElement parentElement; + public InputElement nextElement; + public List childElements; + + public InputElement() {} + + public InputElement(String elementName, boolean logEntry, String inputName, int inputAction, String inputFormat, List attributes) { + this.elementName = elementName; + this.logEntry = logEntry; + this.inputName = inputName; + this.inputAction = inputAction; + this.inputFormat = inputFormat; + this.attributes = attributes; + } + + public void addAttribute(InputAttribute attribute) { + if (attributes == null) { + attributes = new ArrayList(1); + } + attributes.add(attribute); + } + + public void addChild(InputElement input) { + if (childElements == null) { + childElements = new ArrayList(1); + } else if (childElements.size() > 0) { + InputElement last = childElements.get(childElements.size() - 1); + last.nextElement = input; + } + childElements.add(input); + input.parentElement = this; + } + + public void addNext(InputElement input) { + if (parentElement != null) { + int index = parentElement.childElements.indexOf(this); + parentElement.childElements.add(index + 1, input); + InputElement next = nextElement; + nextElement = input; + input.nextElement = next; + } + input.parentElement = this.parentElement; + } + + public void moveUp() { + if (parentElement != null) { + int index = parentElement.childElements.indexOf(this); + if (index > 0) { + parentElement.childElements.add(index - 1 , parentElement.childElements.remove(index)); + parentElement.childElements.get(index).nextElement = nextElement; + nextElement = parentElement.childElements.get(index); + } + } + } + + public void moveDown() { + if (parentElement != null) { + int index = parentElement.childElements.indexOf(this); + if (index < parentElement.childElements.size() - 1) { + parentElement.childElements.add(index + 1 , parentElement.childElements.remove(index)); + nextElement = parentElement.childElements.get(index).nextElement; + parentElement.childElements.get(index).nextElement = this; + } + } + } + + } + + public static class InputAttribute { + public String attributeName; + public String inputName; + public int inputAction; + public String inputFormat; + + public InputAttribute() {} + + public InputAttribute(String attributeName, String inputName, int inputAction, String inputFormat) { + this.attributeName = attributeName; + this.inputName = inputName; + this.inputAction = inputAction; + this.inputFormat = inputFormat; + } + } + + @Override + public void save() { + save(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); + } + + @Override + public void save(String path) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + Document doc = null; + File file = new File(path); + if (file.canRead()) { + doc = db.parse(file); + if (! doc.getDocumentElement().getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { + return; + } + } else { + doc = db.newDocument(); + Node node = doc.createElement(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT); + doc.appendChild(node); + } + + Element root = doc.getDocumentElement(); + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + root.removeChild(node); + } + } + Element definitionElement = doc.createElement(DEFINITION_ELEMENT); + root.appendChild(definitionElement); + definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName); + + Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT); + definitionElement.appendChild(formatElement); + formatElement.appendChild(doc.createTextNode(timeStampOutputFormat)); + + if (rootInputElement != null) { + definitionElement.appendChild(createInputElementElement(rootInputElement, doc)); + } + + if (outputs != null) { + for (OutputColumn output : outputs) { + Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT); + definitionElement.appendChild(outputColumnElement); + outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name); + } + } + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + + //initialize StreamResult with File object to save to file + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + String xmlString = result.getWriter().toString(); + + FileWriter writer = new FileWriter(file); + writer.write(xmlString); + writer.close(); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerConfigurationException e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerFactoryConfigurationError e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (TransformerException e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } + } + + private Element createInputElementElement(InputElement inputElement, Document doc) { + Element inputElementElement = doc.createElement(INPUT_ELEMENT_ELEMENT); + inputElementElement.setAttribute(NAME_ATTRIBUTE, inputElement.elementName); + + if (inputElement.logEntry) { + inputElementElement.setAttribute(LOG_ENTRY_ATTRIBUTE, Boolean.toString(inputElement.logEntry)); + } + + if (inputElement.parentElement != null) { + Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); + inputElementElement.appendChild(inputDataElement); + inputDataElement.setAttribute(NAME_ATTRIBUTE, inputElement.inputName); + inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputElement.inputAction)); + if (inputElement.inputFormat != null) { + inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputElement.inputFormat); + } + } + + if (inputElement.attributes != null) { + for (InputAttribute attribute : inputElement.attributes) { + Element inputAttributeElement = doc.createElement(ATTRIBUTE_ELEMENT); + inputElementElement.appendChild(inputAttributeElement); + inputAttributeElement.setAttribute(NAME_ATTRIBUTE, attribute.attributeName); + Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT); + inputAttributeElement.appendChild(inputDataElement); + inputDataElement.setAttribute(NAME_ATTRIBUTE, attribute.inputName); + inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(attribute.inputAction)); + if (attribute.inputFormat != null) { + inputDataElement.setAttribute(FORMAT_ATTRIBUTE, attribute.inputFormat); + } + } + } + + if (inputElement.childElements != null) { + for (InputElement childInputElement : inputElement.childElements) { + inputElementElement.appendChild(createInputElementElement(childInputElement, doc)); + } + } + + return inputElementElement; + } + + public static CustomXmlTraceDefinition[] loadAll() { + return loadAll(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); + } + + public static CustomXmlTraceDefinition[] loadAll(String path) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(path); + if (!file.canRead()) { + return new CustomXmlTraceDefinition[0]; + } + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { + return new CustomXmlTraceDefinition[0]; + } + + ArrayList defList = new ArrayList(); + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) { + CustomXmlTraceDefinition def = extractDefinition((Element) node); + if (def != null) { + defList.add(def); + } + } + } + return defList.toArray(new CustomXmlTraceDefinition[0]); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$ + } + return new CustomXmlTraceDefinition[0]; + } + + public static CustomXmlTraceDefinition load(String definitionName) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { + return null; + } + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + return extractDefinition((Element) node); + } + } + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } + return null; + } + + public static CustomXmlTraceDefinition extractDefinition(Element definitionElement) { + CustomXmlTraceDefinition def = new CustomXmlTraceDefinition(); + + def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE); + if (def.definitionName == null) { + return null; + } + + NodeList nodeList = definitionElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String nodeName = node.getNodeName(); + if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) { + Element formatElement = (Element) node; + def.timeStampOutputFormat = formatElement.getTextContent(); + } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) { + InputElement inputElement = extractInputElement((Element) node); + if (inputElement != null) { + if (def.rootInputElement == null) { + def.rootInputElement = inputElement; + } else { + return null; + } + } + } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) { + Element outputColumnElement = (Element) node; + OutputColumn outputColumn = new OutputColumn(); + outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE); + def.outputs.add(outputColumn); + } + } + return def; + } + + private static InputElement extractInputElement(Element inputElementElement) { + InputElement inputElement = new InputElement(); + inputElement.elementName = inputElementElement.getAttribute(NAME_ATTRIBUTE); + inputElement.logEntry = (Boolean.toString(true).equals(inputElementElement.getAttribute(LOG_ENTRY_ATTRIBUTE))) ? true : false; + NodeList nodeList = inputElementElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String nodeName = node.getNodeName(); + if (nodeName.equals(INPUT_DATA_ELEMENT)) { + Element inputDataElement = (Element) node; + inputElement.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE); + inputElement.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); + inputElement.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); + } else if (nodeName.equals(ATTRIBUTE_ELEMENT)) { + Element attributeElement = (Element) node; + InputAttribute attribute = new InputAttribute(); + attribute.attributeName = attributeElement.getAttribute(NAME_ATTRIBUTE); + NodeList attributeNodeList = attributeElement.getChildNodes(); + for (int j = 0; j < attributeNodeList.getLength(); j++) { + Node attributeNode = attributeNodeList.item(j); + String attributeNodeName = attributeNode.getNodeName(); + if (attributeNodeName.equals(INPUT_DATA_ELEMENT)) { + Element inputDataElement = (Element) attributeNode; + attribute.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE); + attribute.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)); + attribute.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE); + } + } + inputElement.addAttribute(attribute); + } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) { + Element childInputElementElement = (Element) node; + InputElement childInputElement = extractInputElement(childInputElementElement); + if (childInputElement != null) { + inputElement.addChild(childInputElement); + } + } + } + return inputElement; + } + + public static void delete(String definitionName) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver () { + @Override + public InputSource resolveEntity (String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler(){ + @Override + public void error(SAXParseException saxparseexception) throws SAXException {} + @Override + public void warning(SAXParseException saxparseexception) throws SAXException {} + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + throw saxparseexception; + }}); + + File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME); + Document doc = db.parse(file); + + Element root = doc.getDocumentElement(); + if (! root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { + return; + } + + NodeList nodeList = root.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element && + node.getNodeName().equals(DEFINITION_ELEMENT) && + definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { + root.removeChild(node); + } + } + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + + //initialize StreamResult with File object to save to file + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + String xmlString = result.getWriter().toString(); + + FileWriter writer = new FileWriter(file); + writer.write(xmlString); + writer.close(); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (TransformerConfigurationException e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (TransformerFactoryConfigurationError e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } catch (TransformerException e) { + Activator.getDefault().logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$ + } + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserInputWizardPage.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserInputWizardPage.java index e84e37d4ca..541746556b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserInputWizardPage.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserInputWizardPage.java @@ -1,1562 +1,1562 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Scanner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.ColumnLabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.Cardinality; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputData; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; -import org.eclipse.swt.SWT; -import org.eclipse.swt.browser.Browser; -import org.eclipse.swt.browser.TitleEvent; -import org.eclipse.swt.browser.TitleListener; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.FontData; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; - -public class CustomTxtParserInputWizardPage extends WizardPage { - - private static final String DEFAULT_REGEX = "\\s*(.*\\S)"; //$NON-NLS-1$ - private static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; //$NON-NLS-1$ - private static final String SIMPLE_DATE_FORMAT_URL = "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#skip-navbar_top"; //$NON-NLS-1$ - private static final String PATTERN_URL = "http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#sum"; //$NON-NLS-1$ - private static final Image lineImage = Activator.getDefault().getImageFromPath("/icons/elcl16/line_icon.gif"); //$NON-NLS-1$ - private static final Image addImage = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ - private static final Image addNextImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addnext_button.gif"); //$NON-NLS-1$ - private static final Image addChildImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addchild_button.gif"); //$NON-NLS-1$ - private static final Image deleteImage = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ - private static final Image moveUpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ - private static final Image moveDownImage = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ - private static final Image helpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/help_button.gif"); //$NON-NLS-1$ - private static final Color COLOR_BLACK = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); - private static final Color COLOR_LIGHT_GREEN = new Color(Display.getDefault(), 192, 255, 192); - private static final Color COLOR_GREEN = Display.getCurrent().getSystemColor(SWT.COLOR_GREEN); - private static final Color COLOR_LIGHT_YELLOW = new Color(Display.getDefault(), 255, 255, 192); - private static final Color COLOR_YELLOW = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); - private static final Color COLOR_LIGHT_MAGENTA = new Color(Display.getDefault(), 255, 192, 255); - private static final Color COLOR_MAGENTA = Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA); - private static final Color COLOR_LIGHT_RED = new Color(Display.getDefault(), 255, 192, 192); - private static final Color COLOR_TEXT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); - private static final Color COLOR_WIDGET_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); - - private final ISelection selection; - private CustomTxtTraceDefinition definition; - private String editDefinitionName; - private String defaultDescription; - private Line selectedLine; - private Composite container; - private Text logtypeText; - private Text timestampOutputFormatText; - private Text timestampPreviewText; - private ScrolledComposite treeScrolledComposite; - private ScrolledComposite lineScrolledComposite; - private TreeViewer treeViewer; - private Composite treeContainer; - private Composite lineContainer; - private StyledText inputText; - private Font fixedFont; - private UpdateListener updateListener; - private Browser helpBrowser; - - // variables used recursively through line traversal - private String timeStampFormat; - private boolean timestampFound; - - protected CustomTxtParserInputWizardPage(ISelection selection, CustomTxtTraceDefinition definition) { - super("CustomParserWizardPage"); //$NON-NLS-1$ - if (definition == null) { - setTitle(Messages.CustomTxtParserInputWizardPage_windowTitleNew); - defaultDescription = Messages.CustomTxtParserInputWizardPage_descriptionNew; - } else { - setTitle(Messages.CustomTxtParserInputWizardPage_windowTitleEdit); - defaultDescription = Messages.CustomTxtParserInputWizardPage_desccriptionEdit; - } - setDescription(defaultDescription); - this.selection = selection; - this.definition = definition; - if (definition != null) { - this.editDefinitionName = definition.definitionName; - } - } - - @Override - public void createControl(Composite parent) { - container = new Composite(parent, SWT.NULL); - container.setLayout(new GridLayout()); - - updateListener = new UpdateListener(); - - Composite headerComposite = new Composite(container, SWT.FILL); - GridLayout headerLayout = new GridLayout(5, false); - headerLayout.marginHeight = 0; - headerLayout.marginWidth = 0; - headerComposite.setLayout(headerLayout); - headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Label logtypeLabel = new Label(headerComposite, SWT.NULL); - logtypeLabel.setText(Messages.CustomTxtParserInputWizardPage_logType); - - logtypeText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); - logtypeText.setLayoutData(new GridData(120, SWT.DEFAULT)); - - Label timestampFormatLabel = new Label(headerComposite, SWT.NULL); - timestampFormatLabel.setText(Messages.CustomTxtParserInputWizardPage_timestampFormat); - - timestampOutputFormatText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); - timestampOutputFormatText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - timestampOutputFormatText.setText(DEFAULT_TIMESTAMP_FORMAT); - - Button dateFormatHelpButton = new Button(headerComposite, SWT.PUSH); - dateFormatHelpButton.setImage(helpImage); - dateFormatHelpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_dateFormatHelp); - dateFormatHelpButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openHelpShell(SIMPLE_DATE_FORMAT_URL); - } - }); - - Label timestampPreviewLabel = new Label(headerComposite, SWT.NULL); - timestampPreviewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 3, 1)); - timestampPreviewLabel.setText(Messages.CustomTxtParserInputWizardPage_preview); - - timestampPreviewText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - timestampPreviewText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); - timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingTimestamp); - - Composite buttonBar = new Composite(container, SWT.NONE); - GridLayout buttonBarLayout = new GridLayout(5, false); - buttonBarLayout.marginHeight = 0; - buttonBarLayout.marginWidth = 0; - buttonBar.setLayout(buttonBarLayout); - - Button removeButton = new Button(buttonBar, SWT.PUSH); - removeButton.setImage(deleteImage); - removeButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_removeLine); - removeButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty() || selectedLine == null) { - return; - } - removeLine(); - InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputLine.parentInput == null) { - definition.inputs.remove(inputLine); - } else { - inputLine.parentInput.childrenInputs.remove(inputLine); - } - treeViewer.refresh(); - validate(); - updatePreviews(); - } - }); - Button addNextButton = new Button(buttonBar, SWT.PUSH); - addNextButton.setImage(addNextImage); - addNextButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addNextLine); - addNextButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputLine inputLine = new InputLine(Cardinality.ZERO_OR_MORE, "", null); //$NON-NLS-1$ - if (((List) treeViewer.getInput()).size() == 0) { - definition.inputs.add(inputLine); - } else if (treeViewer.getSelection().isEmpty()) { - return; - } else { - InputLine previousInputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (previousInputLine.parentInput == null) { - for (int i = 0; i < definition.inputs.size(); i++) { - if (definition.inputs.get(i).equals(previousInputLine)) { - definition.inputs.add(i + 1, inputLine); - } - } - } else { - previousInputLine.addNext(inputLine); - } - } - treeViewer.refresh(); - treeViewer.setSelection(new StructuredSelection(inputLine), true); - } - }); - Button addChildButton = new Button(buttonBar, SWT.PUSH); - addChildButton.setImage(addChildImage); - addChildButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addChildLine); - addChildButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputLine inputLine = new InputLine(Cardinality.ZERO_OR_MORE, "", null); //$NON-NLS-1$ - if (((List) treeViewer.getInput()).size() == 0) { - definition.inputs.add(inputLine); - } else if (treeViewer.getSelection().isEmpty()) { - return; - } else { - InputLine parentInputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - parentInputLine.addChild(inputLine); - } - treeViewer.refresh(); - treeViewer.setSelection(new StructuredSelection(inputLine), true); - } - }); - Button moveUpButton = new Button(buttonBar, SWT.PUSH); - moveUpButton.setImage(moveUpImage); - moveUpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_moveUp); - moveUpButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty()) { - return; - } - InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputLine.parentInput == null) { - for (int i = 1; i < definition.inputs.size(); i++) { - if (definition.inputs.get(i).equals(inputLine)) { - definition.inputs.add(i - 1 , definition.inputs.remove(i)); - break; - } - } - } else { - inputLine.moveUp(); - } - treeViewer.refresh(); - validate(); - updatePreviews(); - } - }); - Button moveDownButton = new Button(buttonBar, SWT.PUSH); - moveDownButton.setImage(moveDownImage); - moveDownButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_moveDown); - moveDownButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty()) { - return; - } - InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputLine.parentInput == null) { - for (int i = 0; i < definition.inputs.size() - 1; i++) { - if (definition.inputs.get(i).equals(inputLine)) { - definition.inputs.add(i + 1 , definition.inputs.remove(i)); - break; - } - } - } else { - inputLine.moveDown(); - } - treeViewer.refresh(); - validate(); - updatePreviews(); - } - }); - - SashForm vSash = new SashForm(container, SWT.VERTICAL); - vSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - vSash.setBackground(vSash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); - - SashForm hSash = new SashForm(vSash, SWT.HORIZONTAL); - hSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - treeScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL | SWT.H_SCROLL); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.heightHint = 200; - gd.widthHint = 200; - treeScrolledComposite.setLayoutData(gd); - treeContainer = new Composite(treeScrolledComposite, SWT.NONE); - treeContainer.setLayout(new FillLayout()); - treeScrolledComposite.setContent(treeContainer); - treeScrolledComposite.setExpandHorizontal(true); - treeScrolledComposite.setExpandVertical(true); - - treeViewer = new TreeViewer(treeContainer, SWT.SINGLE | SWT.BORDER); - treeViewer.setContentProvider(new InputLineTreeNodeContentProvider()); - treeViewer.setLabelProvider(new InputLineTreeLabelProvider()); - treeViewer.addSelectionChangedListener(new InputLineTreeSelectionChangedListener()); - treeContainer.layout(); - - treeScrolledComposite.setMinSize(treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y); - - lineScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL); - lineScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - lineContainer = new Composite(lineScrolledComposite, SWT.NONE); - GridLayout linesLayout = new GridLayout(); - linesLayout.marginHeight = 1; - linesLayout.marginWidth = 0; - lineContainer.setLayout(linesLayout); - lineScrolledComposite.setContent(lineContainer); - lineScrolledComposite.setExpandHorizontal(true); - lineScrolledComposite.setExpandVertical(true); - - if (definition == null) { - definition = new CustomTxtTraceDefinition(); - definition.inputs.add(new InputLine(Cardinality.ZERO_OR_MORE, DEFAULT_REGEX, - Arrays.asList(new InputData(CustomTraceDefinition.TAG_MESSAGE, CustomTraceDefinition.ACTION_SET)))); - } - loadDefinition(definition); - treeViewer.expandAll(); - lineContainer.layout(); - - logtypeText.addModifyListener(updateListener); - timestampOutputFormatText.addModifyListener(updateListener); - - lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); - - hSash.setWeights(new int[] {1, 2}); - - Composite sashBottom = new Composite(vSash, SWT.NONE); - GridLayout sashBottomLayout = new GridLayout(3, false); - sashBottomLayout.marginHeight = 0; - sashBottomLayout.marginWidth = 0; - sashBottom.setLayout(sashBottomLayout); - - Label previewLabel = new Label(sashBottom, SWT.NULL); - previewLabel.setText(Messages.CustomTxtParserInputWizardPage_previewInput); - previewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Button highlightAllButton = new Button(sashBottom, SWT.PUSH); - highlightAllButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - highlightAllButton.setText(Messages.CustomTxtParserInputWizardPage_highlightAll); - highlightAllButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - updatePreviews(true); - } - }); - - Button legendButton = new Button(sashBottom, SWT.PUSH); - legendButton.setImage(helpImage); - legendButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_previewLegend); - legendButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - legendButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openLegend(); - } - }); - - inputText = new StyledText(sashBottom, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); - if (fixedFont == null) { - if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ - fixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ - } else { - fixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ - } - } - inputText.setFont(fixedFont); - gd = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); - gd.heightHint = inputText.computeSize(SWT.DEFAULT, inputText.getLineHeight() * 4).y; - gd.widthHint = 800; - inputText.setLayoutData(gd); - inputText.setText(getSelectionText()); - inputText.addModifyListener(updateListener); - - vSash.setWeights(new int[] {hSash.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sashBottom.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); - - setControl(container); - - validate(); - updatePreviews(); - } - - private static class InputLineTreeNodeContentProvider implements ITreeContentProvider { - - @Override - public Object[] getElements(Object inputElement) { - return ((List) inputElement).toArray(); - } - - @Override - public Object[] getChildren(Object parentElement) { - InputLine inputLine = (InputLine) parentElement; - if (inputLine.childrenInputs == null) { - return new InputLine[0]; - } - return inputLine.childrenInputs.toArray(); - } - - @Override - public boolean hasChildren(Object element) { - InputLine inputLine = (InputLine) element; - return (inputLine.childrenInputs != null && inputLine.childrenInputs.size() > 0); - } - - @Override - public void dispose() { - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - @Override - public Object getParent(Object element) { - InputLine inputLine = (InputLine) element; - return inputLine.parentInput; - } - } - - private class InputLineTreeLabelProvider extends ColumnLabelProvider { - - @Override - public Image getImage(Object element) { - return lineImage; - } - - @Override - public String getText(Object element) { - InputLine inputLine = (InputLine) element; - if (inputLine.parentInput == null) { - return "Root Line " + getName(inputLine) + " " + inputLine.cardinality.toString() + " : " + inputLine.getRegex(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - return "Line " + getName(inputLine) + " " + inputLine.cardinality.toString() + " : " + inputLine.getRegex(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - private class InputLineTreeSelectionChangedListener implements ISelectionChangedListener { - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (selectedLine != null) { - selectedLine.dispose(); - } - if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - InputLine inputLine = (InputLine) selection.getFirstElement(); - selectedLine = new Line(lineContainer, getName(inputLine), inputLine); - lineContainer.layout(); - lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); - container.layout(); - validate(); - updatePreviews(); - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.DialogPage#dispose() - */ - @Override - public void dispose() { - if (fixedFont != null) { - fixedFont.dispose(); - fixedFont = null; - } - super.dispose(); - } - - private void loadDefinition(CustomTxtTraceDefinition def) { - logtypeText.setText(def.definitionName); - timestampOutputFormatText.setText(def.timeStampOutputFormat); - treeViewer.setInput(def.inputs); - if (def.inputs.size() > 0) { - InputLine inputLine = def.inputs.get(0); - treeViewer.setSelection(new StructuredSelection(inputLine)); - } - } - - private String getName(InputLine inputLine) { - if (inputLine.parentInput == null) { - return Integer.toString(definition.inputs.indexOf(inputLine)+1); - } - return getName(inputLine.parentInput) + "." + Integer.toString(inputLine.parentInput.childrenInputs.indexOf(inputLine)+1); //$NON-NLS-1$ - } - - public List getInputNames() { - List inputs = new ArrayList(); - for (InputLine inputLine : definition.inputs) { - for (String inputName : getInputNames(inputLine)) { - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - } - return inputs; - } - - public List getInputNames(InputLine inputLine) { - List inputs = new ArrayList(); - if (inputLine.columns != null) { - for (InputData inputData : inputLine.columns) { - String inputName = inputData.name; - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - } - if (inputLine.childrenInputs != null) { - for (InputLine childInputLine : inputLine.childrenInputs) { - for (String inputName : getInputNames(childInputLine)) { - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - } - } - return inputs; - } - - private void removeLine() { - selectedLine.dispose(); - selectedLine = null; - lineContainer.layout(); - lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); - container.layout(); - } - - private String getSelectionText() { - if (this.selection instanceof IStructuredSelection) { - Object selection = ((IStructuredSelection)this.selection).getFirstElement(); - if (selection instanceof IFile) { - IFile file = (IFile)selection; - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(file.getContents())); - StringBuilder sb = new StringBuilder(); - String line = null; - while ((line = reader.readLine()) != null) { - sb.append(line + "\n"); //$NON-NLS-1$ - } - return sb.toString(); - } catch (CoreException e) { - return ""; //$NON-NLS-1$ - } catch (IOException e) { - return ""; //$NON-NLS-1$ - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - } - } - } - } - } - return ""; //$NON-NLS-1$ - } - - private void updatePreviews() { - updatePreviews(false); - } - - private void updatePreviews(boolean updateAll) { - if (inputText == null) { - // early update during construction - return; - } - inputText.setStyleRanges(new StyleRange[] {}); - - Scanner scanner = new Scanner(inputText.getText()); - scanner.useDelimiter("\n"); //$NON-NLS-1$ - int rawPos = 0; - String skip; // skip starting delimiters - if ((skip = scanner.findWithinHorizon("\\A\n+", 0)) != null) { //$NON-NLS-1$ - rawPos += skip.length(); - } - - timeStampFormat = null; - if (selectedLine != null) { - for (InputGroup input : selectedLine.inputs) { - input.previewText.setText(Messages.CustomTxtParserInputWizardPage_noMathcingLine); - } - } - - Map data = new HashMap(); - int rootLineMatches = 0; - String firstEntryTimeStamp = null; - String firstEntryTimeStampInputFormat = null; - String log = null; - event: - while (scanner.hasNext()) { - if (rootLineMatches > 0 && !updateAll) { - break; - } - if (log == null) { - log = scanner.next(); - } - int length = log.length(); - for (InputLine rootInputLine : definition.inputs) { - Pattern pattern; - try { - pattern = rootInputLine.getPattern(); - } catch (PatternSyntaxException e) { - continue; - } - Matcher matcher = pattern.matcher(log); - if (matcher.find()) { - rootLineMatches++; - inputText.setStyleRange(new StyleRange(rawPos, length, - COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); - data = new HashMap(); - timeStampFormat = null; - updatePreviewLine(rootInputLine, matcher, data, rawPos, rootLineMatches); - if (rootLineMatches == 1) { - firstEntryTimeStamp = data.get(CustomTraceDefinition.TAG_TIMESTAMP); - firstEntryTimeStampInputFormat = timeStampFormat; - } - HashMap countMap = new HashMap(); - InputLine currentInput = null; - if (rootInputLine.childrenInputs != null && rootInputLine.childrenInputs.size() > 0) { - currentInput = rootInputLine.childrenInputs.get(0); - countMap.put(currentInput, 0); - } - rawPos += length + 1; // +1 for \n - while (scanner.hasNext()) { - log = scanner.next(); - length = log.length(); - boolean processed = false; - if (currentInput == null) { - for (InputLine input : definition.inputs) { - matcher = input.getPattern().matcher(log); - if (matcher.find()) { - continue event; - } - } - } else { - if (countMap.get(currentInput) >= currentInput.getMinCount()) { - List nextInputs = currentInput.getNextInputs(countMap); - if (nextInputs.size() == 0 || nextInputs.get(nextInputs.size() - 1).getMinCount() == 0) { - for (InputLine input : definition.inputs) { - matcher = input.getPattern().matcher(log); - if (matcher.find()) { - continue event; - } - } - } - for (InputLine input : nextInputs) { - matcher = input.getPattern().matcher(log); - if (matcher.find()) { - inputText.setStyleRange(new StyleRange(rawPos, length, - COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); - currentInput = input; - updatePreviewLine(currentInput, matcher, data, rawPos, rootLineMatches); - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 1); - } else { - countMap.put(currentInput, countMap.get(currentInput) + 1); - } - Iterator iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { - currentInput = currentInput.childrenInputs.get(0); - countMap.put(currentInput, 0); - } else { - if (countMap.get(currentInput) >= currentInput.getMaxCount()) { - if (currentInput.getNextInputs(countMap).size() > 0) { - currentInput = currentInput.getNextInputs(countMap).get(0); - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 0); - } - iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - } else { - currentInput = null; - } - } - } - processed = true; - break; - } - } - } - if (! processed) { - matcher = currentInput.getPattern().matcher(log); - if (matcher.find()) { - inputText.setStyleRange(new StyleRange(rawPos, length, - COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); - updatePreviewLine(currentInput, matcher, data, rawPos, rootLineMatches); - countMap.put(currentInput, countMap.get(currentInput) + 1); - if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { - currentInput = currentInput.childrenInputs.get(0); - countMap.put(currentInput, 0); - } else { - if (countMap.get(currentInput) >= currentInput.getMaxCount()) { - if (currentInput.getNextInputs(countMap).size() > 0) { - currentInput = currentInput.getNextInputs(countMap).get(0); - if (countMap.get(currentInput) == null) { - countMap.put(currentInput, 0); - } - Iterator iter = countMap.keySet().iterator(); - while (iter.hasNext()) { - InputLine inputLine = iter.next(); - if (inputLine.level > currentInput.level) { - iter.remove(); - } - } - } else { - currentInput = null; - } - } - } - } - } - } - rawPos += length + 1; // +1 for \n - } - - break; - } - } - rawPos += length + 1; // +1 for \n - log = null; - } - scanner.close(); - if (rootLineMatches == 1) { - firstEntryTimeStamp = data.get(CustomTraceDefinition.TAG_TIMESTAMP); - firstEntryTimeStampInputFormat = timeStampFormat; - } - if (firstEntryTimeStamp == null) { - timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noTimestampGroup); - if (selectedLine != null) { - for (InputGroup group : selectedLine.inputs) { - if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingTimestamp); - break; - } - } - } - } else { - try { - SimpleDateFormat dateFormat = new SimpleDateFormat(firstEntryTimeStampInputFormat); - Date date = dateFormat.parse(firstEntryTimeStamp); - dateFormat = new SimpleDateFormat(timestampOutputFormatText.getText().trim()); - timestampPreviewText.setText(dateFormat.format(date)); - } catch (ParseException e) { - timestampPreviewText.setText("*parse exception* [" + firstEntryTimeStamp + "] <> [" + firstEntryTimeStampInputFormat + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } catch (IllegalArgumentException e) { - timestampPreviewText.setText("*parse exception* [Illegal Argument]"); //$NON-NLS-1$ - } - - } - } - - private void updatePreviewLine(InputLine line, Matcher matcher, Map data, int rawPos, int rootLineMatches) { - for (int i = 0; i < line.columns.size(); i++) { - InputData input = line.columns.get(i); - if (i < matcher.groupCount() && matcher.group(i+1) != null) { - if (line.parentInput == null) { - inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), - COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); - } else { - inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), - COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); - } - String value = matcher.group(i+1).trim(); - if (selectedLine != null && selectedLine.inputLine.equals(line) && rootLineMatches == 1) { - if (selectedLine.inputs.get(i).previewText.getText().equals(Messages.CustomTxtParserInputWizardPage_noMatchingLine)) { - selectedLine.inputs.get(i).previewText.setText(value); - } - } - if (value.length() == 0) { - continue; - } - if (input.action == CustomTraceDefinition.ACTION_SET) { - data.put(input.name, value); - if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - timeStampFormat = input.format; - } - } else if (input.action == CustomTraceDefinition.ACTION_APPEND) { - String s = data.get(input.name); - if (s != null) { - data.put(input.name, s + value); - } else { - data.put(input.name, value); - } - if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - if (timeStampFormat != null) { - timeStampFormat += input.format; - } else { - timeStampFormat = input.format; - } - } - } else if (input.action == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { - String s = data.get(input.name); - if (s != null) { - data.put(input.name, s + " | " + value); //$NON-NLS-1$ - } else { - data.put(input.name, value); - } - if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - if (timeStampFormat != null) { - timeStampFormat += " | " + input.format; //$NON-NLS-1$ - } else { - timeStampFormat = input.format; - } - } - } - } else { - if (selectedLine != null && selectedLine.inputLine.equals(line) && rootLineMatches == 1) { - if (selectedLine.inputs.get(i).previewText.getText().equals(Messages.CustomTxtParserInputWizardPage_noMatchingLine)) { - selectedLine.inputs.get(i).previewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingGroup); - } - } - } - } - // highlight the matching groups that have no corresponponding input - for (int i = line.columns.size(); i < matcher.groupCount(); i++) { - if (matcher.group(i+1) != null) { - if (line.parentInput == null) { - inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), - COLOR_BLACK, COLOR_MAGENTA)); - } else { - inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), - COLOR_BLACK, COLOR_LIGHT_MAGENTA)); - } - } - } - } - - private void openHelpShell(String url) { - if (helpBrowser != null && !helpBrowser.isDisposed()) { - helpBrowser.getShell().setActive(); - if (!helpBrowser.getUrl().equals(url)) { - helpBrowser.setUrl(url); - } - return; - } - final Shell helpShell = new Shell(getShell(), SWT.SHELL_TRIM); - helpShell.setLayout(new FillLayout()); - helpBrowser = new Browser(helpShell, SWT.NONE); - helpBrowser.addTitleListener(new TitleListener() { - @Override - public void changed(TitleEvent event) { - helpShell.setText(event.title); - } - }); - helpBrowser.setBounds(0,0,600,400); - helpShell.pack(); - helpShell.open(); - helpBrowser.setUrl(url); - } - - private void openLegend() { - final String CG = Messages.CustomTxtParserInputWizardPage_capturedGroup; - final String UCG = Messages.CustomTxtParserInputWizardPage_unidentifiedCaptureGroup; - final String UT = Messages.CustomTxtParserInputWizardPage_uncapturedText; - int line1start = 0; - String line1 = Messages.CustomTxtParserInputWizardPage_nonMatchingLine; - int line2start = line1start + line1.length(); - String line2 = Messages.CustomTxtParserInputWizardPage_matchingLineRoot + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - int line3start = line2start + line2.length(); - String line3 = Messages.CustomTxtParserInputWizardPage_matchingOtherLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - int line4start = line3start + line3.length(); - String line4 = Messages.CustomTxtParserInputWizardPage_matchingOtherLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - int line5start = line4start + line4.length(); - String line5 = Messages.CustomTxtParserInputWizardPage_nonMatchingLine; - int line6start = line5start + line5.length(); - String line6 = Messages.CustomTxtParserInputWizardPage_matchingRootLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - final Shell legendShell = new Shell(getShell(), SWT.DIALOG_TRIM); - legendShell.setLayout(new FillLayout()); - StyledText legendText = new StyledText(legendShell, SWT.MULTI); - legendText.setFont(fixedFont); - legendText.setText(line1 + line2 + line3 + line4 + line5 + line6); - legendText.setStyleRange(new StyleRange(line2start, line2.length(), COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); - legendText.setStyleRange(new StyleRange(line3start, line3.length(), COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); - legendText.setStyleRange(new StyleRange(line4start, line4.length(), COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); - legendText.setStyleRange(new StyleRange(line6start, line6.length(), COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); - legendText.setStyleRange(new StyleRange(line2start + line2.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); - legendText.setStyleRange(new StyleRange(line2start + line2.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_MAGENTA)); - legendText.setStyleRange(new StyleRange(line3start + line3.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); - legendText.setStyleRange(new StyleRange(line3start + line3.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_LIGHT_MAGENTA)); - legendText.setStyleRange(new StyleRange(line4start + line4.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); - legendText.setStyleRange(new StyleRange(line4start + line4.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_LIGHT_MAGENTA)); - legendText.setStyleRange(new StyleRange(line6start + line6.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); - legendText.setStyleRange(new StyleRange(line6start + line6.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_MAGENTA)); - legendShell.setText(Messages.CustomTxtParserInputWizardPage_previewLegend); - legendShell.pack(); - legendShell.open(); - } - - private class UpdateListener implements ModifyListener, SelectionListener { - - @Override - public void modifyText(ModifyEvent e) { - validate(); - updatePreviews(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - validate(); - updatePreviews(); - } - - @Override - public void widgetSelected(SelectionEvent e) { - validate(); - updatePreviews(); - } - - } - - private class Line { - private static final String INFINITY_STRING = "\u221E"; //$NON-NLS-1$ - InputLine inputLine; - Group group; - Composite labelComposite; - Text regexText; - Composite cardinalityContainer; - Combo cardinalityCombo; - Label cardinalityMinLabel; - Text cardinalityMinText; - Label cardinalityMaxLabel; - Text cardinalityMaxText; - Button infiniteButton; - List inputs = new ArrayList(); - Button addGroupButton; - Label addGroupLabel; - - public Line(Composite parent, String name, InputLine inputLine) { - this.inputLine = inputLine; - - group = new Group(parent, SWT.NONE); - group.setText(name); - group.setLayout(new GridLayout(2, false)); - group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - labelComposite = new Composite(group, SWT.FILL); - GridLayout labelLayout = new GridLayout(1, false); - labelLayout.marginWidth = 0; - labelLayout.marginHeight = 0; - labelComposite.setLayout(labelLayout); - labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - Label label = new Label(labelComposite, SWT.NULL); - label.setText(Messages.CustomTxtParserInputWizardPage_regularExpression); - - Composite regexContainer = new Composite(group, SWT.NONE); - GridLayout regexLayout = new GridLayout(2, false); - regexLayout.marginHeight = 0; - regexLayout.marginWidth = 0; - regexContainer.setLayout(regexLayout); - regexContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - regexText = new Text(regexContainer, SWT.BORDER | SWT.SINGLE); - GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - regexText.setLayoutData(gd); - regexText.setText(inputLine.getRegex()); - regexText.addModifyListener(updateListener); - - Button regexHelpButton = new Button(regexContainer, SWT.PUSH); - regexHelpButton.setImage(helpImage); - regexHelpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_regularExpressionHelp); - regexHelpButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openHelpShell(PATTERN_URL); - } - }); - - label = new Label(group, SWT.NONE); - label.setText(Messages.CustomTxtParserInputWizardPage_cardinality); - label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - cardinalityContainer = new Composite(group, SWT.NONE); - GridLayout cardinalityLayout = new GridLayout(6, false); - cardinalityLayout.marginHeight = 0; - cardinalityLayout.marginWidth = 0; - cardinalityContainer.setLayout(cardinalityLayout); - cardinalityContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - cardinalityCombo = new Combo(cardinalityContainer, SWT.DROP_DOWN | SWT.READ_ONLY); - cardinalityCombo.setItems(new String[] { - Cardinality.ZERO_OR_MORE.toString(), - Cardinality.ONE_OR_MORE.toString(), - Cardinality.ZERO_OR_ONE.toString(), - Cardinality.ONE.toString(), - "(?,?)"}); //$NON-NLS-1$ - cardinalityCombo.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - switch (cardinalityCombo.getSelectionIndex()) { - case 4: //(?,?) - cardinalityMinLabel.setVisible(true); - cardinalityMinText.setVisible(true); - cardinalityMaxLabel.setVisible(true); - cardinalityMaxText.setVisible(true); - infiniteButton.setVisible(true); - break; - default: - cardinalityMinLabel.setVisible(false); - cardinalityMinText.setVisible(false); - cardinalityMaxLabel.setVisible(false); - cardinalityMaxText.setVisible(false); - infiniteButton.setVisible(false); - break; - } - cardinalityContainer.layout(); - validate(); - updatePreviews(); - }}); - - cardinalityMinLabel = new Label(cardinalityContainer, SWT.NONE); - cardinalityMinLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - cardinalityMinLabel.setText(Messages.CustomTxtParserInputWizardPage_min); - cardinalityMinLabel.setVisible(false); - - cardinalityMinText = new Text(cardinalityContainer, SWT.BORDER | SWT.SINGLE); - gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); - gd.widthHint = 20; - cardinalityMinText.setLayoutData(gd); - cardinalityMinText.setVisible(false); - - cardinalityMaxLabel = new Label(cardinalityContainer, SWT.NONE); - cardinalityMaxLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - cardinalityMaxLabel.setText(Messages.CustomTxtParserInputWizardPage_max); - cardinalityMaxLabel.setVisible(false); - - cardinalityMaxText = new Text(cardinalityContainer, SWT.BORDER | SWT.SINGLE); - gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); - gd.widthHint = 20; - cardinalityMaxText.setLayoutData(gd); - cardinalityMaxText.setVisible(false); - - infiniteButton = new Button(cardinalityContainer, SWT.PUSH); - infiniteButton.setText(INFINITY_STRING); - infiniteButton.setVisible(false); - infiniteButton.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e) { - cardinalityMaxText.setText(INFINITY_STRING); - }}); - - if (inputLine.cardinality.equals(Cardinality.ZERO_OR_MORE)) { - cardinalityCombo.select(0); - } else if (inputLine.cardinality.equals(Cardinality.ONE_OR_MORE)) { - cardinalityCombo.select(1); - } else if (inputLine.cardinality.equals(Cardinality.ZERO_OR_ONE)) { - cardinalityCombo.select(2); - } else if (inputLine.cardinality.equals(Cardinality.ONE)) { - cardinalityCombo.select(3); - } else { - cardinalityCombo.select(4); - cardinalityMinLabel.setVisible(true); - cardinalityMinText.setVisible(true); - if (inputLine.getMinCount() >= 0) { - cardinalityMinText.setText(Integer.toString(inputLine.getMinCount())); - } - cardinalityMaxLabel.setVisible(true); - cardinalityMaxText.setVisible(true); - if (inputLine.getMaxCount() == Cardinality.INF) { - cardinalityMaxText.setText(INFINITY_STRING); - } else if (inputLine.getMaxCount() >= 0) { - cardinalityMaxText.setText(Integer.toString(inputLine.getMaxCount())); - } - infiniteButton.setVisible(true); - } - - VerifyListener digitsListener = new VerifyListener() { - @Override - public void verifyText(VerifyEvent e) { - if (e.text.equals(INFINITY_STRING)) { - e.doit = e.widget == cardinalityMaxText && e.start == 0 && e.end == ((Text) e.widget).getText().length(); - } else { - if (((Text) e.widget).getText().equals(INFINITY_STRING)) { - e.doit = e.start == 0 && e.end == ((Text) e.widget).getText().length(); - } - for (int i = 0; i < e.text.length(); i++) { - if (!Character.isDigit(e.text.charAt(i))) { - e.doit = false; - break; - } - } - } - }}; - - cardinalityMinText.addModifyListener(updateListener); - cardinalityMaxText.addModifyListener(updateListener); - cardinalityMinText.addVerifyListener(digitsListener); - cardinalityMaxText.addVerifyListener(digitsListener); - - if (inputLine.columns != null) { - for (InputData inputData : inputLine.columns) { - InputGroup inputGroup = new InputGroup(group, this, inputs.size()+1); - if (inputData.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - inputGroup.tagCombo.select(0); - inputGroup.tagText.setText(inputData.format); - inputGroup.tagLabel.setText(Messages.CustomTxtParserInputWizardPage_format); - inputGroup.tagLabel.setVisible(true); - inputGroup.tagText.setVisible(true); - inputGroup.tagText.addModifyListener(updateListener); - } else if (inputData.name.equals(CustomTraceDefinition.TAG_MESSAGE)) { - inputGroup.tagCombo.select(1); - } else { - inputGroup.tagCombo.select(2); - inputGroup.tagText.setText(inputData.name); - inputGroup.tagLabel.setText(Messages.CustomTxtParserInputWizardPage_name); - inputGroup.tagLabel.setVisible(true); - inputGroup.tagText.setVisible(true); - inputGroup.tagText.addModifyListener(updateListener); - } - inputGroup.actionCombo.select(inputData.action); - inputs.add(inputGroup); - } - } - - createAddGroupButton(); - } - - private void createAddGroupButton() { - addGroupButton = new Button(group, SWT.PUSH); - addGroupButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - addGroupButton.setImage(addImage); - addGroupButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addGroup); - addGroupButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - removeAddGroupButton(); - inputs.add(new InputGroup(group, Line.this, inputs.size()+1)); - createAddGroupButton(); - lineContainer.layout(); - lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); - group.getParent().layout(); - validate(); - updatePreviews(); - } - }); - - addGroupLabel = new Label(group, SWT.NULL); - addGroupLabel.setText(Messages.CustomTxtParserInputWizardPage_newGroup); - } - - private void removeAddGroupButton() { - addGroupButton.dispose(); - addGroupLabel.dispose(); - } - - private void removeInput(int inputNumber) { - if (--inputNumber < inputs.size()) { - inputs.remove(inputNumber).dispose(); - for (int i = inputNumber; i < inputs.size(); i++) { - inputs.get(i).setInputNumber(i+1); - } - lineContainer.layout(); - lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); - group.getParent().layout(); - } - } - -// private void setName(String name) { -// this.name = name; -// group.setText("Line " + name); -// } - - private void dispose() { - group.dispose(); - } - - private void extractInputs() { - inputLine.setRegex(selectedLine.regexText.getText()); - switch (cardinalityCombo.getSelectionIndex()) { - case 0: - inputLine.cardinality = Cardinality.ZERO_OR_MORE; - break; - case 1: - inputLine.cardinality = Cardinality.ONE_OR_MORE; - break; - case 2: - inputLine.cardinality = Cardinality.ZERO_OR_ONE; - break; - case 3: - inputLine.cardinality = Cardinality.ONE; - break; - case 4: //(?,?) - int min, max; - try { - min = Integer.parseInt(cardinalityMinText.getText()); - } catch (NumberFormatException e) { - min = -1; - } - try { - if (cardinalityMaxText.getText().equals(INFINITY_STRING)) { - max = Cardinality.INF; - } else { - max = Integer.parseInt(cardinalityMaxText.getText()); - } - } catch (NumberFormatException e) { - max = -1; - } - inputLine.cardinality = new Cardinality(min, max); - break; - default: - inputLine.cardinality = Cardinality.ZERO_OR_MORE; - break; - } - inputLine.columns = new ArrayList(inputs.size()); - for (int i = 0; i < inputs.size(); i++) { - InputGroup group = inputs.get(i); - InputData inputData = new InputData(); - if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { - inputData.name = group.tagText.getText().trim(); - } else { - inputData.name = group.tagCombo.getText(); - if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - inputData.format = group.tagText.getText().trim(); - } - } - inputData.action = group.actionCombo.getSelectionIndex(); - inputLine.columns.add(inputData); - } - } - } - - private class InputGroup { - Line line; - int inputNumber; - - // children of parent (must be disposed) - Composite labelComposite; - Composite tagComposite; - Label previewLabel; - Text previewText; - - // children of labelComposite - Label inputLabel; - - // children of tagComposite - Combo tagCombo; - Label tagLabel; - Text tagText; - Combo actionCombo; - - public InputGroup(Composite parent, Line line, int inputNumber) { - this.line = line; - this.inputNumber = inputNumber; - - labelComposite = new Composite(parent, SWT.FILL); - GridLayout labelLayout = new GridLayout(2, false); - labelLayout.marginWidth = 0; - labelLayout.marginHeight = 0; - labelComposite.setLayout(labelLayout); - labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - Button deleteButton = new Button(labelComposite, SWT.PUSH); - deleteButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - deleteButton.setImage(deleteImage); - deleteButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_removeGroup); - deleteButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputGroup.this.line.removeInput(InputGroup.this.inputNumber); - validate(); - updatePreviews(); - } - }); - - inputLabel = new Label(labelComposite, SWT.NULL); - inputLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - inputLabel.setText(Messages.CustomTxtParserInputWizardPage_group + inputNumber + ":"); //$NON-NLS-1$ - - tagComposite = new Composite(parent, SWT.FILL); - GridLayout tagLayout = new GridLayout(4, false); - tagLayout.marginWidth = 0; - tagLayout.marginHeight = 0; - tagComposite.setLayout(tagLayout); - tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - tagCombo.setItems(new String[] {CustomTraceDefinition.TAG_TIMESTAMP, - CustomTraceDefinition.TAG_MESSAGE, - CustomTraceDefinition.TAG_OTHER}); - tagCombo.select(1); - tagCombo.addSelectionListener(new SelectionListener(){ - @Override - public void widgetDefaultSelected(SelectionEvent e) {} - @Override - public void widgetSelected(SelectionEvent e) { - tagText.removeModifyListener(updateListener); - switch (tagCombo.getSelectionIndex()) { - case 0: //Time Stamp - tagLabel.setText(Messages.CustomTxtParserInputWizardPage_format); - tagLabel.setVisible(true); - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - break; - case 1: //Message - tagLabel.setVisible(false); - tagText.setVisible(false); - break; - case 2: //Other - tagLabel.setText(Messages.CustomTxtParserInputWizardPage_name); - tagLabel.setVisible(true); - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - break; - case 3: //Continue - tagLabel.setVisible(false); - tagText.setVisible(false); - break; - default: - break; - } - tagComposite.layout(); - validate(); - updatePreviews(); - }}); - - tagLabel = new Label(tagComposite, SWT.NULL); - tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - tagLabel.setVisible(false); - - tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); - GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - tagText.setLayoutData(gd); - tagText.setVisible(false); - - actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - actionCombo.setItems(new String[] {Messages.CustomTxtParserInputWizardPage_set, Messages.CustomTxtParserInputWizardPage_append, Messages.CustomTxtParserInputWizardPage_appendWith}); - actionCombo.select(0); - actionCombo.addSelectionListener(updateListener); - - previewLabel = new Label(parent, SWT.NULL); - previewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - previewLabel.setText(Messages.CustomTxtParserInputWizardPage_preview); - - previewText = new Text(parent, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - previewText.setLayoutData(gd); - previewText.setText(Messages.CustomTxtParserInputWizardPage_noMatch); - previewText.setBackground(COLOR_WIDGET_BACKGROUND); - } - - private void dispose() { - labelComposite.dispose(); - tagComposite.dispose(); - previewLabel.dispose(); - previewText.dispose(); - } - - private void setInputNumber(int inputNumber) { - this.inputNumber = inputNumber; - inputLabel.setText(Messages.CustomTxtParserInputWizardPage_group + inputNumber + ":"); //$NON-NLS-1$ - labelComposite.layout(); - } - } - - private void validate() { - - definition.definitionName = logtypeText.getText().trim(); - definition.timeStampOutputFormat = timestampOutputFormatText.getText().trim(); - - if (selectedLine != null) { - selectedLine.extractInputs(); - treeViewer.refresh(); - } - - StringBuffer errors = new StringBuffer(); - - if (definition.definitionName.length() == 0) { - errors.append("Enter a name for the new log type. "); //$NON-NLS-1$ - logtypeText.setBackground(COLOR_LIGHT_RED); - } else { - logtypeText.setBackground(COLOR_TEXT_BACKGROUND); - for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { - if (definition.definitionName.equals(def.definitionName)) { - if (editDefinitionName == null || ! editDefinitionName.equals(definition.definitionName)) { - errors.append("The log type name already exists. "); //$NON-NLS-1$ - logtypeText.setBackground(COLOR_LIGHT_RED); - break; - } - } - } - } - - timestampFound = false; - for (int i = 0; i < definition.inputs.size(); i++) { - - InputLine inputLine = definition.inputs.get(i); - String name = Integer.toString(i+1); - errors.append(validateLine(inputLine, name)); - } - if (timestampFound) { - if (definition.timeStampOutputFormat.length() == 0) { - errors.append("Enter the output format for the Time Stamp field. "); //$NON-NLS-1$ - timestampOutputFormatText.setBackground(COLOR_LIGHT_RED); - } else { - try { - new SimpleDateFormat(definition.timeStampOutputFormat); - timestampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); - } catch (IllegalArgumentException e) { - errors.append("Enter a valid output format for the Time Stamp field. "); //$NON-NLS-1$ - timestampOutputFormatText.setBackground(COLOR_LIGHT_RED); - } - } - - } else { - timestampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); -// timestampPreviewText.setBackground(COLOR_WIDGET_BACKGROUND); -// errors.append("Identify a Time Stamp group (Line "+name+"). "); -// timestampPreviewText.setText("*no timestamp group*"); -// timestampPreviewText.setBackground(COLOR_LIGHT_RED); - } - - if (errors.length() == 0) { - setDescription(defaultDescription); - setPageComplete(true); - } else { - setDescription(errors.toString()); - setPageComplete(false); - } - } - - public StringBuffer validateLine(InputLine inputLine, String name) { - StringBuffer errors = new StringBuffer(); - Line line = null; - if (selectedLine != null && selectedLine.inputLine.equals(inputLine)) { - line = selectedLine; - } - try { - Pattern.compile(inputLine.getRegex()); - if (line != null) { - line.regexText.setBackground(COLOR_TEXT_BACKGROUND); - } - } catch (PatternSyntaxException e) { - errors.append("Enter a valid regular expression (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ - if (line != null) { - line.regexText.setBackground(COLOR_LIGHT_RED); - } - } - if (inputLine.getMinCount() == -1) { - errors.append("Enter a minimum value for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ - if (line != null) { - line.cardinalityMinText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (line != null) { - line.cardinalityMinText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - if (inputLine.getMaxCount() == -1) { - errors.append("Enter a maximum value for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ - if (line != null) { - line.cardinalityMaxText.setBackground(COLOR_LIGHT_RED); - } - } else if (inputLine.getMinCount() > inputLine.getMaxCount()) { - errors.append("Enter correct (min <= max) values for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ - if (line != null) { - line.cardinalityMinText.setBackground(COLOR_LIGHT_RED); - } - if (line != null) { - line.cardinalityMaxText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (line != null) { - line.cardinalityMaxText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - for (int i = 0; inputLine.columns != null && i < inputLine.columns.size(); i++) { - InputData inputData = inputLine.columns.get(i); - InputGroup group = null; - if (line != null) { - group = line.inputs.get(i); - } - if (inputData.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - timestampFound = true; - if (inputData.format.length() == 0) { - errors.append("Enter the input format for the Time Stamp (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (group != null) { - group.tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - try { - new SimpleDateFormat(inputData.format); - if (group != null) { - group.tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } catch (IllegalArgumentException e) { - errors.append("Enter a valid input format for the Time Stamp (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (group != null) { - group.tagText.setBackground(COLOR_LIGHT_RED); - } - } - } - } else if (inputData.name.length() == 0) { - errors.append("Enter a name for the data group (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (group != null) { - group.tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (group != null) { - group.tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - } - for (int i = 0; inputLine.childrenInputs != null && i < inputLine.childrenInputs.size(); i++) { - errors.append(validateLine(inputLine.childrenInputs.get(i), name+"."+(i+1))); //$NON-NLS-1$ - } - return errors; - } - - public CustomTxtTraceDefinition getDefinition() { - return definition; - } - - public char[] getInputText() { - return inputText.getText().toCharArray(); - } -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.Cardinality; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputData; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition.InputLine; +import org.eclipse.swt.SWT; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.browser.TitleEvent; +import org.eclipse.swt.browser.TitleListener; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +public class CustomTxtParserInputWizardPage extends WizardPage { + + private static final String DEFAULT_REGEX = "\\s*(.*\\S)"; //$NON-NLS-1$ + private static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; //$NON-NLS-1$ + private static final String SIMPLE_DATE_FORMAT_URL = "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#skip-navbar_top"; //$NON-NLS-1$ + private static final String PATTERN_URL = "http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#sum"; //$NON-NLS-1$ + private static final Image lineImage = Activator.getDefault().getImageFromPath("/icons/elcl16/line_icon.gif"); //$NON-NLS-1$ + private static final Image addImage = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ + private static final Image addNextImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addnext_button.gif"); //$NON-NLS-1$ + private static final Image addChildImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addchild_button.gif"); //$NON-NLS-1$ + private static final Image deleteImage = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ + private static final Image moveUpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ + private static final Image moveDownImage = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ + private static final Image helpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/help_button.gif"); //$NON-NLS-1$ + private static final Color COLOR_BLACK = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); + private static final Color COLOR_LIGHT_GREEN = new Color(Display.getDefault(), 192, 255, 192); + private static final Color COLOR_GREEN = Display.getCurrent().getSystemColor(SWT.COLOR_GREEN); + private static final Color COLOR_LIGHT_YELLOW = new Color(Display.getDefault(), 255, 255, 192); + private static final Color COLOR_YELLOW = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); + private static final Color COLOR_LIGHT_MAGENTA = new Color(Display.getDefault(), 255, 192, 255); + private static final Color COLOR_MAGENTA = Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA); + private static final Color COLOR_LIGHT_RED = new Color(Display.getDefault(), 255, 192, 192); + private static final Color COLOR_TEXT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + private static final Color COLOR_WIDGET_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); + + private final ISelection selection; + private CustomTxtTraceDefinition definition; + private String editDefinitionName; + private String defaultDescription; + private Line selectedLine; + private Composite container; + private Text logtypeText; + private Text timestampOutputFormatText; + private Text timestampPreviewText; + private ScrolledComposite treeScrolledComposite; + private ScrolledComposite lineScrolledComposite; + private TreeViewer treeViewer; + private Composite treeContainer; + private Composite lineContainer; + private StyledText inputText; + private Font fixedFont; + private UpdateListener updateListener; + private Browser helpBrowser; + + // variables used recursively through line traversal + private String timeStampFormat; + private boolean timestampFound; + + protected CustomTxtParserInputWizardPage(ISelection selection, CustomTxtTraceDefinition definition) { + super("CustomParserWizardPage"); //$NON-NLS-1$ + if (definition == null) { + setTitle(Messages.CustomTxtParserInputWizardPage_windowTitleNew); + defaultDescription = Messages.CustomTxtParserInputWizardPage_descriptionNew; + } else { + setTitle(Messages.CustomTxtParserInputWizardPage_windowTitleEdit); + defaultDescription = Messages.CustomTxtParserInputWizardPage_desccriptionEdit; + } + setDescription(defaultDescription); + this.selection = selection; + this.definition = definition; + if (definition != null) { + this.editDefinitionName = definition.definitionName; + } + } + + @Override + public void createControl(Composite parent) { + container = new Composite(parent, SWT.NULL); + container.setLayout(new GridLayout()); + + updateListener = new UpdateListener(); + + Composite headerComposite = new Composite(container, SWT.FILL); + GridLayout headerLayout = new GridLayout(5, false); + headerLayout.marginHeight = 0; + headerLayout.marginWidth = 0; + headerComposite.setLayout(headerLayout); + headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label logtypeLabel = new Label(headerComposite, SWT.NULL); + logtypeLabel.setText(Messages.CustomTxtParserInputWizardPage_logType); + + logtypeText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); + logtypeText.setLayoutData(new GridData(120, SWT.DEFAULT)); + + Label timestampFormatLabel = new Label(headerComposite, SWT.NULL); + timestampFormatLabel.setText(Messages.CustomTxtParserInputWizardPage_timestampFormat); + + timestampOutputFormatText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); + timestampOutputFormatText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + timestampOutputFormatText.setText(DEFAULT_TIMESTAMP_FORMAT); + + Button dateFormatHelpButton = new Button(headerComposite, SWT.PUSH); + dateFormatHelpButton.setImage(helpImage); + dateFormatHelpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_dateFormatHelp); + dateFormatHelpButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + openHelpShell(SIMPLE_DATE_FORMAT_URL); + } + }); + + Label timestampPreviewLabel = new Label(headerComposite, SWT.NULL); + timestampPreviewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 3, 1)); + timestampPreviewLabel.setText(Messages.CustomTxtParserInputWizardPage_preview); + + timestampPreviewText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); + timestampPreviewText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingTimestamp); + + Composite buttonBar = new Composite(container, SWT.NONE); + GridLayout buttonBarLayout = new GridLayout(5, false); + buttonBarLayout.marginHeight = 0; + buttonBarLayout.marginWidth = 0; + buttonBar.setLayout(buttonBarLayout); + + Button removeButton = new Button(buttonBar, SWT.PUSH); + removeButton.setImage(deleteImage); + removeButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_removeLine); + removeButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty() || selectedLine == null) { + return; + } + removeLine(); + InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputLine.parentInput == null) { + definition.inputs.remove(inputLine); + } else { + inputLine.parentInput.childrenInputs.remove(inputLine); + } + treeViewer.refresh(); + validate(); + updatePreviews(); + } + }); + Button addNextButton = new Button(buttonBar, SWT.PUSH); + addNextButton.setImage(addNextImage); + addNextButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addNextLine); + addNextButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputLine inputLine = new InputLine(Cardinality.ZERO_OR_MORE, "", null); //$NON-NLS-1$ + if (((List) treeViewer.getInput()).size() == 0) { + definition.inputs.add(inputLine); + } else if (treeViewer.getSelection().isEmpty()) { + return; + } else { + InputLine previousInputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (previousInputLine.parentInput == null) { + for (int i = 0; i < definition.inputs.size(); i++) { + if (definition.inputs.get(i).equals(previousInputLine)) { + definition.inputs.add(i + 1, inputLine); + } + } + } else { + previousInputLine.addNext(inputLine); + } + } + treeViewer.refresh(); + treeViewer.setSelection(new StructuredSelection(inputLine), true); + } + }); + Button addChildButton = new Button(buttonBar, SWT.PUSH); + addChildButton.setImage(addChildImage); + addChildButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addChildLine); + addChildButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputLine inputLine = new InputLine(Cardinality.ZERO_OR_MORE, "", null); //$NON-NLS-1$ + if (((List) treeViewer.getInput()).size() == 0) { + definition.inputs.add(inputLine); + } else if (treeViewer.getSelection().isEmpty()) { + return; + } else { + InputLine parentInputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + parentInputLine.addChild(inputLine); + } + treeViewer.refresh(); + treeViewer.setSelection(new StructuredSelection(inputLine), true); + } + }); + Button moveUpButton = new Button(buttonBar, SWT.PUSH); + moveUpButton.setImage(moveUpImage); + moveUpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_moveUp); + moveUpButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty()) { + return; + } + InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputLine.parentInput == null) { + for (int i = 1; i < definition.inputs.size(); i++) { + if (definition.inputs.get(i).equals(inputLine)) { + definition.inputs.add(i - 1 , definition.inputs.remove(i)); + break; + } + } + } else { + inputLine.moveUp(); + } + treeViewer.refresh(); + validate(); + updatePreviews(); + } + }); + Button moveDownButton = new Button(buttonBar, SWT.PUSH); + moveDownButton.setImage(moveDownImage); + moveDownButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_moveDown); + moveDownButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty()) { + return; + } + InputLine inputLine = (InputLine) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputLine.parentInput == null) { + for (int i = 0; i < definition.inputs.size() - 1; i++) { + if (definition.inputs.get(i).equals(inputLine)) { + definition.inputs.add(i + 1 , definition.inputs.remove(i)); + break; + } + } + } else { + inputLine.moveDown(); + } + treeViewer.refresh(); + validate(); + updatePreviews(); + } + }); + + SashForm vSash = new SashForm(container, SWT.VERTICAL); + vSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + vSash.setBackground(vSash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); + + SashForm hSash = new SashForm(vSash, SWT.HORIZONTAL); + hSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + treeScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL | SWT.H_SCROLL); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.heightHint = 200; + gd.widthHint = 200; + treeScrolledComposite.setLayoutData(gd); + treeContainer = new Composite(treeScrolledComposite, SWT.NONE); + treeContainer.setLayout(new FillLayout()); + treeScrolledComposite.setContent(treeContainer); + treeScrolledComposite.setExpandHorizontal(true); + treeScrolledComposite.setExpandVertical(true); + + treeViewer = new TreeViewer(treeContainer, SWT.SINGLE | SWT.BORDER); + treeViewer.setContentProvider(new InputLineTreeNodeContentProvider()); + treeViewer.setLabelProvider(new InputLineTreeLabelProvider()); + treeViewer.addSelectionChangedListener(new InputLineTreeSelectionChangedListener()); + treeContainer.layout(); + + treeScrolledComposite.setMinSize(treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y); + + lineScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL); + lineScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + lineContainer = new Composite(lineScrolledComposite, SWT.NONE); + GridLayout linesLayout = new GridLayout(); + linesLayout.marginHeight = 1; + linesLayout.marginWidth = 0; + lineContainer.setLayout(linesLayout); + lineScrolledComposite.setContent(lineContainer); + lineScrolledComposite.setExpandHorizontal(true); + lineScrolledComposite.setExpandVertical(true); + + if (definition == null) { + definition = new CustomTxtTraceDefinition(); + definition.inputs.add(new InputLine(Cardinality.ZERO_OR_MORE, DEFAULT_REGEX, + Arrays.asList(new InputData(CustomTraceDefinition.TAG_MESSAGE, CustomTraceDefinition.ACTION_SET)))); + } + loadDefinition(definition); + treeViewer.expandAll(); + lineContainer.layout(); + + logtypeText.addModifyListener(updateListener); + timestampOutputFormatText.addModifyListener(updateListener); + + lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); + + hSash.setWeights(new int[] {1, 2}); + + Composite sashBottom = new Composite(vSash, SWT.NONE); + GridLayout sashBottomLayout = new GridLayout(3, false); + sashBottomLayout.marginHeight = 0; + sashBottomLayout.marginWidth = 0; + sashBottom.setLayout(sashBottomLayout); + + Label previewLabel = new Label(sashBottom, SWT.NULL); + previewLabel.setText(Messages.CustomTxtParserInputWizardPage_previewInput); + previewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Button highlightAllButton = new Button(sashBottom, SWT.PUSH); + highlightAllButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + highlightAllButton.setText(Messages.CustomTxtParserInputWizardPage_highlightAll); + highlightAllButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updatePreviews(true); + } + }); + + Button legendButton = new Button(sashBottom, SWT.PUSH); + legendButton.setImage(helpImage); + legendButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_previewLegend); + legendButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + legendButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + openLegend(); + } + }); + + inputText = new StyledText(sashBottom, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + if (fixedFont == null) { + if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ + fixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ + } else { + fixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ + } + } + inputText.setFont(fixedFont); + gd = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); + gd.heightHint = inputText.computeSize(SWT.DEFAULT, inputText.getLineHeight() * 4).y; + gd.widthHint = 800; + inputText.setLayoutData(gd); + inputText.setText(getSelectionText()); + inputText.addModifyListener(updateListener); + + vSash.setWeights(new int[] {hSash.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sashBottom.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); + + setControl(container); + + validate(); + updatePreviews(); + } + + private static class InputLineTreeNodeContentProvider implements ITreeContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + return ((List) inputElement).toArray(); + } + + @Override + public Object[] getChildren(Object parentElement) { + InputLine inputLine = (InputLine) parentElement; + if (inputLine.childrenInputs == null) { + return new InputLine[0]; + } + return inputLine.childrenInputs.toArray(); + } + + @Override + public boolean hasChildren(Object element) { + InputLine inputLine = (InputLine) element; + return (inputLine.childrenInputs != null && inputLine.childrenInputs.size() > 0); + } + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + + @Override + public Object getParent(Object element) { + InputLine inputLine = (InputLine) element; + return inputLine.parentInput; + } + } + + private class InputLineTreeLabelProvider extends ColumnLabelProvider { + + @Override + public Image getImage(Object element) { + return lineImage; + } + + @Override + public String getText(Object element) { + InputLine inputLine = (InputLine) element; + if (inputLine.parentInput == null) { + return "Root Line " + getName(inputLine) + " " + inputLine.cardinality.toString() + " : " + inputLine.getRegex(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + return "Line " + getName(inputLine) + " " + inputLine.cardinality.toString() + " : " + inputLine.getRegex(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + + private class InputLineTreeSelectionChangedListener implements ISelectionChangedListener { + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (selectedLine != null) { + selectedLine.dispose(); + } + if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + InputLine inputLine = (InputLine) selection.getFirstElement(); + selectedLine = new Line(lineContainer, getName(inputLine), inputLine); + lineContainer.layout(); + lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); + container.layout(); + validate(); + updatePreviews(); + } + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.DialogPage#dispose() + */ + @Override + public void dispose() { + if (fixedFont != null) { + fixedFont.dispose(); + fixedFont = null; + } + super.dispose(); + } + + private void loadDefinition(CustomTxtTraceDefinition def) { + logtypeText.setText(def.definitionName); + timestampOutputFormatText.setText(def.timeStampOutputFormat); + treeViewer.setInput(def.inputs); + if (def.inputs.size() > 0) { + InputLine inputLine = def.inputs.get(0); + treeViewer.setSelection(new StructuredSelection(inputLine)); + } + } + + private String getName(InputLine inputLine) { + if (inputLine.parentInput == null) { + return Integer.toString(definition.inputs.indexOf(inputLine)+1); + } + return getName(inputLine.parentInput) + "." + Integer.toString(inputLine.parentInput.childrenInputs.indexOf(inputLine)+1); //$NON-NLS-1$ + } + + public List getInputNames() { + List inputs = new ArrayList(); + for (InputLine inputLine : definition.inputs) { + for (String inputName : getInputNames(inputLine)) { + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + } + return inputs; + } + + public List getInputNames(InputLine inputLine) { + List inputs = new ArrayList(); + if (inputLine.columns != null) { + for (InputData inputData : inputLine.columns) { + String inputName = inputData.name; + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + } + if (inputLine.childrenInputs != null) { + for (InputLine childInputLine : inputLine.childrenInputs) { + for (String inputName : getInputNames(childInputLine)) { + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + } + } + return inputs; + } + + private void removeLine() { + selectedLine.dispose(); + selectedLine = null; + lineContainer.layout(); + lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); + container.layout(); + } + + private String getSelectionText() { + if (this.selection instanceof IStructuredSelection) { + Object selection = ((IStructuredSelection)this.selection).getFirstElement(); + if (selection instanceof IFile) { + IFile file = (IFile)selection; + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(file.getContents())); + StringBuilder sb = new StringBuilder(); + String line = null; + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); //$NON-NLS-1$ + } + return sb.toString(); + } catch (CoreException e) { + return ""; //$NON-NLS-1$ + } catch (IOException e) { + return ""; //$NON-NLS-1$ + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + } + } + } + } + } + return ""; //$NON-NLS-1$ + } + + private void updatePreviews() { + updatePreviews(false); + } + + private void updatePreviews(boolean updateAll) { + if (inputText == null) { + // early update during construction + return; + } + inputText.setStyleRanges(new StyleRange[] {}); + + Scanner scanner = new Scanner(inputText.getText()); + scanner.useDelimiter("\n"); //$NON-NLS-1$ + int rawPos = 0; + String skip; // skip starting delimiters + if ((skip = scanner.findWithinHorizon("\\A\n+", 0)) != null) { //$NON-NLS-1$ + rawPos += skip.length(); + } + + timeStampFormat = null; + if (selectedLine != null) { + for (InputGroup input : selectedLine.inputs) { + input.previewText.setText(Messages.CustomTxtParserInputWizardPage_noMathcingLine); + } + } + + Map data = new HashMap(); + int rootLineMatches = 0; + String firstEntryTimeStamp = null; + String firstEntryTimeStampInputFormat = null; + String log = null; + event: + while (scanner.hasNext()) { + if (rootLineMatches > 0 && !updateAll) { + break; + } + if (log == null) { + log = scanner.next(); + } + int length = log.length(); + for (InputLine rootInputLine : definition.inputs) { + Pattern pattern; + try { + pattern = rootInputLine.getPattern(); + } catch (PatternSyntaxException e) { + continue; + } + Matcher matcher = pattern.matcher(log); + if (matcher.find()) { + rootLineMatches++; + inputText.setStyleRange(new StyleRange(rawPos, length, + COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); + data = new HashMap(); + timeStampFormat = null; + updatePreviewLine(rootInputLine, matcher, data, rawPos, rootLineMatches); + if (rootLineMatches == 1) { + firstEntryTimeStamp = data.get(CustomTraceDefinition.TAG_TIMESTAMP); + firstEntryTimeStampInputFormat = timeStampFormat; + } + HashMap countMap = new HashMap(); + InputLine currentInput = null; + if (rootInputLine.childrenInputs != null && rootInputLine.childrenInputs.size() > 0) { + currentInput = rootInputLine.childrenInputs.get(0); + countMap.put(currentInput, 0); + } + rawPos += length + 1; // +1 for \n + while (scanner.hasNext()) { + log = scanner.next(); + length = log.length(); + boolean processed = false; + if (currentInput == null) { + for (InputLine input : definition.inputs) { + matcher = input.getPattern().matcher(log); + if (matcher.find()) { + continue event; + } + } + } else { + if (countMap.get(currentInput) >= currentInput.getMinCount()) { + List nextInputs = currentInput.getNextInputs(countMap); + if (nextInputs.size() == 0 || nextInputs.get(nextInputs.size() - 1).getMinCount() == 0) { + for (InputLine input : definition.inputs) { + matcher = input.getPattern().matcher(log); + if (matcher.find()) { + continue event; + } + } + } + for (InputLine input : nextInputs) { + matcher = input.getPattern().matcher(log); + if (matcher.find()) { + inputText.setStyleRange(new StyleRange(rawPos, length, + COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); + currentInput = input; + updatePreviewLine(currentInput, matcher, data, rawPos, rootLineMatches); + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 1); + } else { + countMap.put(currentInput, countMap.get(currentInput) + 1); + } + Iterator iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { + currentInput = currentInput.childrenInputs.get(0); + countMap.put(currentInput, 0); + } else { + if (countMap.get(currentInput) >= currentInput.getMaxCount()) { + if (currentInput.getNextInputs(countMap).size() > 0) { + currentInput = currentInput.getNextInputs(countMap).get(0); + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 0); + } + iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + } else { + currentInput = null; + } + } + } + processed = true; + break; + } + } + } + if (! processed) { + matcher = currentInput.getPattern().matcher(log); + if (matcher.find()) { + inputText.setStyleRange(new StyleRange(rawPos, length, + COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); + updatePreviewLine(currentInput, matcher, data, rawPos, rootLineMatches); + countMap.put(currentInput, countMap.get(currentInput) + 1); + if (currentInput.childrenInputs != null && currentInput.childrenInputs.size() > 0) { + currentInput = currentInput.childrenInputs.get(0); + countMap.put(currentInput, 0); + } else { + if (countMap.get(currentInput) >= currentInput.getMaxCount()) { + if (currentInput.getNextInputs(countMap).size() > 0) { + currentInput = currentInput.getNextInputs(countMap).get(0); + if (countMap.get(currentInput) == null) { + countMap.put(currentInput, 0); + } + Iterator iter = countMap.keySet().iterator(); + while (iter.hasNext()) { + InputLine inputLine = iter.next(); + if (inputLine.level > currentInput.level) { + iter.remove(); + } + } + } else { + currentInput = null; + } + } + } + } + } + } + rawPos += length + 1; // +1 for \n + } + + break; + } + } + rawPos += length + 1; // +1 for \n + log = null; + } + scanner.close(); + if (rootLineMatches == 1) { + firstEntryTimeStamp = data.get(CustomTraceDefinition.TAG_TIMESTAMP); + firstEntryTimeStampInputFormat = timeStampFormat; + } + if (firstEntryTimeStamp == null) { + timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noTimestampGroup); + if (selectedLine != null) { + for (InputGroup group : selectedLine.inputs) { + if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + timestampPreviewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingTimestamp); + break; + } + } + } + } else { + try { + SimpleDateFormat dateFormat = new SimpleDateFormat(firstEntryTimeStampInputFormat); + Date date = dateFormat.parse(firstEntryTimeStamp); + dateFormat = new SimpleDateFormat(timestampOutputFormatText.getText().trim()); + timestampPreviewText.setText(dateFormat.format(date)); + } catch (ParseException e) { + timestampPreviewText.setText("*parse exception* [" + firstEntryTimeStamp + "] <> [" + firstEntryTimeStampInputFormat + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } catch (IllegalArgumentException e) { + timestampPreviewText.setText("*parse exception* [Illegal Argument]"); //$NON-NLS-1$ + } + + } + } + + private void updatePreviewLine(InputLine line, Matcher matcher, Map data, int rawPos, int rootLineMatches) { + for (int i = 0; i < line.columns.size(); i++) { + InputData input = line.columns.get(i); + if (i < matcher.groupCount() && matcher.group(i+1) != null) { + if (line.parentInput == null) { + inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), + COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); + } else { + inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), + COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); + } + String value = matcher.group(i+1).trim(); + if (selectedLine != null && selectedLine.inputLine.equals(line) && rootLineMatches == 1) { + if (selectedLine.inputs.get(i).previewText.getText().equals(Messages.CustomTxtParserInputWizardPage_noMatchingLine)) { + selectedLine.inputs.get(i).previewText.setText(value); + } + } + if (value.length() == 0) { + continue; + } + if (input.action == CustomTraceDefinition.ACTION_SET) { + data.put(input.name, value); + if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + timeStampFormat = input.format; + } + } else if (input.action == CustomTraceDefinition.ACTION_APPEND) { + String s = data.get(input.name); + if (s != null) { + data.put(input.name, s + value); + } else { + data.put(input.name, value); + } + if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + if (timeStampFormat != null) { + timeStampFormat += input.format; + } else { + timeStampFormat = input.format; + } + } + } else if (input.action == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { + String s = data.get(input.name); + if (s != null) { + data.put(input.name, s + " | " + value); //$NON-NLS-1$ + } else { + data.put(input.name, value); + } + if (input.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + if (timeStampFormat != null) { + timeStampFormat += " | " + input.format; //$NON-NLS-1$ + } else { + timeStampFormat = input.format; + } + } + } + } else { + if (selectedLine != null && selectedLine.inputLine.equals(line) && rootLineMatches == 1) { + if (selectedLine.inputs.get(i).previewText.getText().equals(Messages.CustomTxtParserInputWizardPage_noMatchingLine)) { + selectedLine.inputs.get(i).previewText.setText(Messages.CustomTxtParserInputWizardPage_noMatchingGroup); + } + } + } + } + // highlight the matching groups that have no corresponponding input + for (int i = line.columns.size(); i < matcher.groupCount(); i++) { + if (matcher.group(i+1) != null) { + if (line.parentInput == null) { + inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), + COLOR_BLACK, COLOR_MAGENTA)); + } else { + inputText.setStyleRange(new StyleRange(rawPos + matcher.start(i+1), matcher.end(i+1) - matcher.start(i+1), + COLOR_BLACK, COLOR_LIGHT_MAGENTA)); + } + } + } + } + + private void openHelpShell(String url) { + if (helpBrowser != null && !helpBrowser.isDisposed()) { + helpBrowser.getShell().setActive(); + if (!helpBrowser.getUrl().equals(url)) { + helpBrowser.setUrl(url); + } + return; + } + final Shell helpShell = new Shell(getShell(), SWT.SHELL_TRIM); + helpShell.setLayout(new FillLayout()); + helpBrowser = new Browser(helpShell, SWT.NONE); + helpBrowser.addTitleListener(new TitleListener() { + @Override + public void changed(TitleEvent event) { + helpShell.setText(event.title); + } + }); + helpBrowser.setBounds(0,0,600,400); + helpShell.pack(); + helpShell.open(); + helpBrowser.setUrl(url); + } + + private void openLegend() { + final String CG = Messages.CustomTxtParserInputWizardPage_capturedGroup; + final String UCG = Messages.CustomTxtParserInputWizardPage_unidentifiedCaptureGroup; + final String UT = Messages.CustomTxtParserInputWizardPage_uncapturedText; + int line1start = 0; + String line1 = Messages.CustomTxtParserInputWizardPage_nonMatchingLine; + int line2start = line1start + line1.length(); + String line2 = Messages.CustomTxtParserInputWizardPage_matchingLineRoot + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + int line3start = line2start + line2.length(); + String line3 = Messages.CustomTxtParserInputWizardPage_matchingOtherLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + int line4start = line3start + line3.length(); + String line4 = Messages.CustomTxtParserInputWizardPage_matchingOtherLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + int line5start = line4start + line4.length(); + String line5 = Messages.CustomTxtParserInputWizardPage_nonMatchingLine; + int line6start = line5start + line5.length(); + String line6 = Messages.CustomTxtParserInputWizardPage_matchingRootLine + CG + " " + UCG + " " + UT + " \n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + final Shell legendShell = new Shell(getShell(), SWT.DIALOG_TRIM); + legendShell.setLayout(new FillLayout()); + StyledText legendText = new StyledText(legendShell, SWT.MULTI); + legendText.setFont(fixedFont); + legendText.setText(line1 + line2 + line3 + line4 + line5 + line6); + legendText.setStyleRange(new StyleRange(line2start, line2.length(), COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); + legendText.setStyleRange(new StyleRange(line3start, line3.length(), COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); + legendText.setStyleRange(new StyleRange(line4start, line4.length(), COLOR_BLACK, COLOR_LIGHT_YELLOW, SWT.ITALIC)); + legendText.setStyleRange(new StyleRange(line6start, line6.length(), COLOR_BLACK, COLOR_YELLOW, SWT.ITALIC)); + legendText.setStyleRange(new StyleRange(line2start + line2.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); + legendText.setStyleRange(new StyleRange(line2start + line2.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_MAGENTA)); + legendText.setStyleRange(new StyleRange(line3start + line3.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); + legendText.setStyleRange(new StyleRange(line3start + line3.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_LIGHT_MAGENTA)); + legendText.setStyleRange(new StyleRange(line4start + line4.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_LIGHT_GREEN, SWT.BOLD)); + legendText.setStyleRange(new StyleRange(line4start + line4.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_LIGHT_MAGENTA)); + legendText.setStyleRange(new StyleRange(line6start + line6.indexOf(CG), CG.length(), COLOR_BLACK, COLOR_GREEN, SWT.BOLD)); + legendText.setStyleRange(new StyleRange(line6start + line6.indexOf(UCG), UCG.length(), COLOR_BLACK, COLOR_MAGENTA)); + legendShell.setText(Messages.CustomTxtParserInputWizardPage_previewLegend); + legendShell.pack(); + legendShell.open(); + } + + private class UpdateListener implements ModifyListener, SelectionListener { + + @Override + public void modifyText(ModifyEvent e) { + validate(); + updatePreviews(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + validate(); + updatePreviews(); + } + + @Override + public void widgetSelected(SelectionEvent e) { + validate(); + updatePreviews(); + } + + } + + private class Line { + private static final String INFINITY_STRING = "\u221E"; //$NON-NLS-1$ + InputLine inputLine; + Group group; + Composite labelComposite; + Text regexText; + Composite cardinalityContainer; + Combo cardinalityCombo; + Label cardinalityMinLabel; + Text cardinalityMinText; + Label cardinalityMaxLabel; + Text cardinalityMaxText; + Button infiniteButton; + List inputs = new ArrayList(); + Button addGroupButton; + Label addGroupLabel; + + public Line(Composite parent, String name, InputLine inputLine) { + this.inputLine = inputLine; + + group = new Group(parent, SWT.NONE); + group.setText(name); + group.setLayout(new GridLayout(2, false)); + group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + labelComposite = new Composite(group, SWT.FILL); + GridLayout labelLayout = new GridLayout(1, false); + labelLayout.marginWidth = 0; + labelLayout.marginHeight = 0; + labelComposite.setLayout(labelLayout); + labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + Label label = new Label(labelComposite, SWT.NULL); + label.setText(Messages.CustomTxtParserInputWizardPage_regularExpression); + + Composite regexContainer = new Composite(group, SWT.NONE); + GridLayout regexLayout = new GridLayout(2, false); + regexLayout.marginHeight = 0; + regexLayout.marginWidth = 0; + regexContainer.setLayout(regexLayout); + regexContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + regexText = new Text(regexContainer, SWT.BORDER | SWT.SINGLE); + GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + regexText.setLayoutData(gd); + regexText.setText(inputLine.getRegex()); + regexText.addModifyListener(updateListener); + + Button regexHelpButton = new Button(regexContainer, SWT.PUSH); + regexHelpButton.setImage(helpImage); + regexHelpButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_regularExpressionHelp); + regexHelpButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + openHelpShell(PATTERN_URL); + } + }); + + label = new Label(group, SWT.NONE); + label.setText(Messages.CustomTxtParserInputWizardPage_cardinality); + label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + cardinalityContainer = new Composite(group, SWT.NONE); + GridLayout cardinalityLayout = new GridLayout(6, false); + cardinalityLayout.marginHeight = 0; + cardinalityLayout.marginWidth = 0; + cardinalityContainer.setLayout(cardinalityLayout); + cardinalityContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + cardinalityCombo = new Combo(cardinalityContainer, SWT.DROP_DOWN | SWT.READ_ONLY); + cardinalityCombo.setItems(new String[] { + Cardinality.ZERO_OR_MORE.toString(), + Cardinality.ONE_OR_MORE.toString(), + Cardinality.ZERO_OR_ONE.toString(), + Cardinality.ONE.toString(), + "(?,?)"}); //$NON-NLS-1$ + cardinalityCombo.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + switch (cardinalityCombo.getSelectionIndex()) { + case 4: //(?,?) + cardinalityMinLabel.setVisible(true); + cardinalityMinText.setVisible(true); + cardinalityMaxLabel.setVisible(true); + cardinalityMaxText.setVisible(true); + infiniteButton.setVisible(true); + break; + default: + cardinalityMinLabel.setVisible(false); + cardinalityMinText.setVisible(false); + cardinalityMaxLabel.setVisible(false); + cardinalityMaxText.setVisible(false); + infiniteButton.setVisible(false); + break; + } + cardinalityContainer.layout(); + validate(); + updatePreviews(); + }}); + + cardinalityMinLabel = new Label(cardinalityContainer, SWT.NONE); + cardinalityMinLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + cardinalityMinLabel.setText(Messages.CustomTxtParserInputWizardPage_min); + cardinalityMinLabel.setVisible(false); + + cardinalityMinText = new Text(cardinalityContainer, SWT.BORDER | SWT.SINGLE); + gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); + gd.widthHint = 20; + cardinalityMinText.setLayoutData(gd); + cardinalityMinText.setVisible(false); + + cardinalityMaxLabel = new Label(cardinalityContainer, SWT.NONE); + cardinalityMaxLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + cardinalityMaxLabel.setText(Messages.CustomTxtParserInputWizardPage_max); + cardinalityMaxLabel.setVisible(false); + + cardinalityMaxText = new Text(cardinalityContainer, SWT.BORDER | SWT.SINGLE); + gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); + gd.widthHint = 20; + cardinalityMaxText.setLayoutData(gd); + cardinalityMaxText.setVisible(false); + + infiniteButton = new Button(cardinalityContainer, SWT.PUSH); + infiniteButton.setText(INFINITY_STRING); + infiniteButton.setVisible(false); + infiniteButton.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e) { + cardinalityMaxText.setText(INFINITY_STRING); + }}); + + if (inputLine.cardinality.equals(Cardinality.ZERO_OR_MORE)) { + cardinalityCombo.select(0); + } else if (inputLine.cardinality.equals(Cardinality.ONE_OR_MORE)) { + cardinalityCombo.select(1); + } else if (inputLine.cardinality.equals(Cardinality.ZERO_OR_ONE)) { + cardinalityCombo.select(2); + } else if (inputLine.cardinality.equals(Cardinality.ONE)) { + cardinalityCombo.select(3); + } else { + cardinalityCombo.select(4); + cardinalityMinLabel.setVisible(true); + cardinalityMinText.setVisible(true); + if (inputLine.getMinCount() >= 0) { + cardinalityMinText.setText(Integer.toString(inputLine.getMinCount())); + } + cardinalityMaxLabel.setVisible(true); + cardinalityMaxText.setVisible(true); + if (inputLine.getMaxCount() == Cardinality.INF) { + cardinalityMaxText.setText(INFINITY_STRING); + } else if (inputLine.getMaxCount() >= 0) { + cardinalityMaxText.setText(Integer.toString(inputLine.getMaxCount())); + } + infiniteButton.setVisible(true); + } + + VerifyListener digitsListener = new VerifyListener() { + @Override + public void verifyText(VerifyEvent e) { + if (e.text.equals(INFINITY_STRING)) { + e.doit = e.widget == cardinalityMaxText && e.start == 0 && e.end == ((Text) e.widget).getText().length(); + } else { + if (((Text) e.widget).getText().equals(INFINITY_STRING)) { + e.doit = e.start == 0 && e.end == ((Text) e.widget).getText().length(); + } + for (int i = 0; i < e.text.length(); i++) { + if (!Character.isDigit(e.text.charAt(i))) { + e.doit = false; + break; + } + } + } + }}; + + cardinalityMinText.addModifyListener(updateListener); + cardinalityMaxText.addModifyListener(updateListener); + cardinalityMinText.addVerifyListener(digitsListener); + cardinalityMaxText.addVerifyListener(digitsListener); + + if (inputLine.columns != null) { + for (InputData inputData : inputLine.columns) { + InputGroup inputGroup = new InputGroup(group, this, inputs.size()+1); + if (inputData.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + inputGroup.tagCombo.select(0); + inputGroup.tagText.setText(inputData.format); + inputGroup.tagLabel.setText(Messages.CustomTxtParserInputWizardPage_format); + inputGroup.tagLabel.setVisible(true); + inputGroup.tagText.setVisible(true); + inputGroup.tagText.addModifyListener(updateListener); + } else if (inputData.name.equals(CustomTraceDefinition.TAG_MESSAGE)) { + inputGroup.tagCombo.select(1); + } else { + inputGroup.tagCombo.select(2); + inputGroup.tagText.setText(inputData.name); + inputGroup.tagLabel.setText(Messages.CustomTxtParserInputWizardPage_name); + inputGroup.tagLabel.setVisible(true); + inputGroup.tagText.setVisible(true); + inputGroup.tagText.addModifyListener(updateListener); + } + inputGroup.actionCombo.select(inputData.action); + inputs.add(inputGroup); + } + } + + createAddGroupButton(); + } + + private void createAddGroupButton() { + addGroupButton = new Button(group, SWT.PUSH); + addGroupButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + addGroupButton.setImage(addImage); + addGroupButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_addGroup); + addGroupButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + removeAddGroupButton(); + inputs.add(new InputGroup(group, Line.this, inputs.size()+1)); + createAddGroupButton(); + lineContainer.layout(); + lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); + group.getParent().layout(); + validate(); + updatePreviews(); + } + }); + + addGroupLabel = new Label(group, SWT.NULL); + addGroupLabel.setText(Messages.CustomTxtParserInputWizardPage_newGroup); + } + + private void removeAddGroupButton() { + addGroupButton.dispose(); + addGroupLabel.dispose(); + } + + private void removeInput(int inputNumber) { + if (--inputNumber < inputs.size()) { + inputs.remove(inputNumber).dispose(); + for (int i = inputNumber; i < inputs.size(); i++) { + inputs.get(i).setInputNumber(i+1); + } + lineContainer.layout(); + lineScrolledComposite.setMinSize(lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, lineContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-1); + group.getParent().layout(); + } + } + +// private void setName(String name) { +// this.name = name; +// group.setText("Line " + name); +// } + + private void dispose() { + group.dispose(); + } + + private void extractInputs() { + inputLine.setRegex(selectedLine.regexText.getText()); + switch (cardinalityCombo.getSelectionIndex()) { + case 0: + inputLine.cardinality = Cardinality.ZERO_OR_MORE; + break; + case 1: + inputLine.cardinality = Cardinality.ONE_OR_MORE; + break; + case 2: + inputLine.cardinality = Cardinality.ZERO_OR_ONE; + break; + case 3: + inputLine.cardinality = Cardinality.ONE; + break; + case 4: //(?,?) + int min, max; + try { + min = Integer.parseInt(cardinalityMinText.getText()); + } catch (NumberFormatException e) { + min = -1; + } + try { + if (cardinalityMaxText.getText().equals(INFINITY_STRING)) { + max = Cardinality.INF; + } else { + max = Integer.parseInt(cardinalityMaxText.getText()); + } + } catch (NumberFormatException e) { + max = -1; + } + inputLine.cardinality = new Cardinality(min, max); + break; + default: + inputLine.cardinality = Cardinality.ZERO_OR_MORE; + break; + } + inputLine.columns = new ArrayList(inputs.size()); + for (int i = 0; i < inputs.size(); i++) { + InputGroup group = inputs.get(i); + InputData inputData = new InputData(); + if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { + inputData.name = group.tagText.getText().trim(); + } else { + inputData.name = group.tagCombo.getText(); + if (group.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + inputData.format = group.tagText.getText().trim(); + } + } + inputData.action = group.actionCombo.getSelectionIndex(); + inputLine.columns.add(inputData); + } + } + } + + private class InputGroup { + Line line; + int inputNumber; + + // children of parent (must be disposed) + Composite labelComposite; + Composite tagComposite; + Label previewLabel; + Text previewText; + + // children of labelComposite + Label inputLabel; + + // children of tagComposite + Combo tagCombo; + Label tagLabel; + Text tagText; + Combo actionCombo; + + public InputGroup(Composite parent, Line line, int inputNumber) { + this.line = line; + this.inputNumber = inputNumber; + + labelComposite = new Composite(parent, SWT.FILL); + GridLayout labelLayout = new GridLayout(2, false); + labelLayout.marginWidth = 0; + labelLayout.marginHeight = 0; + labelComposite.setLayout(labelLayout); + labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + Button deleteButton = new Button(labelComposite, SWT.PUSH); + deleteButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + deleteButton.setImage(deleteImage); + deleteButton.setToolTipText(Messages.CustomTxtParserInputWizardPage_removeGroup); + deleteButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputGroup.this.line.removeInput(InputGroup.this.inputNumber); + validate(); + updatePreviews(); + } + }); + + inputLabel = new Label(labelComposite, SWT.NULL); + inputLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + inputLabel.setText(Messages.CustomTxtParserInputWizardPage_group + inputNumber + ":"); //$NON-NLS-1$ + + tagComposite = new Composite(parent, SWT.FILL); + GridLayout tagLayout = new GridLayout(4, false); + tagLayout.marginWidth = 0; + tagLayout.marginHeight = 0; + tagComposite.setLayout(tagLayout); + tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + tagCombo.setItems(new String[] {CustomTraceDefinition.TAG_TIMESTAMP, + CustomTraceDefinition.TAG_MESSAGE, + CustomTraceDefinition.TAG_OTHER}); + tagCombo.select(1); + tagCombo.addSelectionListener(new SelectionListener(){ + @Override + public void widgetDefaultSelected(SelectionEvent e) {} + @Override + public void widgetSelected(SelectionEvent e) { + tagText.removeModifyListener(updateListener); + switch (tagCombo.getSelectionIndex()) { + case 0: //Time Stamp + tagLabel.setText(Messages.CustomTxtParserInputWizardPage_format); + tagLabel.setVisible(true); + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + break; + case 1: //Message + tagLabel.setVisible(false); + tagText.setVisible(false); + break; + case 2: //Other + tagLabel.setText(Messages.CustomTxtParserInputWizardPage_name); + tagLabel.setVisible(true); + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + break; + case 3: //Continue + tagLabel.setVisible(false); + tagText.setVisible(false); + break; + default: + break; + } + tagComposite.layout(); + validate(); + updatePreviews(); + }}); + + tagLabel = new Label(tagComposite, SWT.NULL); + tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + tagLabel.setVisible(false); + + tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); + GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + tagText.setLayoutData(gd); + tagText.setVisible(false); + + actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + actionCombo.setItems(new String[] {Messages.CustomTxtParserInputWizardPage_set, Messages.CustomTxtParserInputWizardPage_append, Messages.CustomTxtParserInputWizardPage_appendWith}); + actionCombo.select(0); + actionCombo.addSelectionListener(updateListener); + + previewLabel = new Label(parent, SWT.NULL); + previewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + previewLabel.setText(Messages.CustomTxtParserInputWizardPage_preview); + + previewText = new Text(parent, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); + gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + previewText.setLayoutData(gd); + previewText.setText(Messages.CustomTxtParserInputWizardPage_noMatch); + previewText.setBackground(COLOR_WIDGET_BACKGROUND); + } + + private void dispose() { + labelComposite.dispose(); + tagComposite.dispose(); + previewLabel.dispose(); + previewText.dispose(); + } + + private void setInputNumber(int inputNumber) { + this.inputNumber = inputNumber; + inputLabel.setText(Messages.CustomTxtParserInputWizardPage_group + inputNumber + ":"); //$NON-NLS-1$ + labelComposite.layout(); + } + } + + private void validate() { + + definition.definitionName = logtypeText.getText().trim(); + definition.timeStampOutputFormat = timestampOutputFormatText.getText().trim(); + + if (selectedLine != null) { + selectedLine.extractInputs(); + treeViewer.refresh(); + } + + StringBuffer errors = new StringBuffer(); + + if (definition.definitionName.length() == 0) { + errors.append("Enter a name for the new log type. "); //$NON-NLS-1$ + logtypeText.setBackground(COLOR_LIGHT_RED); + } else { + logtypeText.setBackground(COLOR_TEXT_BACKGROUND); + for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { + if (definition.definitionName.equals(def.definitionName)) { + if (editDefinitionName == null || ! editDefinitionName.equals(definition.definitionName)) { + errors.append("The log type name already exists. "); //$NON-NLS-1$ + logtypeText.setBackground(COLOR_LIGHT_RED); + break; + } + } + } + } + + timestampFound = false; + for (int i = 0; i < definition.inputs.size(); i++) { + + InputLine inputLine = definition.inputs.get(i); + String name = Integer.toString(i+1); + errors.append(validateLine(inputLine, name)); + } + if (timestampFound) { + if (definition.timeStampOutputFormat.length() == 0) { + errors.append("Enter the output format for the Time Stamp field. "); //$NON-NLS-1$ + timestampOutputFormatText.setBackground(COLOR_LIGHT_RED); + } else { + try { + new SimpleDateFormat(definition.timeStampOutputFormat); + timestampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); + } catch (IllegalArgumentException e) { + errors.append("Enter a valid output format for the Time Stamp field. "); //$NON-NLS-1$ + timestampOutputFormatText.setBackground(COLOR_LIGHT_RED); + } + } + + } else { + timestampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); +// timestampPreviewText.setBackground(COLOR_WIDGET_BACKGROUND); +// errors.append("Identify a Time Stamp group (Line "+name+"). "); +// timestampPreviewText.setText("*no timestamp group*"); +// timestampPreviewText.setBackground(COLOR_LIGHT_RED); + } + + if (errors.length() == 0) { + setDescription(defaultDescription); + setPageComplete(true); + } else { + setDescription(errors.toString()); + setPageComplete(false); + } + } + + public StringBuffer validateLine(InputLine inputLine, String name) { + StringBuffer errors = new StringBuffer(); + Line line = null; + if (selectedLine != null && selectedLine.inputLine.equals(inputLine)) { + line = selectedLine; + } + try { + Pattern.compile(inputLine.getRegex()); + if (line != null) { + line.regexText.setBackground(COLOR_TEXT_BACKGROUND); + } + } catch (PatternSyntaxException e) { + errors.append("Enter a valid regular expression (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ + if (line != null) { + line.regexText.setBackground(COLOR_LIGHT_RED); + } + } + if (inputLine.getMinCount() == -1) { + errors.append("Enter a minimum value for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ + if (line != null) { + line.cardinalityMinText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (line != null) { + line.cardinalityMinText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + if (inputLine.getMaxCount() == -1) { + errors.append("Enter a maximum value for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ + if (line != null) { + line.cardinalityMaxText.setBackground(COLOR_LIGHT_RED); + } + } else if (inputLine.getMinCount() > inputLine.getMaxCount()) { + errors.append("Enter correct (min <= max) values for cardinality (Line "+name+"). "); //$NON-NLS-1$ //$NON-NLS-2$ + if (line != null) { + line.cardinalityMinText.setBackground(COLOR_LIGHT_RED); + } + if (line != null) { + line.cardinalityMaxText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (line != null) { + line.cardinalityMaxText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + for (int i = 0; inputLine.columns != null && i < inputLine.columns.size(); i++) { + InputData inputData = inputLine.columns.get(i); + InputGroup group = null; + if (line != null) { + group = line.inputs.get(i); + } + if (inputData.name.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + timestampFound = true; + if (inputData.format.length() == 0) { + errors.append("Enter the input format for the Time Stamp (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (group != null) { + group.tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + try { + new SimpleDateFormat(inputData.format); + if (group != null) { + group.tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } catch (IllegalArgumentException e) { + errors.append("Enter a valid input format for the Time Stamp (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (group != null) { + group.tagText.setBackground(COLOR_LIGHT_RED); + } + } + } + } else if (inputData.name.length() == 0) { + errors.append("Enter a name for the data group (Line "+name+" Group "+(i+1)+"). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (group != null) { + group.tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (group != null) { + group.tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + } + for (int i = 0; inputLine.childrenInputs != null && i < inputLine.childrenInputs.size(); i++) { + errors.append(validateLine(inputLine.childrenInputs.get(i), name+"."+(i+1))); //$NON-NLS-1$ + } + return errors; + } + + public CustomTxtTraceDefinition getDefinition() { + return definition; + } + + public char[] getInputText() { + return inputText.getText().toCharArray(); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserOutputWizardPage.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserOutputWizardPage.java index ed3f3fa46e..6ba1886686 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserOutputWizardPage.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserOutputWizardPage.java @@ -1,297 +1,297 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; -import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Text; - -public class CustomTxtParserOutputWizardPage extends WizardPage { - - private static final Image upImage = Activator.getDefault().getImageFromPath("/icons/elcl16/up_button.gif"); //$NON-NLS-1$ - private static final Image downImage = Activator.getDefault().getImageFromPath("/icons/elcl16/down_button.gif"); //$NON-NLS-1$ - private final CustomTxtParserWizard wizard; - private CustomTxtTraceDefinition definition; - List outputs = new ArrayList(); - // Output messageOutput; - Composite container; - SashForm sash; - // Text timestampFormatText; - // Text timestampPreviewText; - ScrolledComposite outputsScrolledComposite; - Composite outputsContainer; - // ScrolledComposite inputScrolledComposite; - Composite tableContainer; - CustomEventsTable previewTable; - File tmpFile; - - protected CustomTxtParserOutputWizardPage(final CustomTxtParserWizard wizard) { - super("CustomParserOutputWizardPage"); //$NON-NLS-1$ - setTitle(wizard.inputPage.getTitle()); - setDescription(Messages.CustomTxtParserOutputWizardPage_description); - this.wizard = wizard; - setPageComplete(false); - } - - @Override - public void createControl(final Composite parent) { - container = new Composite(parent, SWT.NULL); - container.setLayout(new GridLayout()); - - sash = new SashForm(container, SWT.VERTICAL); - sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - sash.setBackground(sash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); - - outputsScrolledComposite = new ScrolledComposite(sash, SWT.V_SCROLL); - outputsScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - outputsContainer = new Composite(outputsScrolledComposite, SWT.NONE); - final GridLayout outputsLayout = new GridLayout(4, false); - outputsLayout.marginHeight = 10; - outputsLayout.marginWidth = 0; - outputsContainer.setLayout(outputsLayout); - outputsScrolledComposite.setContent(outputsContainer); - outputsScrolledComposite.setExpandHorizontal(true); - outputsScrolledComposite.setExpandVertical(true); - - outputsContainer.layout(); - - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - - tableContainer = new Composite(sash, SWT.NONE); - final GridLayout tableLayout = new GridLayout(); - tableLayout.marginHeight = 0; - tableLayout.marginWidth = 0; - tableContainer.setLayout(tableLayout); - previewTable = new CustomEventsTable(new CustomTxtTraceDefinition(), tableContainer, 0); - previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - if (wizard.definition != null) - loadDefinition(wizard.definition); - setControl(container); - - } - - @Override - public void dispose() { - previewTable.dispose(); - super.dispose(); - } - - private void loadDefinition(final CustomTxtTraceDefinition definition) { - for (final OutputColumn outputColumn : definition.outputs) { - final Output output = new Output(outputsContainer, outputColumn.name); - outputs.add(output); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) - */ - @Override - public void setVisible(final boolean visible) { - if (visible) { - this.definition = wizard.inputPage.getDefinition(); - final List outputNames = wizard.inputPage.getInputNames(); - - // dispose outputs that have been removed in the input page - final Iterator iter = outputs.iterator(); - while (iter.hasNext()) { - final Output output = iter.next(); - boolean found = false; - for (final String name : outputNames) - if (output.name.equals(name)) { - found = true; - break; - } - if (!found) { - output.dispose(); - iter.remove(); - } - } - - // create outputs that have been added in the input page - for (final String name : outputNames) { - boolean found = false; - for (final Output output : outputs) - if (output.name.equals(name)) { - found = true; - break; - } - if (!found) - outputs.add(new Output(outputsContainer, name)); - } - - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - updatePreviewTable(); - if (sash.getSize().y > outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y + previewTable.getTable().getItemHeight()) - sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sash.getSize().y - outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); - else - sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, previewTable.getTable().getItemHeight()}); - setPageComplete(true); - } else - setPageComplete(false); - super.setVisible(visible); - } - - private void moveBefore(final Output moved) { - final int i = outputs.indexOf(moved); - if (i > 0) { - final Output previous = outputs.get(i-1); - moved.enabledButton.moveAbove(previous.enabledButton); - moved.nameLabel.moveBelow(moved.enabledButton); - moved.upButton.moveBelow(moved.nameLabel); - moved.downButton.moveBelow(moved.upButton); - outputs.add(i-1, outputs.remove(i)); - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - container.layout(); - updatePreviewTable(); - } - } - - private void moveAfter(final Output moved) { - final int i = outputs.indexOf(moved); - if (i+1 < outputs.size()) { - final Output next = outputs.get(i+1); - moved.enabledButton.moveBelow(next.downButton); - moved.nameLabel.moveBelow(moved.enabledButton); - moved.upButton.moveBelow(moved.nameLabel); - moved.downButton.moveBelow(moved.upButton); - outputs.add(i+1, outputs.remove(i)); - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - container.layout(); - updatePreviewTable(); - } - } - - private void updatePreviewTable() { - final int CACHE_SIZE = 50; - definition.outputs = extractOutputs(); - - try { - tmpFile = Activator.getDefault().getStateLocation().addTrailingSeparator().append("customwizard.tmp").toFile(); //$NON-NLS-1$ - final FileWriter writer = new FileWriter(tmpFile); - writer.write(wizard.inputPage.getInputText()); - writer.close(); - - final ITmfTrace trace = new CustomTxtTrace(null, definition, tmpFile.getAbsolutePath(), CACHE_SIZE); - previewTable.dispose(); - previewTable = new CustomEventsTable(definition, tableContainer, CACHE_SIZE); - previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - previewTable.setTrace(trace, true); - } catch (final TmfTraceException e) { - Activator.getDefault().logError("Error creating CustomTxtTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ - } catch (final IOException e) { - Activator.getDefault().logError("Error creating CustomTxtTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ - } - - tableContainer.layout(); - container.layout(); - } - - public List extractOutputs() { - int numColumns = 0; - for (int i = 0; i < outputs.size(); i++) - if (outputs.get(i).enabledButton.getSelection()) - numColumns++; - final List outputColumns = new ArrayList(numColumns); - numColumns = 0; - for (int i = 0; i < outputs.size(); i++) { - final Output output = outputs.get(i); - if (output.enabledButton.getSelection()) { - final OutputColumn column = new OutputColumn(); - column.name = output.nameLabel.getText(); - outputColumns.add(column); - } - } - return outputColumns; - } - - private class Output { - String name; - Button enabledButton; - Text nameLabel; - Button upButton; - Button downButton; - - public Output(final Composite parent, final String name) { - this.name = name; - - enabledButton = new Button(parent, SWT.CHECK); - enabledButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_visible); - enabledButton.setSelection(true); - enabledButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - updatePreviewTable(); - } - }); - // if (messageOutput != null) { - // enabledButton.moveAbove(messageOutput.enabledButton); - // } - - nameLabel = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE); - nameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - nameLabel.setText(name); - nameLabel.moveBelow(enabledButton); - - upButton = new Button(parent, SWT.PUSH); - upButton.setImage(upImage); - upButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_moveBefore); - upButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - moveBefore(Output.this); - } - }); - upButton.moveBelow(nameLabel); - - downButton = new Button(parent, SWT.PUSH); - downButton.setImage(downImage); - downButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_moveAfter); - downButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - moveAfter(Output.this); - } - }); - downButton.moveBelow(upButton); - } - - private void dispose() { - enabledButton.dispose(); - nameLabel.dispose(); - upButton.dispose(); - downButton.dispose(); - } - } - - public CustomTxtTraceDefinition getDefinition() { - return definition; - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; +import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; + +public class CustomTxtParserOutputWizardPage extends WizardPage { + + private static final Image upImage = Activator.getDefault().getImageFromPath("/icons/elcl16/up_button.gif"); //$NON-NLS-1$ + private static final Image downImage = Activator.getDefault().getImageFromPath("/icons/elcl16/down_button.gif"); //$NON-NLS-1$ + private final CustomTxtParserWizard wizard; + private CustomTxtTraceDefinition definition; + List outputs = new ArrayList(); + // Output messageOutput; + Composite container; + SashForm sash; + // Text timestampFormatText; + // Text timestampPreviewText; + ScrolledComposite outputsScrolledComposite; + Composite outputsContainer; + // ScrolledComposite inputScrolledComposite; + Composite tableContainer; + CustomEventsTable previewTable; + File tmpFile; + + protected CustomTxtParserOutputWizardPage(final CustomTxtParserWizard wizard) { + super("CustomParserOutputWizardPage"); //$NON-NLS-1$ + setTitle(wizard.inputPage.getTitle()); + setDescription(Messages.CustomTxtParserOutputWizardPage_description); + this.wizard = wizard; + setPageComplete(false); + } + + @Override + public void createControl(final Composite parent) { + container = new Composite(parent, SWT.NULL); + container.setLayout(new GridLayout()); + + sash = new SashForm(container, SWT.VERTICAL); + sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + sash.setBackground(sash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); + + outputsScrolledComposite = new ScrolledComposite(sash, SWT.V_SCROLL); + outputsScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + outputsContainer = new Composite(outputsScrolledComposite, SWT.NONE); + final GridLayout outputsLayout = new GridLayout(4, false); + outputsLayout.marginHeight = 10; + outputsLayout.marginWidth = 0; + outputsContainer.setLayout(outputsLayout); + outputsScrolledComposite.setContent(outputsContainer); + outputsScrolledComposite.setExpandHorizontal(true); + outputsScrolledComposite.setExpandVertical(true); + + outputsContainer.layout(); + + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + + tableContainer = new Composite(sash, SWT.NONE); + final GridLayout tableLayout = new GridLayout(); + tableLayout.marginHeight = 0; + tableLayout.marginWidth = 0; + tableContainer.setLayout(tableLayout); + previewTable = new CustomEventsTable(new CustomTxtTraceDefinition(), tableContainer, 0); + previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + if (wizard.definition != null) + loadDefinition(wizard.definition); + setControl(container); + + } + + @Override + public void dispose() { + previewTable.dispose(); + super.dispose(); + } + + private void loadDefinition(final CustomTxtTraceDefinition definition) { + for (final OutputColumn outputColumn : definition.outputs) { + final Output output = new Output(outputsContainer, outputColumn.name); + outputs.add(output); + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) + */ + @Override + public void setVisible(final boolean visible) { + if (visible) { + this.definition = wizard.inputPage.getDefinition(); + final List outputNames = wizard.inputPage.getInputNames(); + + // dispose outputs that have been removed in the input page + final Iterator iter = outputs.iterator(); + while (iter.hasNext()) { + final Output output = iter.next(); + boolean found = false; + for (final String name : outputNames) + if (output.name.equals(name)) { + found = true; + break; + } + if (!found) { + output.dispose(); + iter.remove(); + } + } + + // create outputs that have been added in the input page + for (final String name : outputNames) { + boolean found = false; + for (final Output output : outputs) + if (output.name.equals(name)) { + found = true; + break; + } + if (!found) + outputs.add(new Output(outputsContainer, name)); + } + + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + updatePreviewTable(); + if (sash.getSize().y > outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y + previewTable.getTable().getItemHeight()) + sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sash.getSize().y - outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); + else + sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, previewTable.getTable().getItemHeight()}); + setPageComplete(true); + } else + setPageComplete(false); + super.setVisible(visible); + } + + private void moveBefore(final Output moved) { + final int i = outputs.indexOf(moved); + if (i > 0) { + final Output previous = outputs.get(i-1); + moved.enabledButton.moveAbove(previous.enabledButton); + moved.nameLabel.moveBelow(moved.enabledButton); + moved.upButton.moveBelow(moved.nameLabel); + moved.downButton.moveBelow(moved.upButton); + outputs.add(i-1, outputs.remove(i)); + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + container.layout(); + updatePreviewTable(); + } + } + + private void moveAfter(final Output moved) { + final int i = outputs.indexOf(moved); + if (i+1 < outputs.size()) { + final Output next = outputs.get(i+1); + moved.enabledButton.moveBelow(next.downButton); + moved.nameLabel.moveBelow(moved.enabledButton); + moved.upButton.moveBelow(moved.nameLabel); + moved.downButton.moveBelow(moved.upButton); + outputs.add(i+1, outputs.remove(i)); + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + container.layout(); + updatePreviewTable(); + } + } + + private void updatePreviewTable() { + final int CACHE_SIZE = 50; + definition.outputs = extractOutputs(); + + try { + tmpFile = Activator.getDefault().getStateLocation().addTrailingSeparator().append("customwizard.tmp").toFile(); //$NON-NLS-1$ + final FileWriter writer = new FileWriter(tmpFile); + writer.write(wizard.inputPage.getInputText()); + writer.close(); + + final ITmfTrace trace = new CustomTxtTrace(null, definition, tmpFile.getAbsolutePath(), CACHE_SIZE); + previewTable.dispose(); + previewTable = new CustomEventsTable(definition, tableContainer, CACHE_SIZE); + previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + previewTable.setTrace(trace, true); + } catch (final TmfTraceException e) { + Activator.getDefault().logError("Error creating CustomTxtTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ + } catch (final IOException e) { + Activator.getDefault().logError("Error creating CustomTxtTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ + } + + tableContainer.layout(); + container.layout(); + } + + public List extractOutputs() { + int numColumns = 0; + for (int i = 0; i < outputs.size(); i++) + if (outputs.get(i).enabledButton.getSelection()) + numColumns++; + final List outputColumns = new ArrayList(numColumns); + numColumns = 0; + for (int i = 0; i < outputs.size(); i++) { + final Output output = outputs.get(i); + if (output.enabledButton.getSelection()) { + final OutputColumn column = new OutputColumn(); + column.name = output.nameLabel.getText(); + outputColumns.add(column); + } + } + return outputColumns; + } + + private class Output { + String name; + Button enabledButton; + Text nameLabel; + Button upButton; + Button downButton; + + public Output(final Composite parent, final String name) { + this.name = name; + + enabledButton = new Button(parent, SWT.CHECK); + enabledButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_visible); + enabledButton.setSelection(true); + enabledButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + updatePreviewTable(); + } + }); + // if (messageOutput != null) { + // enabledButton.moveAbove(messageOutput.enabledButton); + // } + + nameLabel = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE); + nameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + nameLabel.setText(name); + nameLabel.moveBelow(enabledButton); + + upButton = new Button(parent, SWT.PUSH); + upButton.setImage(upImage); + upButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_moveBefore); + upButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + moveBefore(Output.this); + } + }); + upButton.moveBelow(nameLabel); + + downButton = new Button(parent, SWT.PUSH); + downButton.setImage(downImage); + downButton.setToolTipText(Messages.CustomTxtParserOutputWizardPage_moveAfter); + downButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + moveAfter(Output.this); + } + }); + downButton.moveBelow(upButton); + } + + private void dispose() { + enabledButton.dispose(); + nameLabel.dispose(); + upButton.dispose(); + downButton.dispose(); + } + } + + public CustomTxtTraceDefinition getDefinition() { + return definition; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserWizard.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserWizard.java index be8babca93..78d1fea2bb 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserWizard.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomTxtParserWizard.java @@ -1,53 +1,53 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; - -public class CustomTxtParserWizard extends Wizard implements INewWizard { - - CustomTxtParserInputWizardPage inputPage; - CustomTxtParserOutputWizardPage outputPage; - private ISelection selection; - CustomTxtTraceDefinition definition; - - public CustomTxtParserWizard() { - super(); - } - - public CustomTxtParserWizard(CustomTxtTraceDefinition definition) { - super(); - this.definition = definition; - } - - @Override - public boolean performFinish() { - CustomTxtTraceDefinition def = outputPage.getDefinition(); - if (definition != null && !definition.definitionName.equals(def.definitionName)) { - CustomTxtTraceDefinition.delete(definition.definitionName); - } - def.save(); - return true; - } - - /** - * Adding the page to the wizard. - */ - - @Override - public void addPages() { - inputPage = new CustomTxtParserInputWizardPage(selection, definition); - addPage(inputPage); - outputPage = new CustomTxtParserOutputWizardPage(this); - addPage(outputPage); - } - - @Override - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; + +public class CustomTxtParserWizard extends Wizard implements INewWizard { + + CustomTxtParserInputWizardPage inputPage; + CustomTxtParserOutputWizardPage outputPage; + private ISelection selection; + CustomTxtTraceDefinition definition; + + public CustomTxtParserWizard() { + super(); + } + + public CustomTxtParserWizard(CustomTxtTraceDefinition definition) { + super(); + this.definition = definition; + } + + @Override + public boolean performFinish() { + CustomTxtTraceDefinition def = outputPage.getDefinition(); + if (definition != null && !definition.definitionName.equals(def.definitionName)) { + CustomTxtTraceDefinition.delete(definition.definitionName); + } + def.save(); + return true; + } + + /** + * Adding the page to the wizard. + */ + + @Override + public void addPages() { + inputPage = new CustomTxtParserInputWizardPage(selection, definition); + addPage(inputPage); + outputPage = new CustomTxtParserOutputWizardPage(this); + addPage(outputPage); + } + + @Override + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserInputWizardPage.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserInputWizardPage.java index 11c6eb1c19..58aa11eebc 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserInputWizardPage.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserInputWizardPage.java @@ -1,1691 +1,1691 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.AbstractTreeViewer; -import org.eclipse.jface.viewers.ColumnLabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputAttribute; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputElement; -import org.eclipse.swt.SWT; -import org.eclipse.swt.browser.Browser; -import org.eclipse.swt.browser.TitleEvent; -import org.eclipse.swt.browser.TitleListener; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.FontData; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public class CustomXmlParserInputWizardPage extends WizardPage { - - private static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; //$NON-NLS-1$ - private static final String SIMPLE_DATE_FORMAT_URL = "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#skip-navbar_top"; //$NON-NLS-1$ - private static final Image elementImage = Activator.getDefault().getImageFromPath("/icons/elcl16/element_icon.gif"); //$NON-NLS-1$ - private static final Image addImage = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ - private static final Image addNextImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addnext_button.gif"); //$NON-NLS-1$ - private static final Image addChildImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addchild_button.gif"); //$NON-NLS-1$ - private static final Image addManyImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addmany_button.gif"); //$NON-NLS-1$ - private static final Image deleteImage = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ - private static final Image moveUpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ - private static final Image moveDownImage = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ - private static final Image helpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/help_button.gif"); //$NON-NLS-1$ - private static final Color COLOR_LIGHT_RED = new Color(Display.getDefault(), 255, 192, 192); - private static final Color COLOR_TEXT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); - private static final Color COLOR_WIDGET_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); - - private final ISelection selection; - private CustomXmlTraceDefinition definition; - private String editDefinitionName; - private String defaultDescription; - private ElementNode selectedElement; - private Composite container; - private Text logtypeText; - private Text timeStampOutputFormatText; - private Text timeStampPreviewText; - private Button removeButton; - private Button addChildButton; - private Button addNextButton; - private Button moveUpButton; - private Button moveDownButton; - private Button feelingLuckyButton; - private ScrolledComposite treeScrolledComposite; - private ScrolledComposite elementScrolledComposite; - private TreeViewer treeViewer; - private Composite treeContainer; - private Composite elementContainer; - private Text errorText; - private StyledText inputText; - private Font fixedFont; - private UpdateListener updateListener; - private Browser helpBrowser; - private Element documentElement; - - // variables used recursively through element traversal - private String timeStampValue; - private String timeStampFormat; - private boolean timeStampFound; - private int logEntriesCount; - private boolean logEntryFound; - - protected CustomXmlParserInputWizardPage(ISelection selection, CustomXmlTraceDefinition definition) { - super("CustomXmlParserWizardPage"); //$NON-NLS-1$ - if (definition == null) { - setTitle(Messages.CustomXmlParserInputWizardPage_titleNew); - defaultDescription = Messages.CustomXmlParserInputWizardPage_descriptionNew; - } else { - setTitle(Messages.CustomXmlParserInputWizardPage_titleEdit); - defaultDescription = Messages.CustomXmlParserInputWizardPage_descriptionEdit; - } - setDescription(defaultDescription); - this.selection = selection; - this.definition = definition; - if (definition != null) { - this.editDefinitionName = definition.definitionName; - } - } - - @Override - public void createControl(Composite parent) { - container = new Composite(parent, SWT.NULL); - container.setLayout(new GridLayout()); - - updateListener = new UpdateListener(); - - Composite headerComposite = new Composite(container, SWT.FILL); - GridLayout headerLayout = new GridLayout(5, false); - headerLayout.marginHeight = 0; - headerLayout.marginWidth = 0; - headerComposite.setLayout(headerLayout); - headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Label logtypeLabel = new Label(headerComposite, SWT.NULL); - logtypeLabel.setText(Messages.CustomXmlParserInputWizardPage_logType); - - logtypeText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); - logtypeText.setLayoutData(new GridData(120, SWT.DEFAULT)); - - Label timeStampFormatLabel = new Label(headerComposite, SWT.NULL); - timeStampFormatLabel.setText(Messages.CustomXmlParserInputWizardPage_timestampFormat); - - timeStampOutputFormatText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); - timeStampOutputFormatText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - timeStampOutputFormatText.setText(DEFAULT_TIMESTAMP_FORMAT); - - Button dateFormatHelpButton = new Button(headerComposite, SWT.PUSH); - dateFormatHelpButton.setImage(helpImage); - dateFormatHelpButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_dateFormatHelp); - dateFormatHelpButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - openHelpShell(SIMPLE_DATE_FORMAT_URL); - } - }); - - Label timeStampPreviewLabel = new Label(headerComposite, SWT.NULL); - timeStampPreviewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 3, 1)); - timeStampPreviewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); - - timeStampPreviewText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - timeStampPreviewText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); - timeStampPreviewText.setText("*no time stamp element or attribute*"); //$NON-NLS-1$ - - createButtonBar(); - - SashForm vSash = new SashForm(container, SWT.VERTICAL); - vSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - vSash.setBackground(vSash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); - - SashForm hSash = new SashForm(vSash, SWT.HORIZONTAL); - hSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - treeScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL | SWT.H_SCROLL); - treeScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - treeContainer = new Composite(treeScrolledComposite, SWT.NONE); - treeContainer.setLayout(new FillLayout()); - treeScrolledComposite.setContent(treeContainer); - treeScrolledComposite.setExpandHorizontal(true); - treeScrolledComposite.setExpandVertical(true); - - treeViewer = new TreeViewer(treeContainer, SWT.SINGLE | SWT.BORDER); - treeViewer.setContentProvider(new InputElementTreeNodeContentProvider()); - treeViewer.setLabelProvider(new InputElementTreeLabelProvider()); - treeViewer.addSelectionChangedListener(new InputElementTreeSelectionChangedListener()); - treeContainer.layout(); - - treeScrolledComposite - .setMinSize(treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y); - - elementScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL); - elementScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - elementContainer = new Composite(elementScrolledComposite, SWT.NONE); - GridLayout gl = new GridLayout(); - gl.marginHeight = 1; - gl.marginWidth = 0; - elementContainer.setLayout(gl); - elementScrolledComposite.setContent(elementContainer); - elementScrolledComposite.setExpandHorizontal(true); - elementScrolledComposite.setExpandVertical(true); - - if (definition == null) { - definition = new CustomXmlTraceDefinition(); - } - loadDefinition(definition); - treeViewer.expandAll(); - elementContainer.layout(); - - logtypeText.addModifyListener(updateListener); - timeStampOutputFormatText.addModifyListener(updateListener); - - elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, - elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); - - hSash.setWeights(new int[] { 1, 2 }); - - if (definition.rootInputElement == null) { - removeButton.setEnabled(false); - addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentElement); - addNextButton.setEnabled(false); - moveUpButton.setEnabled(false); - moveDownButton.setEnabled(false); - } else { // root is selected - addNextButton.setEnabled(false); - } - - Composite sashBottom = new Composite(vSash, SWT.NONE); - GridLayout sashBottomLayout = new GridLayout(2, false); - sashBottomLayout.marginHeight = 0; - sashBottomLayout.marginWidth = 0; - sashBottom.setLayout(sashBottomLayout); - - Label previewLabel = new Label(sashBottom, SWT.NULL); - previewLabel.setText(Messages.CustomXmlParserInputWizardPage_previewInput); - - errorText = new Text(sashBottom, SWT.SINGLE | SWT.READ_ONLY); - errorText.setBackground(COLOR_WIDGET_BACKGROUND); - errorText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - errorText.setVisible(false); - - inputText = new StyledText(sashBottom, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); - if (fixedFont == null) { - if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ - fixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ - } else { - fixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ - } - } - inputText.setFont(fixedFont); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); - gd.heightHint = inputText.computeSize(SWT.DEFAULT, inputText.getLineHeight() * 4).y; - gd.widthHint = 800; - inputText.setLayoutData(gd); - inputText.setText(getSelectionText()); - inputText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - parseXmlInput(inputText.getText()); - } - }); - inputText.addModifyListener(updateListener); - - vSash.setWeights(new int[] { hSash.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sashBottom.computeSize(SWT.DEFAULT, SWT.DEFAULT).y }); - - setControl(container); - } - - private void createButtonBar() { - Composite buttonBar = new Composite(container, SWT.NONE); - GridLayout buttonBarLayout = new GridLayout(6, false); - buttonBarLayout.marginHeight = 0; - buttonBarLayout.marginWidth = 0; - buttonBar.setLayout(buttonBarLayout); - - removeButton = new Button(buttonBar, SWT.PUSH); - removeButton.setImage(deleteImage); - removeButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_removeElement); - removeButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty() || selectedElement == null) { - return; - } - removeElement(); - InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputElement == definition.rootInputElement) { - definition.rootInputElement = null; - } else { - inputElement.parentElement.childElements.remove(inputElement); - } - treeViewer.refresh(); - validate(); - updatePreviews(); - removeButton.setEnabled(false); - if (definition.rootInputElement == null) { - addChildButton.setEnabled(true); - addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentEleemnt); - } else { - addChildButton.setEnabled(false); - } - addNextButton.setEnabled(false); - moveUpButton.setEnabled(false); - moveDownButton.setEnabled(false); - } - }); - - addChildButton = new Button(buttonBar, SWT.PUSH); - addChildButton.setImage(addChildImage); - addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addChildElement); - addChildButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputElement inputElement = new InputElement("", false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ //$NON-NLS-2$ - if (definition.rootInputElement == null) { - definition.rootInputElement = inputElement; - inputElement.elementName = getChildNameSuggestion(null); - } else if (treeViewer.getSelection().isEmpty()) { - return; - } else { - InputElement parentInputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - parentInputElement.addChild(inputElement); - inputElement.elementName = getChildNameSuggestion(parentInputElement); - } - treeViewer.refresh(); - treeViewer.setSelection(new StructuredSelection(inputElement), true); - } - }); - - addNextButton = new Button(buttonBar, SWT.PUSH); - addNextButton.setImage(addNextImage); - addNextButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addNextElement); - addNextButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputElement inputElement = new InputElement("", false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ //$NON-NLS-2$ - if (definition.rootInputElement == null) { - definition.rootInputElement = inputElement; - inputElement.elementName = getChildNameSuggestion(null); - } else if (treeViewer.getSelection().isEmpty()) { - return; - } else { - InputElement previousInputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (previousInputElement == definition.rootInputElement) { - return; - } - previousInputElement.addNext(inputElement); - inputElement.elementName = getChildNameSuggestion(inputElement.parentElement); - } - treeViewer.refresh(); - treeViewer.setSelection(new StructuredSelection(inputElement), true); - } - }); - - feelingLuckyButton = new Button(buttonBar, SWT.PUSH); - feelingLuckyButton.setImage(addManyImage); - feelingLuckyButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_feelingLucky); - feelingLuckyButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - InputElement inputElement = null; - if (definition.rootInputElement == null) { - if (getChildNameSuggestion(null).length() != 0) { - inputElement = new InputElement(getChildNameSuggestion(null), false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ - definition.rootInputElement = inputElement; - feelingLucky(inputElement); - } else { - return; - } - } else if (treeViewer.getSelection().isEmpty()) { - return; - } else { - inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - feelingLucky(inputElement); - } - treeViewer.refresh(); - treeViewer.setSelection(new StructuredSelection(inputElement), true); - treeViewer.expandToLevel(inputElement, AbstractTreeViewer.ALL_LEVELS); - } - }); - - moveUpButton = new Button(buttonBar, SWT.PUSH); - moveUpButton.setImage(moveUpImage); - moveUpButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_moveUp); - moveUpButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty()) { - return; - } - InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputElement == definition.rootInputElement) { - return; - } - inputElement.moveUp(); - treeViewer.refresh(); - validate(); - updatePreviews(); - } - }); - - moveDownButton = new Button(buttonBar, SWT.PUSH); - moveDownButton.setImage(moveDownImage); - moveDownButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_moveDown); - moveDownButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (treeViewer.getSelection().isEmpty()) { - return; - } - InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); - if (inputElement == definition.rootInputElement) { - return; - } - inputElement.moveDown(); - treeViewer.refresh(); - validate(); - updatePreviews(); - } - }); - } - - private void feelingLucky(InputElement inputElement) { - while (true) { - String attributeName = getAttributeNameSuggestion(inputElement); - if (attributeName.length() == 0) { - break; - } - InputAttribute attribute = new InputAttribute(attributeName, attributeName, 0, ""); //$NON-NLS-1$ - inputElement.addAttribute(attribute); - } - while (true) { - String childName = getChildNameSuggestion(inputElement); - if (childName.length() == 0) { - break; - } - InputElement childElement = new InputElement(childName, false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ - inputElement.addChild(childElement); - feelingLucky(childElement); - } - } - - private static class InputElementTreeNodeContentProvider implements ITreeContentProvider { - - @Override - public Object[] getElements(Object inputElement) { - CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) inputElement; - if (def.rootInputElement != null) { - return new Object[] { def.rootInputElement }; - } - return new Object[0]; - } - - @Override - public Object[] getChildren(Object parentElement) { - InputElement inputElement = (InputElement) parentElement; - if (inputElement.childElements == null) { - return new InputElement[0]; - } - return inputElement.childElements.toArray(); - } - - @Override - public boolean hasChildren(Object element) { - InputElement inputElement = (InputElement) element; - return (inputElement.childElements != null && inputElement.childElements.size() > 0); - } - - @Override - public void dispose() { - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - @Override - public Object getParent(Object element) { - InputElement inputElement = (InputElement) element; - return inputElement.parentElement; - } - } - - private static class InputElementTreeLabelProvider extends ColumnLabelProvider { - - @Override - public Image getImage(Object element) { - return elementImage; - } - - @Override - public String getText(Object element) { - InputElement inputElement = (InputElement) element; - return (inputElement.elementName.trim().length() == 0) ? "?" : inputElement.elementName; //$NON-NLS-1$ - } - } - - private class InputElementTreeSelectionChangedListener implements ISelectionChangedListener { - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (selectedElement != null) { - selectedElement.dispose(); - } - if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - InputElement inputElement = (InputElement) selection.getFirstElement(); - selectedElement = new ElementNode(elementContainer, inputElement); - elementContainer.layout(); - elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, - elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); - container.layout(); - validate(); - updatePreviews(); - removeButton.setEnabled(true); - addChildButton.setEnabled(true); - addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addChildElement); - if (definition.rootInputElement == inputElement) { - addNextButton.setEnabled(false); - } else { - addNextButton.setEnabled(true); - } - moveUpButton.setEnabled(true); - moveDownButton.setEnabled(true); - } else { - removeButton.setEnabled(false); - if (definition.rootInputElement == null) { - addChildButton.setEnabled(true); - addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentElement); - } else { - addChildButton.setEnabled(false); - } - addNextButton.setEnabled(false); - moveUpButton.setEnabled(false); - moveDownButton.setEnabled(false); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.dialogs.DialogPage#dispose() - */ - @Override - public void dispose() { - if (fixedFont != null) { - fixedFont.dispose(); - fixedFont = null; - } - super.dispose(); - } - - private void loadDefinition(CustomXmlTraceDefinition def) { - logtypeText.setText(def.definitionName); - timeStampOutputFormatText.setText(def.timeStampOutputFormat); - treeViewer.setInput(def); - - if (def.rootInputElement != null) { - treeViewer.setSelection(new StructuredSelection(def.rootInputElement)); - } - } - - private String getName(InputElement inputElement) { - String name = (inputElement.elementName.trim().length() == 0) ? "?" : inputElement.elementName.trim(); //$NON-NLS-1$ - if (inputElement.parentElement == null) { - return name; - } - return getName(inputElement.parentElement) + " : " + name; //$NON-NLS-1$ - } - - private String getName(InputAttribute inputAttribute, InputElement inputElement) { - String name = (inputAttribute.attributeName.trim().length() == 0) ? "?" : inputAttribute.attributeName.trim(); //$NON-NLS-1$ - return getName(inputElement) + " : " + name; //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) - */ - @Override - public void setVisible(boolean visible) { - if (visible) { - validate(); - updatePreviews(); - } - super.setVisible(visible); - } - - public List getInputNames() { - return getInputNames(definition.rootInputElement); - } - - public List getInputNames(InputElement inputElement) { - List inputs = new ArrayList(); - if (inputElement.inputName != null && !inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { - String inputName = inputElement.inputName; - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - if (inputElement.attributes != null) { - for (InputAttribute attribute : inputElement.attributes) { - String inputName = attribute.inputName; - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - } - if (inputElement.childElements != null) { - for (InputElement childInputElement : inputElement.childElements) { - for (String inputName : getInputNames(childInputElement)) { - if (!inputs.contains(inputName)) { - inputs.add(inputName); - } - } - } - } - return inputs; - } - - private void removeElement() { - selectedElement.dispose(); - selectedElement = null; - elementContainer.layout(); - elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, - elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); - container.layout(); - } - - private String getSelectionText() { - InputStream inputStream = null; - if (this.selection instanceof IStructuredSelection) { - Object selection = ((IStructuredSelection) this.selection).getFirstElement(); - if (selection instanceof IFile) { - IFile file = (IFile) selection; - try { - inputStream = file.getContents(); - } catch (CoreException e) { - return ""; //$NON-NLS-1$ - } - } - } - if (inputStream != null) { - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(inputStream)); - StringBuilder sb = new StringBuilder(); - String line = null; - while ((line = reader.readLine()) != null) { - sb.append(line + "\n"); //$NON-NLS-1$ - } - parseXmlInput(sb.toString()); - reader.close(); - return sb.toString(); - } catch (IOException e) { - return ""; //$NON-NLS-1$ - } - } - return ""; //$NON-NLS-1$ - } - - private void parseXmlInput(final String string) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - // The following allows xml parsing without access to the dtd - EntityResolver resolver = new EntityResolver() { - @Override - public InputSource resolveEntity(String publicId, String systemId) { - String empty = ""; //$NON-NLS-1$ - ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); - return new InputSource(bais); - } - }; - db.setEntityResolver(resolver); - - // The following catches xml parsing exceptions - db.setErrorHandler(new ErrorHandler() { - @Override - public void error(SAXParseException saxparseexception) throws SAXException { - } - - @Override - public void warning(SAXParseException saxparseexception) throws SAXException { - } - - @Override - public void fatalError(SAXParseException saxparseexception) throws SAXException { - if (string.trim().length() != 0) { - errorText.setText(saxparseexception.getMessage()); - errorText.setBackground(COLOR_LIGHT_RED); - errorText.setVisible(true); - } - throw saxparseexception; - } - }); - - errorText.setVisible(false); - Document doc = null; - doc = db.parse(new ByteArrayInputStream(string.getBytes())); - documentElement = doc.getDocumentElement(); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error pasing XML input string: " + string, e); //$NON-NLS-1$ - documentElement = null; - } catch (SAXException e) { - documentElement = null; - } catch (IOException e) { - Activator.getDefault().logError("Error pasing XML input string: " + string, e); //$NON-NLS-1$ - documentElement = null; - } - } - - private void updatePreviews() { - updatePreviews(false); - } - - private void initValues() { - timeStampValue = null; - timeStampFormat = null; - logEntriesCount = 0; - logEntryFound = false; - } - - private void updatePreviews(boolean updateAll) { - if (inputText == null) { - // early update during construction - return; - } - inputText.setStyleRanges(new StyleRange[] {}); - if (selectedElement == null) { - return; - } - - initValues(); - - selectedElement.updatePreview(); - - if (timeStampValue != null && timeStampFormat != null) { - try { - SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampFormat); - Date date = dateFormat.parse(timeStampValue); - dateFormat = new SimpleDateFormat(timeStampOutputFormatText.getText().trim()); - timeStampPreviewText.setText(dateFormat.format(date)); - } catch (ParseException e) { - timeStampPreviewText.setText("*parse exception* [" + timeStampValue + "] <> [" + timeStampFormat + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } catch (IllegalArgumentException e) { - timeStampPreviewText.setText("*parse exception* [Illegal Argument]"); //$NON-NLS-1$ - } - } else { - timeStampPreviewText.setText("*no matching time stamp*"); //$NON-NLS-1$ - } - } - - private void openHelpShell(String url) { - if (helpBrowser != null && !helpBrowser.isDisposed()) { - helpBrowser.getShell().setActive(); - if (!helpBrowser.getUrl().equals(url)) { - helpBrowser.setUrl(url); - } - return; - } - final Shell helpShell = new Shell(getShell(), SWT.SHELL_TRIM); - helpShell.setLayout(new FillLayout()); - helpBrowser = new Browser(helpShell, SWT.NONE); - helpBrowser.addTitleListener(new TitleListener() { - @Override - public void changed(TitleEvent event) { - helpShell.setText(event.title); - } - }); - helpBrowser.setBounds(0, 0, 600, 400); - helpShell.pack(); - helpShell.open(); - helpBrowser.setUrl(url); - } - - private class UpdateListener implements ModifyListener, SelectionListener { - - @Override - public void modifyText(ModifyEvent e) { - validate(); - updatePreviews(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - validate(); - updatePreviews(); - } - - @Override - public void widgetSelected(SelectionEvent e) { - validate(); - updatePreviews(); - } - - } - - private class ElementNode { - final InputElement inputElement; - final Group group; - List attributes = new ArrayList(); - List childElements = new ArrayList(); - Text elementNameText; - Composite tagComposite; - Combo tagCombo; - Label tagLabel; - Text tagText; - Combo actionCombo; - Label previewLabel; - Text previewText; - Button logEntryButton; - Label fillerLabel; - Composite addAttributeComposite; - Button addAttributeButton; - Label addAttributeLabel; - - public ElementNode(Composite parent, InputElement inputElement) { - this.inputElement = inputElement; - - group = new Group(parent, SWT.NONE); - GridLayout gl = new GridLayout(2, false); - gl.marginHeight = 0; - group.setLayout(gl); - group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - group.setText(getName(inputElement)); - - Label label = new Label(group, SWT.NULL); - label.setText(Messages.CustomXmlParserInputWizardPage_elementName); - label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - elementNameText = new Text(group, SWT.BORDER | SWT.SINGLE); - GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - elementNameText.setLayoutData(gd); - elementNameText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - ElementNode.this.inputElement.elementName = elementNameText.getText().trim(); - group.setText(getName(ElementNode.this.inputElement)); - } - }); - elementNameText.setText(inputElement.elementName); - elementNameText.addModifyListener(updateListener); - - if (inputElement.parentElement != null) { - previewLabel = new Label(group, SWT.NULL); - previewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - previewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); - - previewText = new Text(group, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - previewText.setLayoutData(gd); - previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); - previewText.setBackground(COLOR_WIDGET_BACKGROUND); - - logEntryButton = new Button(group, SWT.CHECK); - logEntryButton.setText(Messages.CustomXmlParserInputWizardPage_logEntry); - logEntryButton.setSelection(inputElement.logEntry); - logEntryButton.addSelectionListener(new SelectionListener() { - @Override - public void widgetDefaultSelected(SelectionEvent e) { - } - - @Override - public void widgetSelected(SelectionEvent e) { - InputElement parent = ElementNode.this.inputElement.parentElement; - while (parent != null) { - parent.logEntry = false; - parent = parent.parentElement; - } - } - }); - logEntryButton.addSelectionListener(updateListener); - - tagComposite = new Composite(group, SWT.FILL); - GridLayout tagLayout = new GridLayout(4, false); - tagLayout.marginWidth = 0; - tagLayout.marginHeight = 0; - tagComposite.setLayout(tagLayout); - tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - tagCombo.setItems(new String[] { CustomXmlTraceDefinition.TAG_IGNORE, CustomTraceDefinition.TAG_TIMESTAMP, - CustomTraceDefinition.TAG_MESSAGE, CustomTraceDefinition.TAG_OTHER }); - tagCombo.setVisibleItemCount(tagCombo.getItemCount()); - tagCombo.addSelectionListener(new SelectionListener() { - @Override - public void widgetDefaultSelected(SelectionEvent e) { - } - - @Override - public void widgetSelected(SelectionEvent e) { - tagText.removeModifyListener(updateListener); - switch (tagCombo.getSelectionIndex()) { - case 0: // Ignore - tagLabel.setVisible(false); - tagText.setVisible(false); - actionCombo.setVisible(false); - break; - case 1: // Time Stamp - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); - tagLabel.setVisible(true); - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - actionCombo.setVisible(true); - break; - case 2: // Message - tagLabel.setVisible(false); - tagText.setVisible(false); - actionCombo.setVisible(true); - break; - case 3: // Other - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); - tagLabel.setVisible(true); - if (tagText.getText().trim().length() == 0) { - tagText.setText(elementNameText.getText().trim()); - } - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - actionCombo.setVisible(true); - break; - default: - break; - } - tagComposite.layout(); - validate(); - updatePreviews(); - } - }); - - tagLabel = new Label(tagComposite, SWT.NULL); - tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); - gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - tagText.setLayoutData(gd); - - actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - actionCombo.setItems(new String[] { Messages.CustomXmlParserInputWizardPage_set, Messages.CustomXmlParserInputWizardPage_append, - Messages.CustomXmlParserInputWizardPage_appendWith }); - actionCombo.select(inputElement.inputAction); - actionCombo.addSelectionListener(updateListener); - - if (inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { - tagCombo.select(0); - tagLabel.setVisible(false); - tagText.setVisible(false); - actionCombo.setVisible(false); - } else if (inputElement.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - tagCombo.select(1); - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); - tagText.setText(inputElement.inputFormat); - tagText.addModifyListener(updateListener); - } else if (inputElement.inputName.equals(CustomTraceDefinition.TAG_MESSAGE)) { - tagCombo.select(2); - tagLabel.setVisible(false); - tagText.setVisible(false); - } else { - tagCombo.select(3); - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); - tagText.setText(inputElement.inputName); - tagText.addModifyListener(updateListener); - } - } - - if (inputElement.attributes != null) { - for (InputAttribute inputAttribute : inputElement.attributes) { - Attribute attribute = new Attribute(group, this, inputAttribute, attributes.size() + 1); - attributes.add(attribute); - } - } - - createAddButton(); - } - - private void updatePreview() { - Element element = getPreviewElement(inputElement); - if (inputElement.parentElement != null) { // no preview text for - // document element - previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); - if (element != null) { - previewText.setText(CustomXmlTrace.parseElement(element, new StringBuffer()).toString()); - if (logEntryButton.getSelection()) { - if (!logEntryFound) { - logEntryFound = true; - logEntriesCount++; - } else { - logEntryButton.setSelection(false); // remove nested - // log entry - } - } - if (tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP) && logEntriesCount <= 1) { - String value = previewText.getText().trim(); - if (value.length() != 0) { - if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_SET) { - timeStampValue = value; - timeStampFormat = tagText.getText().trim(); - } else if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND) { - if (timeStampValue != null) { - timeStampValue += value; - timeStampFormat += tagText.getText().trim(); - } else { - timeStampValue = value; - timeStampFormat = tagText.getText().trim(); - } - } else if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { - if (timeStampValue != null) { - timeStampValue += " | " + value; //$NON-NLS-1$ - timeStampFormat += " | " + tagText.getText().trim(); //$NON-NLS-1$ - } else { - timeStampValue = value; - timeStampFormat = tagText.getText().trim(); - } - } - } - } - } - } - for (Attribute attribute : attributes) { - if (element != null) { - String value = element.getAttribute(attribute.attributeNameText.getText().trim()); - if (value.length() != 0) { - attribute.previewText.setText(value); - if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP) && logEntriesCount <= 1) { - if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_SET) { - timeStampValue = value; - timeStampFormat = attribute.tagText.getText().trim(); - } else if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND) { - if (timeStampValue != null) { - timeStampValue += value; - timeStampFormat += attribute.tagText.getText().trim(); - } else { - timeStampValue = value; - timeStampFormat = attribute.tagText.getText().trim(); - } - } else if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { - if (timeStampValue != null) { - timeStampValue += " | " + value; //$NON-NLS-1$ - timeStampFormat += " | " + attribute.tagText.getText().trim(); //$NON-NLS-1$ - } else { - timeStampValue = value; - timeStampFormat = attribute.tagText.getText().trim(); - } - } - } - } else { - attribute.previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingAttribute); - } - } else { - attribute.previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); - } - } - for (ElementNode child : childElements) { - child.updatePreview(); - } - if (logEntryButton != null && logEntryButton.getSelection()) { - logEntryFound = false; - } - } - - private void createAddButton() { - fillerLabel = new Label(group, SWT.NONE); - - addAttributeComposite = new Composite(group, SWT.NONE); - addAttributeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - GridLayout addAttributeLayout = new GridLayout(2, false); - addAttributeLayout.marginHeight = 0; - addAttributeLayout.marginWidth = 0; - addAttributeComposite.setLayout(addAttributeLayout); - - addAttributeButton = new Button(addAttributeComposite, SWT.PUSH); - addAttributeButton.setImage(addImage); - addAttributeButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addAttribute); - addAttributeButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - removeAddButton(); - String attributeName = getAttributeNameSuggestion(inputElement); - InputAttribute inputAttribute = new InputAttribute(attributeName, attributeName, 0, ""); //$NON-NLS-1$ - attributes.add(new Attribute(group, ElementNode.this, inputAttribute, attributes.size() + 1)); - createAddButton(); - elementContainer.layout(); - elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, - elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); - group.getParent().layout(); - validate(); - updatePreviews(); - } - }); - - addAttributeLabel = new Label(addAttributeComposite, SWT.NULL); - addAttributeLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - addAttributeLabel.setText(Messages.CustomXmlParserInputWizardPage_newAttibute); - } - - private void removeAddButton() { - fillerLabel.dispose(); - addAttributeComposite.dispose(); - } - - private void removeAttribute(int attributeNumber) { - if (--attributeNumber < attributes.size()) { - attributes.remove(attributeNumber).dispose(); - for (int i = attributeNumber; i < attributes.size(); i++) { - attributes.get(i).setAttributeNumber(i + 1); - } - elementContainer.layout(); - elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, - elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); - group.getParent().layout(); - } - } - - private void dispose() { - group.dispose(); - } - - private void extractInputs() { - inputElement.elementName = elementNameText.getText().trim(); - if (inputElement.parentElement != null) { - inputElement.logEntry = logEntryButton.getSelection(); - if (tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { - inputElement.inputName = tagText.getText().trim(); - } else { - inputElement.inputName = tagCombo.getText(); - if (tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - inputElement.inputFormat = tagText.getText().trim(); - } - } - inputElement.inputAction = actionCombo.getSelectionIndex(); - } - inputElement.attributes = new ArrayList(attributes.size()); - for (int i = 0; i < attributes.size(); i++) { - Attribute attribute = attributes.get(i); - InputAttribute inputAttribute = new InputAttribute(); - inputAttribute.attributeName = attribute.attributeNameText.getText().trim(); - if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { - inputAttribute.inputName = attribute.tagText.getText().trim(); - } else { - inputAttribute.inputName = attribute.tagCombo.getText(); - if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - inputAttribute.inputFormat = attribute.tagText.getText().trim(); - } - } - inputAttribute.inputAction = attribute.actionCombo.getSelectionIndex(); - inputElement.addAttribute(inputAttribute); - } - } - } - - private class Attribute { - ElementNode element; - int attributeNumber; - - // children of parent (must be disposed) - Composite labelComposite; - Composite attributeComposite; - Label filler; - Composite tagComposite; - - // children of labelComposite - Label attributeLabel; - - // children of attributeComposite - Text attributeNameText; - Text previewText; - - // children of tagComposite - Combo tagCombo; - Label tagLabel; - Text tagText; - Combo actionCombo; - - public Attribute(Composite parent, ElementNode element, InputAttribute inputAttribute, int attributeNumber) { - this.element = element; - this.attributeNumber = attributeNumber; - - labelComposite = new Composite(parent, SWT.FILL); - GridLayout labelLayout = new GridLayout(2, false); - labelLayout.marginWidth = 0; - labelLayout.marginHeight = 0; - labelComposite.setLayout(labelLayout); - labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - Button deleteButton = new Button(labelComposite, SWT.PUSH); - deleteButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - deleteButton.setImage(deleteImage); - deleteButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_removeAttribute); - deleteButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Attribute.this.element.removeAttribute(Attribute.this.attributeNumber); - validate(); - updatePreviews(); - } - }); - - attributeLabel = new Label(labelComposite, SWT.NULL); - attributeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - attributeLabel.setText(Messages.CustomXmlParserInputWizardPage_attibute); - - attributeComposite = new Composite(parent, SWT.FILL); - GridLayout attributeLayout = new GridLayout(4, false); - attributeLayout.marginWidth = 0; - attributeLayout.marginHeight = 0; - attributeComposite.setLayout(attributeLayout); - attributeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Label nameLabel = new Label(attributeComposite, SWT.NONE); - nameLabel.setText(Messages.CustomXmlParserInputWizardPage_name); - - attributeNameText = new Text(attributeComposite, SWT.BORDER | SWT.SINGLE); - attributeNameText.setLayoutData(new GridData(120, SWT.DEFAULT)); - attributeNameText.setText(inputAttribute.attributeName); - attributeNameText.addModifyListener(updateListener); - - Label previewLabel = new Label(attributeComposite, SWT.NONE); - previewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); - - previewText = new Text(attributeComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); - GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - previewText.setLayoutData(gd); - previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatch); - previewText.setBackground(COLOR_WIDGET_BACKGROUND); - - filler = new Label(parent, SWT.NULL); - - tagComposite = new Composite(parent, SWT.FILL); - GridLayout tagLayout = new GridLayout(4, false); - tagLayout.marginWidth = 0; - tagLayout.marginHeight = 0; - tagComposite.setLayout(tagLayout); - tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - tagCombo.setItems(new String[] { CustomTraceDefinition.TAG_TIMESTAMP, CustomTraceDefinition.TAG_MESSAGE, - CustomTraceDefinition.TAG_OTHER }); - tagCombo.select(2); // Other - tagCombo.addSelectionListener(new SelectionListener() { - @Override - public void widgetDefaultSelected(SelectionEvent e) { - } - - @Override - public void widgetSelected(SelectionEvent e) { - tagText.removeModifyListener(updateListener); - switch (tagCombo.getSelectionIndex()) { - case 0: // Time Stamp - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); - tagLabel.setVisible(true); - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - break; - case 1: // Message - tagLabel.setVisible(false); - tagText.setVisible(false); - break; - case 2: // Other - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); - tagLabel.setVisible(true); - if (tagText.getText().trim().length() == 0) { - tagText.setText(attributeNameText.getText().trim()); - } - tagText.setVisible(true); - tagText.addModifyListener(updateListener); - break; - default: - break; - } - tagComposite.layout(); - validate(); - updatePreviews(); - } - }); - - tagLabel = new Label(tagComposite, SWT.NULL); - tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - - tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); - gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - gd.widthHint = 0; - tagText.setLayoutData(gd); - tagText.setText(attributeNameText.getText()); - - actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - actionCombo.setItems(new String[] { Messages.CustomXmlParserInputWizardPage_set, Messages.CustomXmlParserInputWizardPage_append, - Messages.CustomXmlParserInputWizardPage_appendWith }); - actionCombo.select(inputAttribute.inputAction); - actionCombo.addSelectionListener(updateListener); - - if (inputAttribute.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - tagCombo.select(0); - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); - tagText.setText(inputAttribute.inputFormat); - tagText.addModifyListener(updateListener); - } else if (inputAttribute.inputName.equals(CustomTraceDefinition.TAG_MESSAGE)) { - tagCombo.select(1); - tagLabel.setVisible(false); - tagText.setVisible(false); - } else { - tagCombo.select(2); - tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); - tagText.setText(inputAttribute.inputName); - tagText.addModifyListener(updateListener); - } - } - - private void dispose() { - labelComposite.dispose(); - attributeComposite.dispose(); - filler.dispose(); - tagComposite.dispose(); - } - - private void setAttributeNumber(int attributeNumber) { - this.attributeNumber = attributeNumber; - labelComposite.layout(); - } - } - - private Element getPreviewElement(InputElement inputElement) { - Element element = documentElement; - if (element != null) { - if (!documentElement.getNodeName().equals(definition.rootInputElement.elementName)) { - return null; - } - ArrayList elementNames = new ArrayList(); - while (inputElement != null) { - elementNames.add(inputElement.elementName); - inputElement = inputElement.parentElement; - } - for (int i = elementNames.size() - 1; --i >= 0;) { - NodeList childList = element.getChildNodes(); - element = null; - for (int j = 0; j < childList.getLength(); j++) { - Node child = childList.item(j); - if (child instanceof Element && child.getNodeName().equals(elementNames.get(i))) { - element = (Element) child; - break; - } - } - if (element == null) { - break; - } - } - if (element != null) { - return element; - } - } - return null; - } - - private String getChildNameSuggestion(InputElement inputElement) { - if (inputElement == null) { - if (documentElement != null) { - return documentElement.getNodeName(); - } - } else { - Element element = getPreviewElement(inputElement); - if (element != null) { - NodeList childNodes = element.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node node = childNodes.item(i); - if (node instanceof Element) { - boolean unused = true; - if (inputElement.childElements != null) { - for (InputElement child : inputElement.childElements) { - if (child.elementName.equals(node.getNodeName())) { - unused = false; - break; - } - } - } - if (unused) { - return node.getNodeName(); - } - } - } - } - } - return ""; //$NON-NLS-1$ - } - - private String getAttributeNameSuggestion(InputElement inputElement) { - Element element = getPreviewElement(inputElement); - if (element != null) { - NamedNodeMap attributeMap = element.getAttributes(); - for (int i = 0; i < attributeMap.getLength(); i++) { - Node node = attributeMap.item(i); - boolean unused = true; - if (inputElement.attributes != null) { - for (InputAttribute attribute : inputElement.attributes) { - if (attribute.attributeName.equals(node.getNodeName())) { - unused = false; - break; - } - } - } - if (unused) { - return node.getNodeName(); - } - } - } - return ""; //$NON-NLS-1$ - } - - private void validate() { - definition.definitionName = logtypeText.getText().trim(); - definition.timeStampOutputFormat = timeStampOutputFormatText.getText().trim(); - - if (selectedElement != null) { - selectedElement.extractInputs(); - treeViewer.refresh(); - } - - StringBuffer errors = new StringBuffer(); - - if (definition.definitionName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_emptyLogTypeError); - logtypeText.setBackground(COLOR_LIGHT_RED); - } else { - logtypeText.setBackground(COLOR_TEXT_BACKGROUND); - for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { - if (definition.definitionName.equals(def.definitionName)) { - if (editDefinitionName == null || !editDefinitionName.equals(definition.definitionName)) { - errors.append(Messages.CustomXmlParserInputWizardPage_duplicatelogTypeError); - logtypeText.setBackground(COLOR_LIGHT_RED); - break; - } - } - } - } - - if (definition.rootInputElement == null) { - errors.append(Messages.CustomXmlParserInputWizardPage_noDocumentError); - } - - if (definition.rootInputElement != null) { - logEntryFound = false; - timeStampFound = false; - - errors.append(validateElement(definition.rootInputElement)); - - if ((definition.rootInputElement.attributes != null && definition.rootInputElement.attributes.size() != 0) - || (definition.rootInputElement.childElements != null && definition.rootInputElement.childElements.size() != 0) - || errors.length() == 0) { - if (!logEntryFound) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingLogEntryError); - } - - if (timeStampFound) { - if (timeStampOutputFormatText.getText().trim().length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingTimestampFmtError); - timeStampOutputFormatText.setBackground(COLOR_LIGHT_RED); - } else { - try { - new SimpleDateFormat(timeStampOutputFormatText.getText().trim()); - timeStampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); - } catch (IllegalArgumentException e) { - errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampFmtError); - timeStampOutputFormatText.setBackground(COLOR_LIGHT_RED); - } - } - } else { - timeStampPreviewText.setText(Messages.CustomXmlParserInputWizardPage_notimestamporAttributeError); - } - } - } else { - timeStampPreviewText.setText(Messages.CustomXmlParserInputWizardPage_notimestamporAttributeError); - } - - if (errors.length() == 0) { - setDescription(defaultDescription); - setPageComplete(true); - } else { - setDescription(errors.toString()); - setPageComplete(false); - } - } - - public StringBuffer validateElement(InputElement inputElement) { - StringBuffer errors = new StringBuffer(); - ElementNode elementNode = null; - if (selectedElement != null && selectedElement.inputElement.equals(inputElement)) { - elementNode = selectedElement; - } - if (inputElement == definition.rootInputElement) { - if (inputElement.elementName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingDocumentElementError); - if (elementNode != null) { - elementNode.elementNameText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (elementNode != null) { - elementNode.elementNameText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - } - if (inputElement != definition.rootInputElement) { - if (inputElement.logEntry) { - logEntryFound = true; - } - if (inputElement.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - timeStampFound = true; - if (inputElement.inputFormat.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_timestampFormatPrompt - + " (" + Messages.CustomXmlParserInputWizardPage_timestampElementPrompt + " " + getName(inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - try { - new SimpleDateFormat(inputElement.inputFormat); - if (elementNode != null) { - elementNode.tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } catch (IllegalArgumentException e) { - errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampFmtError - + " (" + Messages.CustomXmlParserInputWizardPage_timestampElementPrompt + " " + getName(inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.tagText.setBackground(COLOR_LIGHT_RED); - } - } - } - } else if (inputElement.inputName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingInputElementNameError); - if (elementNode != null) { - elementNode.tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (elementNode != null) { - elementNode.tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - } - if (inputElement.attributes != null) { - if (elementNode != null) { - for (Attribute attribute : elementNode.attributes) { - attribute.attributeNameText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - for (int i = 0; i < inputElement.attributes.size(); i++) { - InputAttribute attribute = inputElement.attributes.get(i); - boolean duplicate = false; - for (int j = i + 1; j < inputElement.attributes.size(); j++) { - InputAttribute otherAttribute = inputElement.attributes.get(j); - if (otherAttribute.attributeName.equals(attribute.attributeName)) { - duplicate = true; - if (elementNode != null) { - elementNode.attributes.get(j).attributeNameText.setBackground(COLOR_LIGHT_RED); - } - } - } - if (attribute.attributeName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingAttribute - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(inputElement) + ": ?). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.attributes.get(i).attributeNameText.setBackground(COLOR_LIGHT_RED); - } - } else if (duplicate) { - errors.append(Messages.CustomXmlParserInputWizardPage_duplicateAttributeError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.attributes.get(i).attributeNameText.setBackground(COLOR_LIGHT_RED); - } - } - if (attribute.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { - timeStampFound = true; - if (attribute.inputFormat.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingTimestampInFmtError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - try { - new SimpleDateFormat(attribute.inputFormat); - if (elementNode != null) { - elementNode.attributes.get(i).tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } catch (IllegalArgumentException e) { - errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampInFmtError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); - } - } - } - } else if (attribute.inputName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingDataGroupNameError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (elementNode != null) { - elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); - } - } else { - if (elementNode != null) { - elementNode.attributes.get(i).tagText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - } - } - if (inputElement.childElements != null) { - for (InputElement child : inputElement.childElements) { - ElementNode childElementNode = null; - if (selectedElement != null && selectedElement.inputElement.equals(child)) { - childElementNode = selectedElement; - } - if (childElementNode != null) { - childElementNode.elementNameText.setBackground(COLOR_TEXT_BACKGROUND); - } - } - for (int i = 0; i < inputElement.childElements.size(); i++) { - InputElement child = inputElement.childElements.get(i); - ElementNode childElementNode = null; - if (selectedElement != null && selectedElement.inputElement.equals(child)) { - childElementNode = selectedElement; - } - if (child.elementName.length() == 0) { - errors.append(Messages.CustomXmlParserInputWizardPage_missingElementNameError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(child) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (childElementNode != null) { - childElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); - } - } else { - boolean duplicate = false; - for (int j = i + 1; j < inputElement.childElements.size(); j++) { - InputElement otherChild = inputElement.childElements.get(j); - if (otherChild.elementName.equals(child.elementName)) { - duplicate = true; - ElementNode otherChildElementNode = null; - if (selectedElement != null && selectedElement.inputElement.equals(otherChild)) { - otherChildElementNode = selectedElement; - } - if (otherChildElementNode != null) { - otherChildElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); - } - } - } - if (duplicate) { - errors.append(Messages.CustomXmlParserInputWizardPage_duplicateElementNameError - + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(child) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (childElementNode != null) { - childElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); - } - } - } - - errors.append(validateElement(child)); - } - } - return errors; - } - - public CustomXmlTraceDefinition getDefinition() { - return definition; - } - - public char[] getInputText() { - return inputText.getText().toCharArray(); - } -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputAttribute; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputElement; +import org.eclipse.swt.SWT; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.browser.TitleEvent; +import org.eclipse.swt.browser.TitleListener; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class CustomXmlParserInputWizardPage extends WizardPage { + + private static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; //$NON-NLS-1$ + private static final String SIMPLE_DATE_FORMAT_URL = "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#skip-navbar_top"; //$NON-NLS-1$ + private static final Image elementImage = Activator.getDefault().getImageFromPath("/icons/elcl16/element_icon.gif"); //$NON-NLS-1$ + private static final Image addImage = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ + private static final Image addNextImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addnext_button.gif"); //$NON-NLS-1$ + private static final Image addChildImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addchild_button.gif"); //$NON-NLS-1$ + private static final Image addManyImage = Activator.getDefault().getImageFromPath("/icons/elcl16/addmany_button.gif"); //$NON-NLS-1$ + private static final Image deleteImage = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ + private static final Image moveUpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ + private static final Image moveDownImage = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ + private static final Image helpImage = Activator.getDefault().getImageFromPath("/icons/elcl16/help_button.gif"); //$NON-NLS-1$ + private static final Color COLOR_LIGHT_RED = new Color(Display.getDefault(), 255, 192, 192); + private static final Color COLOR_TEXT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + private static final Color COLOR_WIDGET_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); + + private final ISelection selection; + private CustomXmlTraceDefinition definition; + private String editDefinitionName; + private String defaultDescription; + private ElementNode selectedElement; + private Composite container; + private Text logtypeText; + private Text timeStampOutputFormatText; + private Text timeStampPreviewText; + private Button removeButton; + private Button addChildButton; + private Button addNextButton; + private Button moveUpButton; + private Button moveDownButton; + private Button feelingLuckyButton; + private ScrolledComposite treeScrolledComposite; + private ScrolledComposite elementScrolledComposite; + private TreeViewer treeViewer; + private Composite treeContainer; + private Composite elementContainer; + private Text errorText; + private StyledText inputText; + private Font fixedFont; + private UpdateListener updateListener; + private Browser helpBrowser; + private Element documentElement; + + // variables used recursively through element traversal + private String timeStampValue; + private String timeStampFormat; + private boolean timeStampFound; + private int logEntriesCount; + private boolean logEntryFound; + + protected CustomXmlParserInputWizardPage(ISelection selection, CustomXmlTraceDefinition definition) { + super("CustomXmlParserWizardPage"); //$NON-NLS-1$ + if (definition == null) { + setTitle(Messages.CustomXmlParserInputWizardPage_titleNew); + defaultDescription = Messages.CustomXmlParserInputWizardPage_descriptionNew; + } else { + setTitle(Messages.CustomXmlParserInputWizardPage_titleEdit); + defaultDescription = Messages.CustomXmlParserInputWizardPage_descriptionEdit; + } + setDescription(defaultDescription); + this.selection = selection; + this.definition = definition; + if (definition != null) { + this.editDefinitionName = definition.definitionName; + } + } + + @Override + public void createControl(Composite parent) { + container = new Composite(parent, SWT.NULL); + container.setLayout(new GridLayout()); + + updateListener = new UpdateListener(); + + Composite headerComposite = new Composite(container, SWT.FILL); + GridLayout headerLayout = new GridLayout(5, false); + headerLayout.marginHeight = 0; + headerLayout.marginWidth = 0; + headerComposite.setLayout(headerLayout); + headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label logtypeLabel = new Label(headerComposite, SWT.NULL); + logtypeLabel.setText(Messages.CustomXmlParserInputWizardPage_logType); + + logtypeText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); + logtypeText.setLayoutData(new GridData(120, SWT.DEFAULT)); + + Label timeStampFormatLabel = new Label(headerComposite, SWT.NULL); + timeStampFormatLabel.setText(Messages.CustomXmlParserInputWizardPage_timestampFormat); + + timeStampOutputFormatText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE); + timeStampOutputFormatText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + timeStampOutputFormatText.setText(DEFAULT_TIMESTAMP_FORMAT); + + Button dateFormatHelpButton = new Button(headerComposite, SWT.PUSH); + dateFormatHelpButton.setImage(helpImage); + dateFormatHelpButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_dateFormatHelp); + dateFormatHelpButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + openHelpShell(SIMPLE_DATE_FORMAT_URL); + } + }); + + Label timeStampPreviewLabel = new Label(headerComposite, SWT.NULL); + timeStampPreviewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 3, 1)); + timeStampPreviewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); + + timeStampPreviewText = new Text(headerComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); + timeStampPreviewText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + timeStampPreviewText.setText("*no time stamp element or attribute*"); //$NON-NLS-1$ + + createButtonBar(); + + SashForm vSash = new SashForm(container, SWT.VERTICAL); + vSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + vSash.setBackground(vSash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); + + SashForm hSash = new SashForm(vSash, SWT.HORIZONTAL); + hSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + treeScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL | SWT.H_SCROLL); + treeScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + treeContainer = new Composite(treeScrolledComposite, SWT.NONE); + treeContainer.setLayout(new FillLayout()); + treeScrolledComposite.setContent(treeContainer); + treeScrolledComposite.setExpandHorizontal(true); + treeScrolledComposite.setExpandVertical(true); + + treeViewer = new TreeViewer(treeContainer, SWT.SINGLE | SWT.BORDER); + treeViewer.setContentProvider(new InputElementTreeNodeContentProvider()); + treeViewer.setLabelProvider(new InputElementTreeLabelProvider()); + treeViewer.addSelectionChangedListener(new InputElementTreeSelectionChangedListener()); + treeContainer.layout(); + + treeScrolledComposite + .setMinSize(treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, treeContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y); + + elementScrolledComposite = new ScrolledComposite(hSash, SWT.V_SCROLL); + elementScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + elementContainer = new Composite(elementScrolledComposite, SWT.NONE); + GridLayout gl = new GridLayout(); + gl.marginHeight = 1; + gl.marginWidth = 0; + elementContainer.setLayout(gl); + elementScrolledComposite.setContent(elementContainer); + elementScrolledComposite.setExpandHorizontal(true); + elementScrolledComposite.setExpandVertical(true); + + if (definition == null) { + definition = new CustomXmlTraceDefinition(); + } + loadDefinition(definition); + treeViewer.expandAll(); + elementContainer.layout(); + + logtypeText.addModifyListener(updateListener); + timeStampOutputFormatText.addModifyListener(updateListener); + + elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, + elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); + + hSash.setWeights(new int[] { 1, 2 }); + + if (definition.rootInputElement == null) { + removeButton.setEnabled(false); + addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentElement); + addNextButton.setEnabled(false); + moveUpButton.setEnabled(false); + moveDownButton.setEnabled(false); + } else { // root is selected + addNextButton.setEnabled(false); + } + + Composite sashBottom = new Composite(vSash, SWT.NONE); + GridLayout sashBottomLayout = new GridLayout(2, false); + sashBottomLayout.marginHeight = 0; + sashBottomLayout.marginWidth = 0; + sashBottom.setLayout(sashBottomLayout); + + Label previewLabel = new Label(sashBottom, SWT.NULL); + previewLabel.setText(Messages.CustomXmlParserInputWizardPage_previewInput); + + errorText = new Text(sashBottom, SWT.SINGLE | SWT.READ_ONLY); + errorText.setBackground(COLOR_WIDGET_BACKGROUND); + errorText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + errorText.setVisible(false); + + inputText = new StyledText(sashBottom, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + if (fixedFont == null) { + if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ + fixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ + } else { + fixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ + } + } + inputText.setFont(fixedFont); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); + gd.heightHint = inputText.computeSize(SWT.DEFAULT, inputText.getLineHeight() * 4).y; + gd.widthHint = 800; + inputText.setLayoutData(gd); + inputText.setText(getSelectionText()); + inputText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + parseXmlInput(inputText.getText()); + } + }); + inputText.addModifyListener(updateListener); + + vSash.setWeights(new int[] { hSash.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sashBottom.computeSize(SWT.DEFAULT, SWT.DEFAULT).y }); + + setControl(container); + } + + private void createButtonBar() { + Composite buttonBar = new Composite(container, SWT.NONE); + GridLayout buttonBarLayout = new GridLayout(6, false); + buttonBarLayout.marginHeight = 0; + buttonBarLayout.marginWidth = 0; + buttonBar.setLayout(buttonBarLayout); + + removeButton = new Button(buttonBar, SWT.PUSH); + removeButton.setImage(deleteImage); + removeButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_removeElement); + removeButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty() || selectedElement == null) { + return; + } + removeElement(); + InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputElement == definition.rootInputElement) { + definition.rootInputElement = null; + } else { + inputElement.parentElement.childElements.remove(inputElement); + } + treeViewer.refresh(); + validate(); + updatePreviews(); + removeButton.setEnabled(false); + if (definition.rootInputElement == null) { + addChildButton.setEnabled(true); + addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentEleemnt); + } else { + addChildButton.setEnabled(false); + } + addNextButton.setEnabled(false); + moveUpButton.setEnabled(false); + moveDownButton.setEnabled(false); + } + }); + + addChildButton = new Button(buttonBar, SWT.PUSH); + addChildButton.setImage(addChildImage); + addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addChildElement); + addChildButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputElement inputElement = new InputElement("", false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ //$NON-NLS-2$ + if (definition.rootInputElement == null) { + definition.rootInputElement = inputElement; + inputElement.elementName = getChildNameSuggestion(null); + } else if (treeViewer.getSelection().isEmpty()) { + return; + } else { + InputElement parentInputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + parentInputElement.addChild(inputElement); + inputElement.elementName = getChildNameSuggestion(parentInputElement); + } + treeViewer.refresh(); + treeViewer.setSelection(new StructuredSelection(inputElement), true); + } + }); + + addNextButton = new Button(buttonBar, SWT.PUSH); + addNextButton.setImage(addNextImage); + addNextButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addNextElement); + addNextButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputElement inputElement = new InputElement("", false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ //$NON-NLS-2$ + if (definition.rootInputElement == null) { + definition.rootInputElement = inputElement; + inputElement.elementName = getChildNameSuggestion(null); + } else if (treeViewer.getSelection().isEmpty()) { + return; + } else { + InputElement previousInputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (previousInputElement == definition.rootInputElement) { + return; + } + previousInputElement.addNext(inputElement); + inputElement.elementName = getChildNameSuggestion(inputElement.parentElement); + } + treeViewer.refresh(); + treeViewer.setSelection(new StructuredSelection(inputElement), true); + } + }); + + feelingLuckyButton = new Button(buttonBar, SWT.PUSH); + feelingLuckyButton.setImage(addManyImage); + feelingLuckyButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_feelingLucky); + feelingLuckyButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + InputElement inputElement = null; + if (definition.rootInputElement == null) { + if (getChildNameSuggestion(null).length() != 0) { + inputElement = new InputElement(getChildNameSuggestion(null), false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ + definition.rootInputElement = inputElement; + feelingLucky(inputElement); + } else { + return; + } + } else if (treeViewer.getSelection().isEmpty()) { + return; + } else { + inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + feelingLucky(inputElement); + } + treeViewer.refresh(); + treeViewer.setSelection(new StructuredSelection(inputElement), true); + treeViewer.expandToLevel(inputElement, AbstractTreeViewer.ALL_LEVELS); + } + }); + + moveUpButton = new Button(buttonBar, SWT.PUSH); + moveUpButton.setImage(moveUpImage); + moveUpButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_moveUp); + moveUpButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty()) { + return; + } + InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputElement == definition.rootInputElement) { + return; + } + inputElement.moveUp(); + treeViewer.refresh(); + validate(); + updatePreviews(); + } + }); + + moveDownButton = new Button(buttonBar, SWT.PUSH); + moveDownButton.setImage(moveDownImage); + moveDownButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_moveDown); + moveDownButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (treeViewer.getSelection().isEmpty()) { + return; + } + InputElement inputElement = (InputElement) ((IStructuredSelection) treeViewer.getSelection()).getFirstElement(); + if (inputElement == definition.rootInputElement) { + return; + } + inputElement.moveDown(); + treeViewer.refresh(); + validate(); + updatePreviews(); + } + }); + } + + private void feelingLucky(InputElement inputElement) { + while (true) { + String attributeName = getAttributeNameSuggestion(inputElement); + if (attributeName.length() == 0) { + break; + } + InputAttribute attribute = new InputAttribute(attributeName, attributeName, 0, ""); //$NON-NLS-1$ + inputElement.addAttribute(attribute); + } + while (true) { + String childName = getChildNameSuggestion(inputElement); + if (childName.length() == 0) { + break; + } + InputElement childElement = new InputElement(childName, false, CustomXmlTraceDefinition.TAG_IGNORE, 0, "", null); //$NON-NLS-1$ + inputElement.addChild(childElement); + feelingLucky(childElement); + } + } + + private static class InputElementTreeNodeContentProvider implements ITreeContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) inputElement; + if (def.rootInputElement != null) { + return new Object[] { def.rootInputElement }; + } + return new Object[0]; + } + + @Override + public Object[] getChildren(Object parentElement) { + InputElement inputElement = (InputElement) parentElement; + if (inputElement.childElements == null) { + return new InputElement[0]; + } + return inputElement.childElements.toArray(); + } + + @Override + public boolean hasChildren(Object element) { + InputElement inputElement = (InputElement) element; + return (inputElement.childElements != null && inputElement.childElements.size() > 0); + } + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + + @Override + public Object getParent(Object element) { + InputElement inputElement = (InputElement) element; + return inputElement.parentElement; + } + } + + private static class InputElementTreeLabelProvider extends ColumnLabelProvider { + + @Override + public Image getImage(Object element) { + return elementImage; + } + + @Override + public String getText(Object element) { + InputElement inputElement = (InputElement) element; + return (inputElement.elementName.trim().length() == 0) ? "?" : inputElement.elementName; //$NON-NLS-1$ + } + } + + private class InputElementTreeSelectionChangedListener implements ISelectionChangedListener { + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (selectedElement != null) { + selectedElement.dispose(); + } + if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + InputElement inputElement = (InputElement) selection.getFirstElement(); + selectedElement = new ElementNode(elementContainer, inputElement); + elementContainer.layout(); + elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, + elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); + container.layout(); + validate(); + updatePreviews(); + removeButton.setEnabled(true); + addChildButton.setEnabled(true); + addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addChildElement); + if (definition.rootInputElement == inputElement) { + addNextButton.setEnabled(false); + } else { + addNextButton.setEnabled(true); + } + moveUpButton.setEnabled(true); + moveDownButton.setEnabled(true); + } else { + removeButton.setEnabled(false); + if (definition.rootInputElement == null) { + addChildButton.setEnabled(true); + addChildButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addDocumentElement); + } else { + addChildButton.setEnabled(false); + } + addNextButton.setEnabled(false); + moveUpButton.setEnabled(false); + moveDownButton.setEnabled(false); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.dialogs.DialogPage#dispose() + */ + @Override + public void dispose() { + if (fixedFont != null) { + fixedFont.dispose(); + fixedFont = null; + } + super.dispose(); + } + + private void loadDefinition(CustomXmlTraceDefinition def) { + logtypeText.setText(def.definitionName); + timeStampOutputFormatText.setText(def.timeStampOutputFormat); + treeViewer.setInput(def); + + if (def.rootInputElement != null) { + treeViewer.setSelection(new StructuredSelection(def.rootInputElement)); + } + } + + private String getName(InputElement inputElement) { + String name = (inputElement.elementName.trim().length() == 0) ? "?" : inputElement.elementName.trim(); //$NON-NLS-1$ + if (inputElement.parentElement == null) { + return name; + } + return getName(inputElement.parentElement) + " : " + name; //$NON-NLS-1$ + } + + private String getName(InputAttribute inputAttribute, InputElement inputElement) { + String name = (inputAttribute.attributeName.trim().length() == 0) ? "?" : inputAttribute.attributeName.trim(); //$NON-NLS-1$ + return getName(inputElement) + " : " + name; //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) + */ + @Override + public void setVisible(boolean visible) { + if (visible) { + validate(); + updatePreviews(); + } + super.setVisible(visible); + } + + public List getInputNames() { + return getInputNames(definition.rootInputElement); + } + + public List getInputNames(InputElement inputElement) { + List inputs = new ArrayList(); + if (inputElement.inputName != null && !inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { + String inputName = inputElement.inputName; + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + if (inputElement.attributes != null) { + for (InputAttribute attribute : inputElement.attributes) { + String inputName = attribute.inputName; + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + } + if (inputElement.childElements != null) { + for (InputElement childInputElement : inputElement.childElements) { + for (String inputName : getInputNames(childInputElement)) { + if (!inputs.contains(inputName)) { + inputs.add(inputName); + } + } + } + } + return inputs; + } + + private void removeElement() { + selectedElement.dispose(); + selectedElement = null; + elementContainer.layout(); + elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, + elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); + container.layout(); + } + + private String getSelectionText() { + InputStream inputStream = null; + if (this.selection instanceof IStructuredSelection) { + Object selection = ((IStructuredSelection) this.selection).getFirstElement(); + if (selection instanceof IFile) { + IFile file = (IFile) selection; + try { + inputStream = file.getContents(); + } catch (CoreException e) { + return ""; //$NON-NLS-1$ + } + } + } + if (inputStream != null) { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder sb = new StringBuilder(); + String line = null; + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); //$NON-NLS-1$ + } + parseXmlInput(sb.toString()); + reader.close(); + return sb.toString(); + } catch (IOException e) { + return ""; //$NON-NLS-1$ + } + } + return ""; //$NON-NLS-1$ + } + + private void parseXmlInput(final String string) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + // The following allows xml parsing without access to the dtd + EntityResolver resolver = new EntityResolver() { + @Override + public InputSource resolveEntity(String publicId, String systemId) { + String empty = ""; //$NON-NLS-1$ + ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); + return new InputSource(bais); + } + }; + db.setEntityResolver(resolver); + + // The following catches xml parsing exceptions + db.setErrorHandler(new ErrorHandler() { + @Override + public void error(SAXParseException saxparseexception) throws SAXException { + } + + @Override + public void warning(SAXParseException saxparseexception) throws SAXException { + } + + @Override + public void fatalError(SAXParseException saxparseexception) throws SAXException { + if (string.trim().length() != 0) { + errorText.setText(saxparseexception.getMessage()); + errorText.setBackground(COLOR_LIGHT_RED); + errorText.setVisible(true); + } + throw saxparseexception; + } + }); + + errorText.setVisible(false); + Document doc = null; + doc = db.parse(new ByteArrayInputStream(string.getBytes())); + documentElement = doc.getDocumentElement(); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error pasing XML input string: " + string, e); //$NON-NLS-1$ + documentElement = null; + } catch (SAXException e) { + documentElement = null; + } catch (IOException e) { + Activator.getDefault().logError("Error pasing XML input string: " + string, e); //$NON-NLS-1$ + documentElement = null; + } + } + + private void updatePreviews() { + updatePreviews(false); + } + + private void initValues() { + timeStampValue = null; + timeStampFormat = null; + logEntriesCount = 0; + logEntryFound = false; + } + + private void updatePreviews(boolean updateAll) { + if (inputText == null) { + // early update during construction + return; + } + inputText.setStyleRanges(new StyleRange[] {}); + if (selectedElement == null) { + return; + } + + initValues(); + + selectedElement.updatePreview(); + + if (timeStampValue != null && timeStampFormat != null) { + try { + SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampFormat); + Date date = dateFormat.parse(timeStampValue); + dateFormat = new SimpleDateFormat(timeStampOutputFormatText.getText().trim()); + timeStampPreviewText.setText(dateFormat.format(date)); + } catch (ParseException e) { + timeStampPreviewText.setText("*parse exception* [" + timeStampValue + "] <> [" + timeStampFormat + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } catch (IllegalArgumentException e) { + timeStampPreviewText.setText("*parse exception* [Illegal Argument]"); //$NON-NLS-1$ + } + } else { + timeStampPreviewText.setText("*no matching time stamp*"); //$NON-NLS-1$ + } + } + + private void openHelpShell(String url) { + if (helpBrowser != null && !helpBrowser.isDisposed()) { + helpBrowser.getShell().setActive(); + if (!helpBrowser.getUrl().equals(url)) { + helpBrowser.setUrl(url); + } + return; + } + final Shell helpShell = new Shell(getShell(), SWT.SHELL_TRIM); + helpShell.setLayout(new FillLayout()); + helpBrowser = new Browser(helpShell, SWT.NONE); + helpBrowser.addTitleListener(new TitleListener() { + @Override + public void changed(TitleEvent event) { + helpShell.setText(event.title); + } + }); + helpBrowser.setBounds(0, 0, 600, 400); + helpShell.pack(); + helpShell.open(); + helpBrowser.setUrl(url); + } + + private class UpdateListener implements ModifyListener, SelectionListener { + + @Override + public void modifyText(ModifyEvent e) { + validate(); + updatePreviews(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + validate(); + updatePreviews(); + } + + @Override + public void widgetSelected(SelectionEvent e) { + validate(); + updatePreviews(); + } + + } + + private class ElementNode { + final InputElement inputElement; + final Group group; + List attributes = new ArrayList(); + List childElements = new ArrayList(); + Text elementNameText; + Composite tagComposite; + Combo tagCombo; + Label tagLabel; + Text tagText; + Combo actionCombo; + Label previewLabel; + Text previewText; + Button logEntryButton; + Label fillerLabel; + Composite addAttributeComposite; + Button addAttributeButton; + Label addAttributeLabel; + + public ElementNode(Composite parent, InputElement inputElement) { + this.inputElement = inputElement; + + group = new Group(parent, SWT.NONE); + GridLayout gl = new GridLayout(2, false); + gl.marginHeight = 0; + group.setLayout(gl); + group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + group.setText(getName(inputElement)); + + Label label = new Label(group, SWT.NULL); + label.setText(Messages.CustomXmlParserInputWizardPage_elementName); + label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + elementNameText = new Text(group, SWT.BORDER | SWT.SINGLE); + GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + elementNameText.setLayoutData(gd); + elementNameText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + ElementNode.this.inputElement.elementName = elementNameText.getText().trim(); + group.setText(getName(ElementNode.this.inputElement)); + } + }); + elementNameText.setText(inputElement.elementName); + elementNameText.addModifyListener(updateListener); + + if (inputElement.parentElement != null) { + previewLabel = new Label(group, SWT.NULL); + previewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + previewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); + + previewText = new Text(group, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); + gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + previewText.setLayoutData(gd); + previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); + previewText.setBackground(COLOR_WIDGET_BACKGROUND); + + logEntryButton = new Button(group, SWT.CHECK); + logEntryButton.setText(Messages.CustomXmlParserInputWizardPage_logEntry); + logEntryButton.setSelection(inputElement.logEntry); + logEntryButton.addSelectionListener(new SelectionListener() { + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + + @Override + public void widgetSelected(SelectionEvent e) { + InputElement parent = ElementNode.this.inputElement.parentElement; + while (parent != null) { + parent.logEntry = false; + parent = parent.parentElement; + } + } + }); + logEntryButton.addSelectionListener(updateListener); + + tagComposite = new Composite(group, SWT.FILL); + GridLayout tagLayout = new GridLayout(4, false); + tagLayout.marginWidth = 0; + tagLayout.marginHeight = 0; + tagComposite.setLayout(tagLayout); + tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + tagCombo.setItems(new String[] { CustomXmlTraceDefinition.TAG_IGNORE, CustomTraceDefinition.TAG_TIMESTAMP, + CustomTraceDefinition.TAG_MESSAGE, CustomTraceDefinition.TAG_OTHER }); + tagCombo.setVisibleItemCount(tagCombo.getItemCount()); + tagCombo.addSelectionListener(new SelectionListener() { + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + + @Override + public void widgetSelected(SelectionEvent e) { + tagText.removeModifyListener(updateListener); + switch (tagCombo.getSelectionIndex()) { + case 0: // Ignore + tagLabel.setVisible(false); + tagText.setVisible(false); + actionCombo.setVisible(false); + break; + case 1: // Time Stamp + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); + tagLabel.setVisible(true); + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + actionCombo.setVisible(true); + break; + case 2: // Message + tagLabel.setVisible(false); + tagText.setVisible(false); + actionCombo.setVisible(true); + break; + case 3: // Other + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); + tagLabel.setVisible(true); + if (tagText.getText().trim().length() == 0) { + tagText.setText(elementNameText.getText().trim()); + } + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + actionCombo.setVisible(true); + break; + default: + break; + } + tagComposite.layout(); + validate(); + updatePreviews(); + } + }); + + tagLabel = new Label(tagComposite, SWT.NULL); + tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + tagText.setLayoutData(gd); + + actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + actionCombo.setItems(new String[] { Messages.CustomXmlParserInputWizardPage_set, Messages.CustomXmlParserInputWizardPage_append, + Messages.CustomXmlParserInputWizardPage_appendWith }); + actionCombo.select(inputElement.inputAction); + actionCombo.addSelectionListener(updateListener); + + if (inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) { + tagCombo.select(0); + tagLabel.setVisible(false); + tagText.setVisible(false); + actionCombo.setVisible(false); + } else if (inputElement.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + tagCombo.select(1); + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); + tagText.setText(inputElement.inputFormat); + tagText.addModifyListener(updateListener); + } else if (inputElement.inputName.equals(CustomTraceDefinition.TAG_MESSAGE)) { + tagCombo.select(2); + tagLabel.setVisible(false); + tagText.setVisible(false); + } else { + tagCombo.select(3); + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); + tagText.setText(inputElement.inputName); + tagText.addModifyListener(updateListener); + } + } + + if (inputElement.attributes != null) { + for (InputAttribute inputAttribute : inputElement.attributes) { + Attribute attribute = new Attribute(group, this, inputAttribute, attributes.size() + 1); + attributes.add(attribute); + } + } + + createAddButton(); + } + + private void updatePreview() { + Element element = getPreviewElement(inputElement); + if (inputElement.parentElement != null) { // no preview text for + // document element + previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); + if (element != null) { + previewText.setText(CustomXmlTrace.parseElement(element, new StringBuffer()).toString()); + if (logEntryButton.getSelection()) { + if (!logEntryFound) { + logEntryFound = true; + logEntriesCount++; + } else { + logEntryButton.setSelection(false); // remove nested + // log entry + } + } + if (tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP) && logEntriesCount <= 1) { + String value = previewText.getText().trim(); + if (value.length() != 0) { + if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_SET) { + timeStampValue = value; + timeStampFormat = tagText.getText().trim(); + } else if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND) { + if (timeStampValue != null) { + timeStampValue += value; + timeStampFormat += tagText.getText().trim(); + } else { + timeStampValue = value; + timeStampFormat = tagText.getText().trim(); + } + } else if (actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { + if (timeStampValue != null) { + timeStampValue += " | " + value; //$NON-NLS-1$ + timeStampFormat += " | " + tagText.getText().trim(); //$NON-NLS-1$ + } else { + timeStampValue = value; + timeStampFormat = tagText.getText().trim(); + } + } + } + } + } + } + for (Attribute attribute : attributes) { + if (element != null) { + String value = element.getAttribute(attribute.attributeNameText.getText().trim()); + if (value.length() != 0) { + attribute.previewText.setText(value); + if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP) && logEntriesCount <= 1) { + if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_SET) { + timeStampValue = value; + timeStampFormat = attribute.tagText.getText().trim(); + } else if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND) { + if (timeStampValue != null) { + timeStampValue += value; + timeStampFormat += attribute.tagText.getText().trim(); + } else { + timeStampValue = value; + timeStampFormat = attribute.tagText.getText().trim(); + } + } else if (attribute.actionCombo.getSelectionIndex() == CustomTraceDefinition.ACTION_APPEND_WITH_SEPARATOR) { + if (timeStampValue != null) { + timeStampValue += " | " + value; //$NON-NLS-1$ + timeStampFormat += " | " + attribute.tagText.getText().trim(); //$NON-NLS-1$ + } else { + timeStampValue = value; + timeStampFormat = attribute.tagText.getText().trim(); + } + } + } + } else { + attribute.previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingAttribute); + } + } else { + attribute.previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatchingElement); + } + } + for (ElementNode child : childElements) { + child.updatePreview(); + } + if (logEntryButton != null && logEntryButton.getSelection()) { + logEntryFound = false; + } + } + + private void createAddButton() { + fillerLabel = new Label(group, SWT.NONE); + + addAttributeComposite = new Composite(group, SWT.NONE); + addAttributeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + GridLayout addAttributeLayout = new GridLayout(2, false); + addAttributeLayout.marginHeight = 0; + addAttributeLayout.marginWidth = 0; + addAttributeComposite.setLayout(addAttributeLayout); + + addAttributeButton = new Button(addAttributeComposite, SWT.PUSH); + addAttributeButton.setImage(addImage); + addAttributeButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_addAttribute); + addAttributeButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + removeAddButton(); + String attributeName = getAttributeNameSuggestion(inputElement); + InputAttribute inputAttribute = new InputAttribute(attributeName, attributeName, 0, ""); //$NON-NLS-1$ + attributes.add(new Attribute(group, ElementNode.this, inputAttribute, attributes.size() + 1)); + createAddButton(); + elementContainer.layout(); + elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, + elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); + group.getParent().layout(); + validate(); + updatePreviews(); + } + }); + + addAttributeLabel = new Label(addAttributeComposite, SWT.NULL); + addAttributeLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + addAttributeLabel.setText(Messages.CustomXmlParserInputWizardPage_newAttibute); + } + + private void removeAddButton() { + fillerLabel.dispose(); + addAttributeComposite.dispose(); + } + + private void removeAttribute(int attributeNumber) { + if (--attributeNumber < attributes.size()) { + attributes.remove(attributeNumber).dispose(); + for (int i = attributeNumber; i < attributes.size(); i++) { + attributes.get(i).setAttributeNumber(i + 1); + } + elementContainer.layout(); + elementScrolledComposite.setMinSize(elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, + elementContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y - 1); + group.getParent().layout(); + } + } + + private void dispose() { + group.dispose(); + } + + private void extractInputs() { + inputElement.elementName = elementNameText.getText().trim(); + if (inputElement.parentElement != null) { + inputElement.logEntry = logEntryButton.getSelection(); + if (tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { + inputElement.inputName = tagText.getText().trim(); + } else { + inputElement.inputName = tagCombo.getText(); + if (tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + inputElement.inputFormat = tagText.getText().trim(); + } + } + inputElement.inputAction = actionCombo.getSelectionIndex(); + } + inputElement.attributes = new ArrayList(attributes.size()); + for (int i = 0; i < attributes.size(); i++) { + Attribute attribute = attributes.get(i); + InputAttribute inputAttribute = new InputAttribute(); + inputAttribute.attributeName = attribute.attributeNameText.getText().trim(); + if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_OTHER)) { + inputAttribute.inputName = attribute.tagText.getText().trim(); + } else { + inputAttribute.inputName = attribute.tagCombo.getText(); + if (attribute.tagCombo.getText().equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + inputAttribute.inputFormat = attribute.tagText.getText().trim(); + } + } + inputAttribute.inputAction = attribute.actionCombo.getSelectionIndex(); + inputElement.addAttribute(inputAttribute); + } + } + } + + private class Attribute { + ElementNode element; + int attributeNumber; + + // children of parent (must be disposed) + Composite labelComposite; + Composite attributeComposite; + Label filler; + Composite tagComposite; + + // children of labelComposite + Label attributeLabel; + + // children of attributeComposite + Text attributeNameText; + Text previewText; + + // children of tagComposite + Combo tagCombo; + Label tagLabel; + Text tagText; + Combo actionCombo; + + public Attribute(Composite parent, ElementNode element, InputAttribute inputAttribute, int attributeNumber) { + this.element = element; + this.attributeNumber = attributeNumber; + + labelComposite = new Composite(parent, SWT.FILL); + GridLayout labelLayout = new GridLayout(2, false); + labelLayout.marginWidth = 0; + labelLayout.marginHeight = 0; + labelComposite.setLayout(labelLayout); + labelComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + Button deleteButton = new Button(labelComposite, SWT.PUSH); + deleteButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + deleteButton.setImage(deleteImage); + deleteButton.setToolTipText(Messages.CustomXmlParserInputWizardPage_removeAttribute); + deleteButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Attribute.this.element.removeAttribute(Attribute.this.attributeNumber); + validate(); + updatePreviews(); + } + }); + + attributeLabel = new Label(labelComposite, SWT.NULL); + attributeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + attributeLabel.setText(Messages.CustomXmlParserInputWizardPage_attibute); + + attributeComposite = new Composite(parent, SWT.FILL); + GridLayout attributeLayout = new GridLayout(4, false); + attributeLayout.marginWidth = 0; + attributeLayout.marginHeight = 0; + attributeComposite.setLayout(attributeLayout); + attributeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label nameLabel = new Label(attributeComposite, SWT.NONE); + nameLabel.setText(Messages.CustomXmlParserInputWizardPage_name); + + attributeNameText = new Text(attributeComposite, SWT.BORDER | SWT.SINGLE); + attributeNameText.setLayoutData(new GridData(120, SWT.DEFAULT)); + attributeNameText.setText(inputAttribute.attributeName); + attributeNameText.addModifyListener(updateListener); + + Label previewLabel = new Label(attributeComposite, SWT.NONE); + previewLabel.setText(Messages.CustomXmlParserInputWizardPage_preview); + + previewText = new Text(attributeComposite, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); + GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + previewText.setLayoutData(gd); + previewText.setText(Messages.CustomXmlParserInputWizardPage_noMatch); + previewText.setBackground(COLOR_WIDGET_BACKGROUND); + + filler = new Label(parent, SWT.NULL); + + tagComposite = new Composite(parent, SWT.FILL); + GridLayout tagLayout = new GridLayout(4, false); + tagLayout.marginWidth = 0; + tagLayout.marginHeight = 0; + tagComposite.setLayout(tagLayout); + tagComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + tagCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + tagCombo.setItems(new String[] { CustomTraceDefinition.TAG_TIMESTAMP, CustomTraceDefinition.TAG_MESSAGE, + CustomTraceDefinition.TAG_OTHER }); + tagCombo.select(2); // Other + tagCombo.addSelectionListener(new SelectionListener() { + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + + @Override + public void widgetSelected(SelectionEvent e) { + tagText.removeModifyListener(updateListener); + switch (tagCombo.getSelectionIndex()) { + case 0: // Time Stamp + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); + tagLabel.setVisible(true); + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + break; + case 1: // Message + tagLabel.setVisible(false); + tagText.setVisible(false); + break; + case 2: // Other + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); + tagLabel.setVisible(true); + if (tagText.getText().trim().length() == 0) { + tagText.setText(attributeNameText.getText().trim()); + } + tagText.setVisible(true); + tagText.addModifyListener(updateListener); + break; + default: + break; + } + tagComposite.layout(); + validate(); + updatePreviews(); + } + }); + + tagLabel = new Label(tagComposite, SWT.NULL); + tagLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + + tagText = new Text(tagComposite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + gd.widthHint = 0; + tagText.setLayoutData(gd); + tagText.setText(attributeNameText.getText()); + + actionCombo = new Combo(tagComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + actionCombo.setItems(new String[] { Messages.CustomXmlParserInputWizardPage_set, Messages.CustomXmlParserInputWizardPage_append, + Messages.CustomXmlParserInputWizardPage_appendWith }); + actionCombo.select(inputAttribute.inputAction); + actionCombo.addSelectionListener(updateListener); + + if (inputAttribute.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + tagCombo.select(0); + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_format); + tagText.setText(inputAttribute.inputFormat); + tagText.addModifyListener(updateListener); + } else if (inputAttribute.inputName.equals(CustomTraceDefinition.TAG_MESSAGE)) { + tagCombo.select(1); + tagLabel.setVisible(false); + tagText.setVisible(false); + } else { + tagCombo.select(2); + tagLabel.setText(Messages.CustomXmlParserInputWizardPage_tagName); + tagText.setText(inputAttribute.inputName); + tagText.addModifyListener(updateListener); + } + } + + private void dispose() { + labelComposite.dispose(); + attributeComposite.dispose(); + filler.dispose(); + tagComposite.dispose(); + } + + private void setAttributeNumber(int attributeNumber) { + this.attributeNumber = attributeNumber; + labelComposite.layout(); + } + } + + private Element getPreviewElement(InputElement inputElement) { + Element element = documentElement; + if (element != null) { + if (!documentElement.getNodeName().equals(definition.rootInputElement.elementName)) { + return null; + } + ArrayList elementNames = new ArrayList(); + while (inputElement != null) { + elementNames.add(inputElement.elementName); + inputElement = inputElement.parentElement; + } + for (int i = elementNames.size() - 1; --i >= 0;) { + NodeList childList = element.getChildNodes(); + element = null; + for (int j = 0; j < childList.getLength(); j++) { + Node child = childList.item(j); + if (child instanceof Element && child.getNodeName().equals(elementNames.get(i))) { + element = (Element) child; + break; + } + } + if (element == null) { + break; + } + } + if (element != null) { + return element; + } + } + return null; + } + + private String getChildNameSuggestion(InputElement inputElement) { + if (inputElement == null) { + if (documentElement != null) { + return documentElement.getNodeName(); + } + } else { + Element element = getPreviewElement(inputElement); + if (element != null) { + NodeList childNodes = element.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node node = childNodes.item(i); + if (node instanceof Element) { + boolean unused = true; + if (inputElement.childElements != null) { + for (InputElement child : inputElement.childElements) { + if (child.elementName.equals(node.getNodeName())) { + unused = false; + break; + } + } + } + if (unused) { + return node.getNodeName(); + } + } + } + } + } + return ""; //$NON-NLS-1$ + } + + private String getAttributeNameSuggestion(InputElement inputElement) { + Element element = getPreviewElement(inputElement); + if (element != null) { + NamedNodeMap attributeMap = element.getAttributes(); + for (int i = 0; i < attributeMap.getLength(); i++) { + Node node = attributeMap.item(i); + boolean unused = true; + if (inputElement.attributes != null) { + for (InputAttribute attribute : inputElement.attributes) { + if (attribute.attributeName.equals(node.getNodeName())) { + unused = false; + break; + } + } + } + if (unused) { + return node.getNodeName(); + } + } + } + return ""; //$NON-NLS-1$ + } + + private void validate() { + definition.definitionName = logtypeText.getText().trim(); + definition.timeStampOutputFormat = timeStampOutputFormatText.getText().trim(); + + if (selectedElement != null) { + selectedElement.extractInputs(); + treeViewer.refresh(); + } + + StringBuffer errors = new StringBuffer(); + + if (definition.definitionName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_emptyLogTypeError); + logtypeText.setBackground(COLOR_LIGHT_RED); + } else { + logtypeText.setBackground(COLOR_TEXT_BACKGROUND); + for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { + if (definition.definitionName.equals(def.definitionName)) { + if (editDefinitionName == null || !editDefinitionName.equals(definition.definitionName)) { + errors.append(Messages.CustomXmlParserInputWizardPage_duplicatelogTypeError); + logtypeText.setBackground(COLOR_LIGHT_RED); + break; + } + } + } + } + + if (definition.rootInputElement == null) { + errors.append(Messages.CustomXmlParserInputWizardPage_noDocumentError); + } + + if (definition.rootInputElement != null) { + logEntryFound = false; + timeStampFound = false; + + errors.append(validateElement(definition.rootInputElement)); + + if ((definition.rootInputElement.attributes != null && definition.rootInputElement.attributes.size() != 0) + || (definition.rootInputElement.childElements != null && definition.rootInputElement.childElements.size() != 0) + || errors.length() == 0) { + if (!logEntryFound) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingLogEntryError); + } + + if (timeStampFound) { + if (timeStampOutputFormatText.getText().trim().length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingTimestampFmtError); + timeStampOutputFormatText.setBackground(COLOR_LIGHT_RED); + } else { + try { + new SimpleDateFormat(timeStampOutputFormatText.getText().trim()); + timeStampOutputFormatText.setBackground(COLOR_TEXT_BACKGROUND); + } catch (IllegalArgumentException e) { + errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampFmtError); + timeStampOutputFormatText.setBackground(COLOR_LIGHT_RED); + } + } + } else { + timeStampPreviewText.setText(Messages.CustomXmlParserInputWizardPage_notimestamporAttributeError); + } + } + } else { + timeStampPreviewText.setText(Messages.CustomXmlParserInputWizardPage_notimestamporAttributeError); + } + + if (errors.length() == 0) { + setDescription(defaultDescription); + setPageComplete(true); + } else { + setDescription(errors.toString()); + setPageComplete(false); + } + } + + public StringBuffer validateElement(InputElement inputElement) { + StringBuffer errors = new StringBuffer(); + ElementNode elementNode = null; + if (selectedElement != null && selectedElement.inputElement.equals(inputElement)) { + elementNode = selectedElement; + } + if (inputElement == definition.rootInputElement) { + if (inputElement.elementName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingDocumentElementError); + if (elementNode != null) { + elementNode.elementNameText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (elementNode != null) { + elementNode.elementNameText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + } + if (inputElement != definition.rootInputElement) { + if (inputElement.logEntry) { + logEntryFound = true; + } + if (inputElement.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + timeStampFound = true; + if (inputElement.inputFormat.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_timestampFormatPrompt + + " (" + Messages.CustomXmlParserInputWizardPage_timestampElementPrompt + " " + getName(inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + try { + new SimpleDateFormat(inputElement.inputFormat); + if (elementNode != null) { + elementNode.tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } catch (IllegalArgumentException e) { + errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampFmtError + + " (" + Messages.CustomXmlParserInputWizardPage_timestampElementPrompt + " " + getName(inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.tagText.setBackground(COLOR_LIGHT_RED); + } + } + } + } else if (inputElement.inputName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingInputElementNameError); + if (elementNode != null) { + elementNode.tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (elementNode != null) { + elementNode.tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + } + if (inputElement.attributes != null) { + if (elementNode != null) { + for (Attribute attribute : elementNode.attributes) { + attribute.attributeNameText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + for (int i = 0; i < inputElement.attributes.size(); i++) { + InputAttribute attribute = inputElement.attributes.get(i); + boolean duplicate = false; + for (int j = i + 1; j < inputElement.attributes.size(); j++) { + InputAttribute otherAttribute = inputElement.attributes.get(j); + if (otherAttribute.attributeName.equals(attribute.attributeName)) { + duplicate = true; + if (elementNode != null) { + elementNode.attributes.get(j).attributeNameText.setBackground(COLOR_LIGHT_RED); + } + } + } + if (attribute.attributeName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingAttribute + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(inputElement) + ": ?). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.attributes.get(i).attributeNameText.setBackground(COLOR_LIGHT_RED); + } + } else if (duplicate) { + errors.append(Messages.CustomXmlParserInputWizardPage_duplicateAttributeError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.attributes.get(i).attributeNameText.setBackground(COLOR_LIGHT_RED); + } + } + if (attribute.inputName.equals(CustomTraceDefinition.TAG_TIMESTAMP)) { + timeStampFound = true; + if (attribute.inputFormat.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingTimestampInFmtError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + try { + new SimpleDateFormat(attribute.inputFormat); + if (elementNode != null) { + elementNode.attributes.get(i).tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } catch (IllegalArgumentException e) { + errors.append(Messages.CustomXmlParserInputWizardPage_invalidTimestampInFmtError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); + } + } + } + } else if (attribute.inputName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingDataGroupNameError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(attribute, inputElement) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (elementNode != null) { + elementNode.attributes.get(i).tagText.setBackground(COLOR_LIGHT_RED); + } + } else { + if (elementNode != null) { + elementNode.attributes.get(i).tagText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + } + } + if (inputElement.childElements != null) { + for (InputElement child : inputElement.childElements) { + ElementNode childElementNode = null; + if (selectedElement != null && selectedElement.inputElement.equals(child)) { + childElementNode = selectedElement; + } + if (childElementNode != null) { + childElementNode.elementNameText.setBackground(COLOR_TEXT_BACKGROUND); + } + } + for (int i = 0; i < inputElement.childElements.size(); i++) { + InputElement child = inputElement.childElements.get(i); + ElementNode childElementNode = null; + if (selectedElement != null && selectedElement.inputElement.equals(child)) { + childElementNode = selectedElement; + } + if (child.elementName.length() == 0) { + errors.append(Messages.CustomXmlParserInputWizardPage_missingElementNameError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(child) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (childElementNode != null) { + childElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); + } + } else { + boolean duplicate = false; + for (int j = i + 1; j < inputElement.childElements.size(); j++) { + InputElement otherChild = inputElement.childElements.get(j); + if (otherChild.elementName.equals(child.elementName)) { + duplicate = true; + ElementNode otherChildElementNode = null; + if (selectedElement != null && selectedElement.inputElement.equals(otherChild)) { + otherChildElementNode = selectedElement; + } + if (otherChildElementNode != null) { + otherChildElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); + } + } + } + if (duplicate) { + errors.append(Messages.CustomXmlParserInputWizardPage_duplicateElementNameError + + " (" + Messages.CustomXmlParserInputWizardPage_attributePrompt + " " + getName(child) + "). "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (childElementNode != null) { + childElementNode.elementNameText.setBackground(COLOR_LIGHT_RED); + } + } + } + + errors.append(validateElement(child)); + } + } + return errors; + } + + public CustomXmlTraceDefinition getDefinition() { + return definition; + } + + public char[] getInputText() { + return inputText.getText().toCharArray(); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserOutputWizardPage.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserOutputWizardPage.java index c17e4f099e..398ad3a60a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserOutputWizardPage.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserOutputWizardPage.java @@ -1,298 +1,298 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; -import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Text; - -public class CustomXmlParserOutputWizardPage extends WizardPage { - - private static final Image upImage = Activator.getDefault().getImageFromPath("/icons/elcl16/up_button.gif"); //$NON-NLS-1$ - private static final Image downImage = Activator.getDefault().getImageFromPath("/icons/elcl16/down_button.gif"); //$NON-NLS-1$ - private final CustomXmlParserWizard wizard; - private CustomXmlTraceDefinition definition; - List outputs = new ArrayList(); - // Output messageOutput; - Composite container; - SashForm sash; - // Text timestampFormatText; - // Text timestampPreviewText; - ScrolledComposite outputsScrolledComposite; - Composite outputsContainer; - // ScrolledComposite inputScrolledComposite; - Composite tableContainer; - CustomEventsTable previewTable; - File tmpFile; - - protected CustomXmlParserOutputWizardPage(final CustomXmlParserWizard wizard) { - super("CustomParserOutputWizardPage"); //$NON-NLS-1$ - setTitle(wizard.inputPage.getTitle()); - setDescription(Messages.CustomXmlParserOutputWizardPage_description); - this.wizard = wizard; - setPageComplete(false); - } - - @Override - public void createControl(final Composite parent) { - container = new Composite(parent, SWT.NULL); - container.setLayout(new GridLayout()); - - sash = new SashForm(container, SWT.VERTICAL); - sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - sash.setBackground(sash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); - - outputsScrolledComposite = new ScrolledComposite(sash, SWT.V_SCROLL); - outputsScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - outputsContainer = new Composite(outputsScrolledComposite, SWT.NONE); - final GridLayout outputsLayout = new GridLayout(4, false); - outputsLayout.marginHeight = 10; - outputsLayout.marginWidth = 0; - outputsContainer.setLayout(outputsLayout); - outputsScrolledComposite.setContent(outputsContainer); - outputsScrolledComposite.setExpandHorizontal(true); - outputsScrolledComposite.setExpandVertical(true); - - outputsContainer.layout(); - - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - - tableContainer = new Composite(sash, SWT.NONE); - final GridLayout tableLayout = new GridLayout(); - tableLayout.marginHeight = 0; - tableLayout.marginWidth = 0; - tableContainer.setLayout(tableLayout); - previewTable = new CustomEventsTable(new CustomXmlTraceDefinition(), tableContainer, 0); - previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - if (wizard.definition != null) - loadDefinition(wizard.definition); - setControl(container); - - } - - @Override - public void dispose() { - previewTable.dispose(); - super.dispose(); - } - - private void loadDefinition(final CustomTraceDefinition definition) { - for (final OutputColumn outputColumn : definition.outputs) { - final Output output = new Output(outputsContainer, outputColumn.name); - outputs.add(output); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) - */ - @Override - public void setVisible(final boolean visible) { - if (visible) { - this.definition = wizard.inputPage.getDefinition(); - final List outputNames = wizard.inputPage.getInputNames(); - - // dispose outputs that have been removed in the input page - final Iterator iter = outputs.iterator(); - while (iter.hasNext()) { - final Output output = iter.next(); - boolean found = false; - for (final String name : outputNames) - if (output.name.equals(name)) { - found = true; - break; - } - if (!found) { - output.dispose(); - iter.remove(); - } - } - - // create outputs that have been added in the input page - for (final String name : outputNames) { - boolean found = false; - for (final Output output : outputs) - if (output.name.equals(name)) { - found = true; - break; - } - if (!found) - outputs.add(new Output(outputsContainer, name)); - } - - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - updatePreviewTable(); - if (sash.getSize().y > outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y + previewTable.getTable().getItemHeight()) - sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sash.getSize().y - outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); - else - sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, previewTable.getTable().getItemHeight()}); - setPageComplete(true); - } else - setPageComplete(false); - super.setVisible(visible); - } - - private void moveBefore(final Output moved) { - final int i = outputs.indexOf(moved); - if (i > 0) { - final Output previous = outputs.get(i-1); - moved.enabledButton.moveAbove(previous.enabledButton); - moved.nameLabel.moveBelow(moved.enabledButton); - moved.upButton.moveBelow(moved.nameLabel); - moved.downButton.moveBelow(moved.upButton); - outputs.add(i-1, outputs.remove(i)); - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - container.layout(); - updatePreviewTable(); - } - } - - private void moveAfter(final Output moved) { - final int i = outputs.indexOf(moved); - if (i+1 < outputs.size()) { - final Output next = outputs.get(i+1); - moved.enabledButton.moveBelow(next.downButton); - moved.nameLabel.moveBelow(moved.enabledButton); - moved.upButton.moveBelow(moved.nameLabel); - moved.downButton.moveBelow(moved.upButton); - outputs.add(i+1, outputs.remove(i)); - outputsContainer.layout(); - outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); - container.layout(); - updatePreviewTable(); - } - } - - private void updatePreviewTable() { - final int CACHE_SIZE = 50; - definition.outputs = extractOutputs(); - - try { - tmpFile = Activator.getDefault().getStateLocation().addTrailingSeparator().append("customwizard.tmp").toFile(); //$NON-NLS-1$ - final FileWriter writer = new FileWriter(tmpFile); - writer.write(wizard.inputPage.getInputText()); - writer.close(); - - final ITmfTrace trace = new CustomXmlTrace(null, definition, tmpFile.getAbsolutePath(), CACHE_SIZE); - previewTable.dispose(); - previewTable = new CustomEventsTable(definition, tableContainer, CACHE_SIZE); - previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - previewTable.setTrace(trace, true); - } catch (final TmfTraceException e) { - Activator.getDefault().logError("Error creating CustomXmlTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ - } catch (final IOException e) { - Activator.getDefault().logError("Error creating CustomXmlTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ - } - - tableContainer.layout(); - container.layout(); - } - - public List extractOutputs() { - int numColumns = 0; - for (int i = 0; i < outputs.size(); i++) - if (outputs.get(i).enabledButton.getSelection()) - numColumns++; - final List outputColumns = new ArrayList(numColumns); - numColumns = 0; - for (int i = 0; i < outputs.size(); i++) { - final Output output = outputs.get(i); - if (output.enabledButton.getSelection()) { - final OutputColumn column = new OutputColumn(); - column.name = output.nameLabel.getText(); - outputColumns.add(column); - } - } - return outputColumns; - } - - private class Output { - String name; - Button enabledButton; - Text nameLabel; - Button upButton; - Button downButton; - - public Output(final Composite parent, final String name) { - this.name = name; - - enabledButton = new Button(parent, SWT.CHECK); - enabledButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_visible); - enabledButton.setSelection(true); - enabledButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - updatePreviewTable(); - } - }); - // if (messageOutput != null) { - // enabledButton.moveAbove(messageOutput.enabledButton); - // } - - nameLabel = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE); - nameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - nameLabel.setText(name); - nameLabel.moveBelow(enabledButton); - - upButton = new Button(parent, SWT.PUSH); - upButton.setImage(upImage); - upButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_moveBefore); - upButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - moveBefore(Output.this); - } - }); - upButton.moveBelow(nameLabel); - - downButton = new Button(parent, SWT.PUSH); - downButton.setImage(downImage); - downButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_moveAfter); - downButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(final SelectionEvent e) { - moveAfter(Output.this); - } - }); - downButton.moveBelow(upButton); - } - - private void dispose() { - enabledButton.dispose(); - nameLabel.dispose(); - upButton.dispose(); - downButton.dispose(); - } - } - - public CustomXmlTraceDefinition getDefinition() { - return definition; - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; +import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; + +public class CustomXmlParserOutputWizardPage extends WizardPage { + + private static final Image upImage = Activator.getDefault().getImageFromPath("/icons/elcl16/up_button.gif"); //$NON-NLS-1$ + private static final Image downImage = Activator.getDefault().getImageFromPath("/icons/elcl16/down_button.gif"); //$NON-NLS-1$ + private final CustomXmlParserWizard wizard; + private CustomXmlTraceDefinition definition; + List outputs = new ArrayList(); + // Output messageOutput; + Composite container; + SashForm sash; + // Text timestampFormatText; + // Text timestampPreviewText; + ScrolledComposite outputsScrolledComposite; + Composite outputsContainer; + // ScrolledComposite inputScrolledComposite; + Composite tableContainer; + CustomEventsTable previewTable; + File tmpFile; + + protected CustomXmlParserOutputWizardPage(final CustomXmlParserWizard wizard) { + super("CustomParserOutputWizardPage"); //$NON-NLS-1$ + setTitle(wizard.inputPage.getTitle()); + setDescription(Messages.CustomXmlParserOutputWizardPage_description); + this.wizard = wizard; + setPageComplete(false); + } + + @Override + public void createControl(final Composite parent) { + container = new Composite(parent, SWT.NULL); + container.setLayout(new GridLayout()); + + sash = new SashForm(container, SWT.VERTICAL); + sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + sash.setBackground(sash.getDisplay().getSystemColor(SWT.COLOR_GRAY)); + + outputsScrolledComposite = new ScrolledComposite(sash, SWT.V_SCROLL); + outputsScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + outputsContainer = new Composite(outputsScrolledComposite, SWT.NONE); + final GridLayout outputsLayout = new GridLayout(4, false); + outputsLayout.marginHeight = 10; + outputsLayout.marginWidth = 0; + outputsContainer.setLayout(outputsLayout); + outputsScrolledComposite.setContent(outputsContainer); + outputsScrolledComposite.setExpandHorizontal(true); + outputsScrolledComposite.setExpandVertical(true); + + outputsContainer.layout(); + + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + + tableContainer = new Composite(sash, SWT.NONE); + final GridLayout tableLayout = new GridLayout(); + tableLayout.marginHeight = 0; + tableLayout.marginWidth = 0; + tableContainer.setLayout(tableLayout); + previewTable = new CustomEventsTable(new CustomXmlTraceDefinition(), tableContainer, 0); + previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + if (wizard.definition != null) + loadDefinition(wizard.definition); + setControl(container); + + } + + @Override + public void dispose() { + previewTable.dispose(); + super.dispose(); + } + + private void loadDefinition(final CustomTraceDefinition definition) { + for (final OutputColumn outputColumn : definition.outputs) { + final Output output = new Output(outputsContainer, outputColumn.name); + outputs.add(output); + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) + */ + @Override + public void setVisible(final boolean visible) { + if (visible) { + this.definition = wizard.inputPage.getDefinition(); + final List outputNames = wizard.inputPage.getInputNames(); + + // dispose outputs that have been removed in the input page + final Iterator iter = outputs.iterator(); + while (iter.hasNext()) { + final Output output = iter.next(); + boolean found = false; + for (final String name : outputNames) + if (output.name.equals(name)) { + found = true; + break; + } + if (!found) { + output.dispose(); + iter.remove(); + } + } + + // create outputs that have been added in the input page + for (final String name : outputNames) { + boolean found = false; + for (final Output output : outputs) + if (output.name.equals(name)) { + found = true; + break; + } + if (!found) + outputs.add(new Output(outputsContainer, name)); + } + + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + updatePreviewTable(); + if (sash.getSize().y > outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y + previewTable.getTable().getItemHeight()) + sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, sash.getSize().y - outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y}); + else + sash.setWeights(new int[] {outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y, previewTable.getTable().getItemHeight()}); + setPageComplete(true); + } else + setPageComplete(false); + super.setVisible(visible); + } + + private void moveBefore(final Output moved) { + final int i = outputs.indexOf(moved); + if (i > 0) { + final Output previous = outputs.get(i-1); + moved.enabledButton.moveAbove(previous.enabledButton); + moved.nameLabel.moveBelow(moved.enabledButton); + moved.upButton.moveBelow(moved.nameLabel); + moved.downButton.moveBelow(moved.upButton); + outputs.add(i-1, outputs.remove(i)); + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + container.layout(); + updatePreviewTable(); + } + } + + private void moveAfter(final Output moved) { + final int i = outputs.indexOf(moved); + if (i+1 < outputs.size()) { + final Output next = outputs.get(i+1); + moved.enabledButton.moveBelow(next.downButton); + moved.nameLabel.moveBelow(moved.enabledButton); + moved.upButton.moveBelow(moved.nameLabel); + moved.downButton.moveBelow(moved.upButton); + outputs.add(i+1, outputs.remove(i)); + outputsContainer.layout(); + outputsScrolledComposite.setMinSize(outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, outputsContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT).y-5); + container.layout(); + updatePreviewTable(); + } + } + + private void updatePreviewTable() { + final int CACHE_SIZE = 50; + definition.outputs = extractOutputs(); + + try { + tmpFile = Activator.getDefault().getStateLocation().addTrailingSeparator().append("customwizard.tmp").toFile(); //$NON-NLS-1$ + final FileWriter writer = new FileWriter(tmpFile); + writer.write(wizard.inputPage.getInputText()); + writer.close(); + + final ITmfTrace trace = new CustomXmlTrace(null, definition, tmpFile.getAbsolutePath(), CACHE_SIZE); + previewTable.dispose(); + previewTable = new CustomEventsTable(definition, tableContainer, CACHE_SIZE); + previewTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + previewTable.setTrace(trace, true); + } catch (final TmfTraceException e) { + Activator.getDefault().logError("Error creating CustomXmlTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ + } catch (final IOException e) { + Activator.getDefault().logError("Error creating CustomXmlTrace. File:" + tmpFile.getAbsolutePath(), e); //$NON-NLS-1$ + } + + tableContainer.layout(); + container.layout(); + } + + public List extractOutputs() { + int numColumns = 0; + for (int i = 0; i < outputs.size(); i++) + if (outputs.get(i).enabledButton.getSelection()) + numColumns++; + final List outputColumns = new ArrayList(numColumns); + numColumns = 0; + for (int i = 0; i < outputs.size(); i++) { + final Output output = outputs.get(i); + if (output.enabledButton.getSelection()) { + final OutputColumn column = new OutputColumn(); + column.name = output.nameLabel.getText(); + outputColumns.add(column); + } + } + return outputColumns; + } + + private class Output { + String name; + Button enabledButton; + Text nameLabel; + Button upButton; + Button downButton; + + public Output(final Composite parent, final String name) { + this.name = name; + + enabledButton = new Button(parent, SWT.CHECK); + enabledButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_visible); + enabledButton.setSelection(true); + enabledButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + updatePreviewTable(); + } + }); + // if (messageOutput != null) { + // enabledButton.moveAbove(messageOutput.enabledButton); + // } + + nameLabel = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE); + nameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + nameLabel.setText(name); + nameLabel.moveBelow(enabledButton); + + upButton = new Button(parent, SWT.PUSH); + upButton.setImage(upImage); + upButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_moveBefore); + upButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + moveBefore(Output.this); + } + }); + upButton.moveBelow(nameLabel); + + downButton = new Button(parent, SWT.PUSH); + downButton.setImage(downImage); + downButton.setToolTipText(Messages.CustomXmlParserOutputWizardPage_moveAfter); + downButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(final SelectionEvent e) { + moveAfter(Output.this); + } + }); + downButton.moveBelow(upButton); + } + + private void dispose() { + enabledButton.dispose(); + nameLabel.dispose(); + upButton.dispose(); + downButton.dispose(); + } + } + + public CustomXmlTraceDefinition getDefinition() { + return definition; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserWizard.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserWizard.java index 235877f6eb..d51b9e1c28 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserWizard.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/parsers/wizards/CustomXmlParserWizard.java @@ -1,53 +1,53 @@ -package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; - -public class CustomXmlParserWizard extends Wizard implements INewWizard { - - CustomXmlParserInputWizardPage inputPage; - CustomXmlParserOutputWizardPage outputPage; - private ISelection selection; - CustomXmlTraceDefinition definition; - - public CustomXmlParserWizard() { - super(); - } - - public CustomXmlParserWizard(CustomXmlTraceDefinition definition) { - super(); - this.definition = definition; - } - - @Override - public boolean performFinish() { - CustomXmlTraceDefinition def = outputPage.getDefinition(); - if (definition != null && !definition.definitionName.equals(def.definitionName)) { - CustomXmlTraceDefinition.delete(definition.definitionName); - } - def.save(); - return true; - } - - /** - * Adding the page to the wizard. - */ - - @Override - public void addPages() { - inputPage = new CustomXmlParserInputWizardPage(selection, definition); - addPage(inputPage); - outputPage = new CustomXmlParserOutputWizardPage(this); - addPage(outputPage); - } - - @Override - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } - -} +package org.eclipse.linuxtools.internal.tmf.ui.parsers.wizards; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; + +public class CustomXmlParserWizard extends Wizard implements INewWizard { + + CustomXmlParserInputWizardPage inputPage; + CustomXmlParserOutputWizardPage outputPage; + private ISelection selection; + CustomXmlTraceDefinition definition; + + public CustomXmlParserWizard() { + super(); + } + + public CustomXmlParserWizard(CustomXmlTraceDefinition definition) { + super(); + this.definition = definition; + } + + @Override + public boolean performFinish() { + CustomXmlTraceDefinition def = outputPage.getDefinition(); + if (definition != null && !definition.definitionName.equals(def.definitionName)) { + CustomXmlTraceDefinition.delete(definition.definitionName); + } + def.save(); + return true; + } + + /** + * Adding the page to the wizard. + */ + + @Override + public void addPages() { + inputPage = new CustomXmlParserInputWizardPage(selection, definition); + addPage(inputPage); + outputPage = new CustomXmlParserOutputWizardPage(this); + addPage(outputPage); + } + + @Override + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceClosedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceClosedSignal.java index 39f2bca7a4..0b86a99383 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceClosedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceClosedSignal.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.signal; - -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -/** - * Signal that a trace was closed - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceClosedSignal extends TmfSignal { - - private final ITmfTrace fTrace; - - public TmfTraceClosedSignal(Object source, ITmfTrace trace) { - super(source); - fTrace = trace; - } - - public ITmfTrace getTrace() { - return fTrace; - } - - @Override - public String toString() { - return "[TmfTraceClosedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.signal; + +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +/** + * Signal that a trace was closed + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceClosedSignal extends TmfSignal { + + private final ITmfTrace fTrace; + + public TmfTraceClosedSignal(Object source, ITmfTrace trace) { + super(source); + fTrace = trace; + } + + public ITmfTrace getTrace() { + return fTrace; + } + + @Override + public String toString() { + return "[TmfTraceClosedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceOpenedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceOpenedSignal.java index e507897e7e..66ee704562 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceOpenedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceOpenedSignal.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.signal; - -import org.eclipse.core.resources.IFile; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; - -/** - * Signal that a trace was opened - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceOpenedSignal extends TmfSignal { - - private final ITmfTrace fTrace; - private final IFile fBookmarksFile; - private final ITmfEventsFilterProvider fEventsFilterProvider; - - public TmfTraceOpenedSignal(Object source, ITmfTrace trace, IFile bookmarksFile, ITmfEventsFilterProvider eventsFilterProvider) { - super(source); - fTrace = trace; - fBookmarksFile = bookmarksFile; - fEventsFilterProvider = eventsFilterProvider; - } - - public ITmfTrace getTrace() { - return fTrace; - } - - public IFile getBookmarksFile() { - return fBookmarksFile; - } - - public ITmfEventsFilterProvider getEventsFilterProvider() { - return fEventsFilterProvider; - } - - @Override - public String toString() { - return "[TmfTraceOpenedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.signal; + +import org.eclipse.core.resources.IFile; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; + +/** + * Signal that a trace was opened + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceOpenedSignal extends TmfSignal { + + private final ITmfTrace fTrace; + private final IFile fBookmarksFile; + private final ITmfEventsFilterProvider fEventsFilterProvider; + + public TmfTraceOpenedSignal(Object source, ITmfTrace trace, IFile bookmarksFile, ITmfEventsFilterProvider eventsFilterProvider) { + super(source); + fTrace = trace; + fBookmarksFile = bookmarksFile; + fEventsFilterProvider = eventsFilterProvider; + } + + public ITmfTrace getTrace() { + return fTrace; + } + + public IFile getBookmarksFile() { + return fBookmarksFile; + } + + public ITmfEventsFilterProvider getEventsFilterProvider() { + return fEventsFilterProvider; + } + + @Override + public String toString() { + return "[TmfTraceOpenedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceParserUpdatedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceParserUpdatedSignal.java index 521574860d..05736c9fbf 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceParserUpdatedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/signal/TmfTraceParserUpdatedSignal.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.internal.tmf.ui.signal; - -import org.eclipse.core.resources.IResource; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; - -/** - * Signal that a trace parser was updated - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceParserUpdatedSignal extends TmfSignal { - - private final IResource fTraceResource; - - public TmfTraceParserUpdatedSignal(Object source, IResource traceResource) { - super(source); - fTraceResource = traceResource; - } - - public IResource getTraceResource() { - return fTraceResource; - } - - @Override - public String toString() { - return "[TmfTraceParserUpdatedSignal (" + fTraceResource.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.internal.tmf.ui.signal; + +import org.eclipse.core.resources.IResource; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; + +/** + * Signal that a trace parser was updated + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceParserUpdatedSignal extends TmfSignal { + + private final IResource fTraceResource; + + public TmfTraceParserUpdatedSignal(Object source, IResource traceResource) { + super(source); + fTraceResource = traceResource; + } + + public IResource getTraceResource() { + return fTraceResource; + } + + @Override + public String toString() { + return "[TmfTraceParserUpdatedSignal (" + fTraceResource.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/ITmfTraceEditor.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/ITmfTraceEditor.java index 7ab0675274..43359bf745 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/ITmfTraceEditor.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/ITmfTraceEditor.java @@ -1,39 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.editors; - -import org.eclipse.core.resources.IFile; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -/** - * The trace editor interface - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITmfTraceEditor { - - /** - * Get the trace to which this editor is assigned - * - * @return The trace - */ - public ITmfTrace getTrace(); - - /** - * Get the bookmark file associated to this trace - * - * @return The IFile object pointing to the bookmark file - */ - public IFile getBookmarksFile(); -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.editors; + +import org.eclipse.core.resources.IFile; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +/** + * The trace editor interface + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITmfTraceEditor { + + /** + * Get the trace to which this editor is assigned + * + * @return The trace + */ + public ITmfTrace getTrace(); + + /** + * Get the bookmark file associated to this trace + * + * @return The IFile object pointing to the bookmark file + */ + public IFile getBookmarksFile(); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java index e5bfbf3af3..f7fe0fef78 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.editors; - -import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager; -import org.eclipse.ui.part.EditorPart; - -/** - * The main editor abstract class for use in TMF. - * - * @version 1.0 - * @author Patrick Tasse - */ -public abstract class TmfEditor extends EditorPart implements ITmfComponent { - - private final String fName; - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Default constructor - */ - public TmfEditor() { - super(); - fName = "TmfEditor"; //$NON-NLS-1$ - TmfSignalManager.register(this); - } - - @Override - public void dispose() { - TmfSignalManager.deregister(this); - super.dispose(); - } - - // ------------------------------------------------------------------------ - // ITmfComponent - // ------------------------------------------------------------------------ - - @Override - public String getName() { - return fName; - } - - @Override - public void broadcast(TmfSignal signal) { - TmfSignalManager.dispatchSignal(signal); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.editors; + +import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager; +import org.eclipse.ui.part.EditorPart; + +/** + * The main editor abstract class for use in TMF. + * + * @version 1.0 + * @author Patrick Tasse + */ +public abstract class TmfEditor extends EditorPart implements ITmfComponent { + + private final String fName; + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Default constructor + */ + public TmfEditor() { + super(); + fName = "TmfEditor"; //$NON-NLS-1$ + TmfSignalManager.register(this); + } + + @Override + public void dispose() { + TmfSignalManager.deregister(this); + super.dispose(); + } + + // ------------------------------------------------------------------------ + // ITmfComponent + // ------------------------------------------------------------------------ + + @Override + public String getName() { + return fName; + } + + @Override + public void broadcast(TmfSignal signal) { + TmfSignalManager.dispatchSignal(signal); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditorInput.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditorInput.java index d16a26ce62..14667634c8 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditorInput.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditorInput.java @@ -1,140 +1,140 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.editors; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IPersistableElement; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; - -/** - * The input interface for TMF editors. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfEditorInput implements IEditorInput { - - private final IFile fFile; - private final ITmfTrace fTrace; - - /** - * Standard constructor - * - * @param file The IFile pointer - * @param trace Reference to the trace - */ - public TmfEditorInput(IFile file, ITmfTrace trace) { - fFile = file; - fTrace = trace; - } - - @Override - public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { - return null; - } - - @Override - public boolean exists() { - return fFile.exists(); - } - - @Override - public ImageDescriptor getImageDescriptor() { - IContentType contentType = IDE.getContentType(fFile); - return PlatformUI.getWorkbench().getEditorRegistry() - .getImageDescriptor(fFile.getName(), contentType); - } - - @Override - public String getName() { - return fTrace.getName(); - } - - @Override - public IPersistableElement getPersistable() { - return null; - } - - @Override - public String getToolTipText() { - return fFile.getFullPath().makeRelative().toString(); - } - - /** - * Get this editor input's file object - * - * @return The IFile - */ - public IFile getFile() { - return fFile; - } - - /** - * Get this editor input's trace - * - * @return The trace - */ - public ITmfTrace getTrace() { - return fTrace; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fFile == null) ? 0 : fFile.getLocation().hashCode()); - result = prime * result + ((fTrace == null) ? 0 : fTrace.getName().hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - TmfEditorInput other = (TmfEditorInput) obj; - if (fFile == null) { - if (other.fFile != null) { - return false; - } - } else if (!fFile.getLocation().equals(other.fFile.getLocation())) { - return false; - } - if (fTrace == null) { - if (other.fTrace != null) { - return false; - } - } else if (!fTrace.getName().equals(other.fTrace.getName())) { - return false; - } - return true; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.editors; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.content.IContentType; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IPersistableElement; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + +/** + * The input interface for TMF editors. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfEditorInput implements IEditorInput { + + private final IFile fFile; + private final ITmfTrace fTrace; + + /** + * Standard constructor + * + * @param file The IFile pointer + * @param trace Reference to the trace + */ + public TmfEditorInput(IFile file, ITmfTrace trace) { + fFile = file; + fTrace = trace; + } + + @Override + public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { + return null; + } + + @Override + public boolean exists() { + return fFile.exists(); + } + + @Override + public ImageDescriptor getImageDescriptor() { + IContentType contentType = IDE.getContentType(fFile); + return PlatformUI.getWorkbench().getEditorRegistry() + .getImageDescriptor(fFile.getName(), contentType); + } + + @Override + public String getName() { + return fTrace.getName(); + } + + @Override + public IPersistableElement getPersistable() { + return null; + } + + @Override + public String getToolTipText() { + return fFile.getFullPath().makeRelative().toString(); + } + + /** + * Get this editor input's file object + * + * @return The IFile + */ + public IFile getFile() { + return fFile; + } + + /** + * Get this editor input's trace + * + * @return The trace + */ + public ITmfTrace getTrace() { + return fTrace; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fFile == null) ? 0 : fFile.getLocation().hashCode()); + result = prime * result + ((fTrace == null) ? 0 : fTrace.getName().hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TmfEditorInput other = (TmfEditorInput) obj; + if (fFile == null) { + if (other.fFile != null) { + return false; + } + } else if (!fFile.getLocation().equals(other.fFile.getLocation())) { + return false; + } + if (fTrace == null) { + if (other.fTrace != null) { + return false; + } + } else if (!fTrace.getName().equals(other.fTrace.getName())) { + return false; + } + return true; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEventsEditor.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEventsEditor.java index c0567eab38..c62463ae1d 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEventsEditor.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEventsEditor.java @@ -1,559 +1,559 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.editors; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IMarkerDelta; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; -import org.eclipse.linuxtools.internal.tmf.ui.project.handlers.Messages; -import org.eclipse.linuxtools.tmf.core.TmfCommonConstants; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; -import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; -import org.eclipse.linuxtools.tmf.core.signal.TmfTraceSelectedSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; -import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; -import org.eclipse.linuxtools.tmf.ui.project.model.ITmfProjectModelElement; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfExperimentElement; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfNavigatorContentProvider; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectElement; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType; -import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceClosedSignal; -import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceOpenedSignal; -import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceParserUpdatedSignal; -import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IPropertyListener; -import org.eclipse.ui.IReusableEditor; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.ide.IGotoMarker; -import org.eclipse.ui.part.FileEditorInput; -import org.osgi.framework.Bundle; - -/** - * Editor for TMF events - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfEventsEditor extends TmfEditor implements ITmfTraceEditor, IReusableEditor, IPropertyListener, IResourceChangeListener { - - /** ID for this class */ - public static final String ID = "org.eclipse.linuxtools.tmf.ui.editors.events"; //$NON-NLS-1$ - - private TmfEventsTable fEventsTable; - private IFile fFile; - @SuppressWarnings("rawtypes") - private ITmfTrace fTrace; - private Composite fParent; - - @Override - public void doSave(final IProgressMonitor monitor) { - } - - @Override - public void doSaveAs() { - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void init(final IEditorSite site, IEditorInput input) throws PartInitException { - if (input instanceof TmfEditorInput) { - fFile = ((TmfEditorInput) input).getFile(); - fTrace = ((TmfEditorInput) input).getTrace(); - input = new FileEditorInput(fFile); - } else if (input instanceof IFileEditorInput) { - fFile = ((IFileEditorInput) input).getFile(); - if (fFile == null) - { - throw new PartInitException("Invalid IFileEditorInput: " + input); //$NON-NLS-1$ - } - try { - final String traceTypeId = fFile.getPersistentProperty(TmfCommonConstants.TRACETYPE); - if (traceTypeId == null) { - throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); - } - if (traceTypeId.equals(TmfExperiment.class.getCanonicalName())) { - // Special case: experiment bookmark resource - final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); - ncp.getChildren(fFile.getProject()); // force the model to be populated - final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); - if (project == null) { - throw new PartInitException(Messages.OpenExperimentHandler_NoTraceType); - } - for (final ITmfProjectModelElement projectElement : project.getExperimentsFolder().getChildren()) { - final String traceName = fFile.getParent().getName(); - if (projectElement.getName().equals(traceName)) { - final TmfExperimentElement experimentElement = (TmfExperimentElement) projectElement; - // Instantiate the experiment's traces - final List traceEntries = experimentElement.getTraces(); - final int nbTraces = traceEntries.size(); - int cacheSize = Integer.MAX_VALUE; - final ITmfTrace[] traces = new ITmfTrace[nbTraces]; - for (int i = 0; i < nbTraces; i++) { - final TmfTraceElement traceElement = traceEntries.get(i); - final ITmfTrace trace = traceElement.instantiateTrace(); - final ITmfEvent traceEvent = traceElement.instantiateEvent(); - if ((trace == null) || (traceEvent == null)) { - for (int j = 0; j < i; j++) { - traces[j].dispose(); - } - throw new PartInitException(Messages.OpenExperimentHandler_NoTraceType); - } - try { - trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); - } catch (final TmfTraceException e) { - } - cacheSize = Math.min(cacheSize, trace.getCacheSize()); - traces[i] = trace; - } - final TmfExperiment experiment = new TmfExperiment(ITmfEvent.class, experimentElement.getName(), traces, cacheSize) { - @Override - public void initTrace(IResource resource, String path, Class type) { - super.initTrace(resource, path, type); - getIndexer().buildIndex(getNbEvents(), TmfTimeRange.ETERNITY, false); - } - }; - experiment.setBookmarksFile(fFile); - fTrace = experiment; - experiment.initTrace(null, null, null); - break; - } - } - } else if (traceTypeId.equals(TmfTrace.class.getCanonicalName())) { - // Special case: trace bookmark resource - final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); - ncp.getChildren(fFile.getProject()); // force the model to be populated - final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); - for (final ITmfProjectModelElement projectElement : project.getTracesFolder().getChildren()) { - final String traceName = fFile.getParent().getName(); - if (projectElement.getName().equals(traceName)) { - final TmfTraceElement traceElement = (TmfTraceElement) projectElement; - // Instantiate the trace - final ITmfTrace trace = traceElement.instantiateTrace(); - final ITmfEvent traceEvent = traceElement.instantiateEvent(); - if ((trace == null) || (traceEvent == null)) { - throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); - } - try { - trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); - } catch (final TmfTraceException e) { - } - fTrace = trace; - break; - } - } - } else { - final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); - ncp.getChildren(fFile.getProject()); // force the model to be populated - final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); - for (final ITmfProjectModelElement projectElement : project.getTracesFolder().getChildren()) { - if (projectElement.getResource().equals(fFile)) { - final TmfTraceElement traceElement = (TmfTraceElement) projectElement; - // Instantiate the trace - final ITmfTrace trace = traceElement.instantiateTrace(); - final ITmfEvent traceEvent = traceElement.instantiateEvent(); - if ((trace == null) || (traceEvent == null)) { - throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); - } - try { - trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); - } catch (final TmfTraceException e) { - } - fTrace = trace; - break; - } - } - } - } catch (final InvalidRegistryObjectException e) { - Activator.getDefault().logError("Error initializing TmfEventsEditor", e); //$NON-NLS-1$ - } catch (final CoreException e) { - Activator.getDefault().logError("Error initializing TmfEventsEditor", e); //$NON-NLS-1$ - } - } - else { - throw new PartInitException("Invalid IEditorInput: " + input.getClass()); //$NON-NLS-1$ - } - if (fTrace == null) - { - throw new PartInitException("Invalid IEditorInput: " + fFile.getName()); //$NON-NLS-1$ - } - super.setSite(site); - super.setInput(input); - } - - @Override - public boolean isDirty() { - return false; - } - - @Override - public boolean isSaveAsAllowed() { - return false; - } - - @Override - public void setInput(final IEditorInput input) { - super.setInput(input); - firePropertyChange(IEditorPart.PROP_INPUT); - } - - @Override - public void propertyChanged(final Object source, final int propId) { - if (propId == IEditorPart.PROP_INPUT) { - broadcast(new TmfTraceClosedSignal(this, fTrace)); - fFile = ((TmfEditorInput) getEditorInput()).getFile(); - fTrace = ((TmfEditorInput) getEditorInput()).getTrace(); - super.setInput(new FileEditorInput(fFile)); - fEventsTable.dispose(); - if (fTrace != null) { - fEventsTable = createEventsTable(fParent, fTrace.getCacheSize()); - fEventsTable.setTrace(fTrace, true); - fEventsTable.refreshBookmarks(fFile); - broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); - } else { - fEventsTable = new TmfEventsTable(fParent, 0); - } - fParent.layout(); - } - } - - @Override - public void createPartControl(final Composite parent) { - fParent = parent; - if (fTrace != null) { - setPartName(fTrace.getName()); - fEventsTable = createEventsTable(parent, fTrace.getCacheSize()); - fEventsTable.setTrace(fTrace, true); - fEventsTable.refreshBookmarks(fFile); - broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); - } else { - setPartName(getEditorInput().getName()); - fEventsTable = new TmfEventsTable(parent, 0); - } - addPropertyListener(this); - ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); - } - - @Override - public void dispose() { - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - removePropertyListener(this); - if (fTrace != null) { - broadcast(new TmfTraceClosedSignal(this, fTrace)); - } - if (fEventsTable != null) { - fEventsTable.dispose(); - } - super.dispose(); - } - - protected TmfEventsTable createEventsTable(final Composite parent, final int cacheSize) { - TmfEventsTable eventsTable = getEventsTable(parent, cacheSize); - if (eventsTable == null) { - eventsTable = new TmfEventsTable(parent, cacheSize); - } - return eventsTable; - } - - private TmfEventsTable getEventsTable(final Composite parent, final int cacheSize) { - if (fTrace instanceof TmfExperiment) { - return getExperimentEventsTable((TmfExperiment) fTrace, parent, cacheSize); - } - TmfEventsTable eventsTable = null; - try { - if (fTrace.getResource() == null) { - return null; - } - final String traceType = fTrace.getResource().getPersistentProperty(TmfCommonConstants.TRACETYPE); - if (traceType == null) { - return null; - } - if (traceType.startsWith(CustomTxtTrace.class.getCanonicalName())) { - return new CustomEventsTable(((CustomTxtTrace) fTrace).getDefinition(), parent, cacheSize); - } - if (traceType.startsWith(CustomXmlTrace.class.getCanonicalName())) { - return new CustomEventsTable(((CustomXmlTrace) fTrace).getDefinition(), parent, cacheSize); - } - for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { - if (ce.getAttribute(TmfTraceType.ID_ATTR).equals(traceType)) { - final IConfigurationElement[] eventsTableTypeCE = ce.getChildren(TmfTraceType.EVENTS_TABLE_TYPE_ELEM); - if (eventsTableTypeCE.length != 1) { - break; - } - final String eventsTableType = eventsTableTypeCE[0].getAttribute(TmfTraceType.CLASS_ATTR); - if ((eventsTableType == null) || (eventsTableType.length() == 0)) { - break; - } - final Bundle bundle = Platform.getBundle(ce.getContributor().getName()); - final Class c = bundle.loadClass(eventsTableType); - final Class[] constructorArgs = new Class[] { Composite.class, int.class }; - final Constructor constructor = c.getConstructor(constructorArgs); - final Object[] args = new Object[] { parent, cacheSize }; - eventsTable = (TmfEventsTable) constructor.newInstance(args); - break; - } - } - } catch (final InvalidRegistryObjectException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final CoreException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final ClassNotFoundException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final SecurityException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final NoSuchMethodException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final IllegalArgumentException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final InstantiationException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final IllegalAccessException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } catch (final InvocationTargetException e) { - Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ - } - return eventsTable; - } - - /** - * Get the events table for an experiment. If all traces in the experiment - * are of the same type, use the extension point specified event table - * - * @param experiment - * the experiment - * @param parent - * the parent Composite - * @param cacheSize - * the event table cache size - * @return an events table of the appropriate type - */ - private static TmfEventsTable getExperimentEventsTable( - final TmfExperiment experiment, final Composite parent, - final int cacheSize) { - TmfEventsTable eventsTable = null; - String commonTraceType = null; - try { - for (final ITmfTrace trace : experiment.getTraces()) { - final IResource resource = trace.getResource(); - if (resource == null) { - return null; - } - final String traceType = resource.getPersistentProperty(TmfCommonConstants.TRACETYPE); - if ((commonTraceType != null) && !commonTraceType.equals(traceType)) { - return null; - } - commonTraceType = traceType; - } - if (commonTraceType == null) { - return null; - } - if (commonTraceType.startsWith(CustomTxtTrace.class.getCanonicalName())) { - return new CustomEventsTable(((CustomTxtTrace) experiment.getTraces()[0]).getDefinition(), parent, cacheSize); - } - if (commonTraceType.startsWith(CustomXmlTrace.class.getCanonicalName())) { - return new CustomEventsTable(((CustomXmlTrace) experiment.getTraces()[0]).getDefinition(), parent, cacheSize); - } - for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { - if (ce.getAttribute(TmfTraceType.ID_ATTR).equals(commonTraceType)) { - final IConfigurationElement[] eventsTableTypeCE = ce.getChildren(TmfTraceType.EVENTS_TABLE_TYPE_ELEM); - if (eventsTableTypeCE.length != 1) { - break; - } - final String eventsTableType = eventsTableTypeCE[0].getAttribute(TmfTraceType.CLASS_ATTR); - if ((eventsTableType == null) || (eventsTableType.length() == 0)) { - break; - } - final Bundle bundle = Platform.getBundle(ce.getContributor().getName()); - final Class c = bundle.loadClass(eventsTableType); - final Class[] constructorArgs = new Class[] { Composite.class, int.class }; - final Constructor constructor = c.getConstructor(constructorArgs); - final Object[] args = new Object[] { parent, cacheSize }; - eventsTable = (TmfEventsTable) constructor.newInstance(args); - break; - } - } - } catch (final CoreException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final InvalidRegistryObjectException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final SecurityException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final IllegalArgumentException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final ClassNotFoundException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final NoSuchMethodException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final InstantiationException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final IllegalAccessException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } catch (final InvocationTargetException e) { - Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ - } - return eventsTable; - } - - @Override - public ITmfTrace getTrace() { - return fTrace; - } - - @Override - public IFile getBookmarksFile() { - return fFile; - } - - @Override - public void setFocus() { - fEventsTable.setFocus(); - if (fTrace != null) { - broadcast(new TmfTraceSelectedSignal(this, fTrace)); - } - } - - @Override - @SuppressWarnings("rawtypes") - public Object getAdapter(final Class adapter) { - if (IGotoMarker.class.equals(adapter)) { - return fEventsTable; - } - return super.getAdapter(adapter); - } - - @Override - public void resourceChanged(final IResourceChangeEvent event) { - for (final IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { - if (delta.getResource().equals(fFile)) { - if (delta.getKind() == IResourceDelta.REMOVED) { - final IMarker bookmark = delta.getMarker(); - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - fEventsTable.removeBookmark(bookmark); - } - }); - } else if (delta.getKind() == IResourceDelta.CHANGED) { - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - fEventsTable.getTable().refresh(); - } - }); - } - } - } - } - - // ------------------------------------------------------------------------ - // Global commands - // ------------------------------------------------------------------------ - - /** - * Add a bookmark - */ - public void addBookmark() { - fEventsTable.addBookmark(fFile); - } - - - // ------------------------------------------------------------------------ - // Signal handlers - // ------------------------------------------------------------------------ - - /** - * Handler for the Trace Parser Updated signal - * - * @param signal The incoming signal - */ - @SuppressWarnings("unchecked") - @TmfSignalHandler - public void traceParserUpdated(final TmfTraceParserUpdatedSignal signal) { - if (signal.getTraceResource().equals(fFile)) { - broadcast(new TmfTraceClosedSignal(this, fTrace)); - try { - fTrace.getName(); - fTrace = null; - final String traceTypeId = fFile.getPersistentProperty(TmfCommonConstants.TRACETYPE); - if (traceTypeId != null) { - for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { - if (traceTypeId.equals(ce.getAttribute(TmfTraceType.ID_ATTR))) { - fTrace = (ITmfTrace) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR); - final ITmfEvent event = (TmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); - final String path = fFile.getLocationURI().getPath(); - fTrace.initTrace(null, path, event.getClass()); - break; - } - } - } - } catch (final InvalidRegistryObjectException e) { - Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ - } catch (final TmfTraceException e) { - Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ - } catch (final CoreException e) { - Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ - } - fEventsTable.dispose(); - if (fTrace != null) { - fEventsTable = createEventsTable(fParent, fTrace.getCacheSize()); - fEventsTable.setTrace(fTrace, true); - broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); - } else { - fEventsTable = new TmfEventsTable(fParent, 0); - } - fParent.layout(); - } - } - - /** - * Handler for the Trace Selected signal - * - * @param signal The incoming signal - */ - @TmfSignalHandler - public void traceSelected(final TmfTraceSelectedSignal signal) { - if ((signal.getSource() != this) && signal.getTrace().equals(fTrace)) { - getSite().getPage().bringToTop(this); - } - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.editors; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IMarkerDelta; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.InvalidRegistryObjectException; +import org.eclipse.core.runtime.Platform; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomEventsTable; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace; +import org.eclipse.linuxtools.internal.tmf.ui.project.handlers.Messages; +import org.eclipse.linuxtools.tmf.core.TmfCommonConstants; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; +import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; +import org.eclipse.linuxtools.tmf.core.signal.TmfTraceSelectedSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; +import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; +import org.eclipse.linuxtools.tmf.ui.project.model.ITmfProjectModelElement; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfExperimentElement; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfNavigatorContentProvider; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectElement; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType; +import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceClosedSignal; +import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceOpenedSignal; +import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceParserUpdatedSignal; +import org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IPropertyListener; +import org.eclipse.ui.IReusableEditor; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.ide.IGotoMarker; +import org.eclipse.ui.part.FileEditorInput; +import org.osgi.framework.Bundle; + +/** + * Editor for TMF events + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfEventsEditor extends TmfEditor implements ITmfTraceEditor, IReusableEditor, IPropertyListener, IResourceChangeListener { + + /** ID for this class */ + public static final String ID = "org.eclipse.linuxtools.tmf.ui.editors.events"; //$NON-NLS-1$ + + private TmfEventsTable fEventsTable; + private IFile fFile; + @SuppressWarnings("rawtypes") + private ITmfTrace fTrace; + private Composite fParent; + + @Override + public void doSave(final IProgressMonitor monitor) { + } + + @Override + public void doSaveAs() { + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void init(final IEditorSite site, IEditorInput input) throws PartInitException { + if (input instanceof TmfEditorInput) { + fFile = ((TmfEditorInput) input).getFile(); + fTrace = ((TmfEditorInput) input).getTrace(); + input = new FileEditorInput(fFile); + } else if (input instanceof IFileEditorInput) { + fFile = ((IFileEditorInput) input).getFile(); + if (fFile == null) + { + throw new PartInitException("Invalid IFileEditorInput: " + input); //$NON-NLS-1$ + } + try { + final String traceTypeId = fFile.getPersistentProperty(TmfCommonConstants.TRACETYPE); + if (traceTypeId == null) { + throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); + } + if (traceTypeId.equals(TmfExperiment.class.getCanonicalName())) { + // Special case: experiment bookmark resource + final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); + ncp.getChildren(fFile.getProject()); // force the model to be populated + final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); + if (project == null) { + throw new PartInitException(Messages.OpenExperimentHandler_NoTraceType); + } + for (final ITmfProjectModelElement projectElement : project.getExperimentsFolder().getChildren()) { + final String traceName = fFile.getParent().getName(); + if (projectElement.getName().equals(traceName)) { + final TmfExperimentElement experimentElement = (TmfExperimentElement) projectElement; + // Instantiate the experiment's traces + final List traceEntries = experimentElement.getTraces(); + final int nbTraces = traceEntries.size(); + int cacheSize = Integer.MAX_VALUE; + final ITmfTrace[] traces = new ITmfTrace[nbTraces]; + for (int i = 0; i < nbTraces; i++) { + final TmfTraceElement traceElement = traceEntries.get(i); + final ITmfTrace trace = traceElement.instantiateTrace(); + final ITmfEvent traceEvent = traceElement.instantiateEvent(); + if ((trace == null) || (traceEvent == null)) { + for (int j = 0; j < i; j++) { + traces[j].dispose(); + } + throw new PartInitException(Messages.OpenExperimentHandler_NoTraceType); + } + try { + trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); + } catch (final TmfTraceException e) { + } + cacheSize = Math.min(cacheSize, trace.getCacheSize()); + traces[i] = trace; + } + final TmfExperiment experiment = new TmfExperiment(ITmfEvent.class, experimentElement.getName(), traces, cacheSize) { + @Override + public void initTrace(IResource resource, String path, Class type) { + super.initTrace(resource, path, type); + getIndexer().buildIndex(getNbEvents(), TmfTimeRange.ETERNITY, false); + } + }; + experiment.setBookmarksFile(fFile); + fTrace = experiment; + experiment.initTrace(null, null, null); + break; + } + } + } else if (traceTypeId.equals(TmfTrace.class.getCanonicalName())) { + // Special case: trace bookmark resource + final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); + ncp.getChildren(fFile.getProject()); // force the model to be populated + final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); + for (final ITmfProjectModelElement projectElement : project.getTracesFolder().getChildren()) { + final String traceName = fFile.getParent().getName(); + if (projectElement.getName().equals(traceName)) { + final TmfTraceElement traceElement = (TmfTraceElement) projectElement; + // Instantiate the trace + final ITmfTrace trace = traceElement.instantiateTrace(); + final ITmfEvent traceEvent = traceElement.instantiateEvent(); + if ((trace == null) || (traceEvent == null)) { + throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); + } + try { + trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); + } catch (final TmfTraceException e) { + } + fTrace = trace; + break; + } + } + } else { + final TmfNavigatorContentProvider ncp = new TmfNavigatorContentProvider(); + ncp.getChildren(fFile.getProject()); // force the model to be populated + final TmfProjectElement project = TmfProjectRegistry.getProject(fFile.getProject()); + for (final ITmfProjectModelElement projectElement : project.getTracesFolder().getChildren()) { + if (projectElement.getResource().equals(fFile)) { + final TmfTraceElement traceElement = (TmfTraceElement) projectElement; + // Instantiate the trace + final ITmfTrace trace = traceElement.instantiateTrace(); + final ITmfEvent traceEvent = traceElement.instantiateEvent(); + if ((trace == null) || (traceEvent == null)) { + throw new PartInitException(Messages.OpenTraceHandler_NoTraceType); + } + try { + trace.initTrace(traceElement.getResource(), traceElement.getLocation().getPath(), traceEvent.getClass()); + } catch (final TmfTraceException e) { + } + fTrace = trace; + break; + } + } + } + } catch (final InvalidRegistryObjectException e) { + Activator.getDefault().logError("Error initializing TmfEventsEditor", e); //$NON-NLS-1$ + } catch (final CoreException e) { + Activator.getDefault().logError("Error initializing TmfEventsEditor", e); //$NON-NLS-1$ + } + } + else { + throw new PartInitException("Invalid IEditorInput: " + input.getClass()); //$NON-NLS-1$ + } + if (fTrace == null) + { + throw new PartInitException("Invalid IEditorInput: " + fFile.getName()); //$NON-NLS-1$ + } + super.setSite(site); + super.setInput(input); + } + + @Override + public boolean isDirty() { + return false; + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } + + @Override + public void setInput(final IEditorInput input) { + super.setInput(input); + firePropertyChange(IEditorPart.PROP_INPUT); + } + + @Override + public void propertyChanged(final Object source, final int propId) { + if (propId == IEditorPart.PROP_INPUT) { + broadcast(new TmfTraceClosedSignal(this, fTrace)); + fFile = ((TmfEditorInput) getEditorInput()).getFile(); + fTrace = ((TmfEditorInput) getEditorInput()).getTrace(); + super.setInput(new FileEditorInput(fFile)); + fEventsTable.dispose(); + if (fTrace != null) { + fEventsTable = createEventsTable(fParent, fTrace.getCacheSize()); + fEventsTable.setTrace(fTrace, true); + fEventsTable.refreshBookmarks(fFile); + broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); + } else { + fEventsTable = new TmfEventsTable(fParent, 0); + } + fParent.layout(); + } + } + + @Override + public void createPartControl(final Composite parent) { + fParent = parent; + if (fTrace != null) { + setPartName(fTrace.getName()); + fEventsTable = createEventsTable(parent, fTrace.getCacheSize()); + fEventsTable.setTrace(fTrace, true); + fEventsTable.refreshBookmarks(fFile); + broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); + } else { + setPartName(getEditorInput().getName()); + fEventsTable = new TmfEventsTable(parent, 0); + } + addPropertyListener(this); + ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); + } + + @Override + public void dispose() { + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + removePropertyListener(this); + if (fTrace != null) { + broadcast(new TmfTraceClosedSignal(this, fTrace)); + } + if (fEventsTable != null) { + fEventsTable.dispose(); + } + super.dispose(); + } + + protected TmfEventsTable createEventsTable(final Composite parent, final int cacheSize) { + TmfEventsTable eventsTable = getEventsTable(parent, cacheSize); + if (eventsTable == null) { + eventsTable = new TmfEventsTable(parent, cacheSize); + } + return eventsTable; + } + + private TmfEventsTable getEventsTable(final Composite parent, final int cacheSize) { + if (fTrace instanceof TmfExperiment) { + return getExperimentEventsTable((TmfExperiment) fTrace, parent, cacheSize); + } + TmfEventsTable eventsTable = null; + try { + if (fTrace.getResource() == null) { + return null; + } + final String traceType = fTrace.getResource().getPersistentProperty(TmfCommonConstants.TRACETYPE); + if (traceType == null) { + return null; + } + if (traceType.startsWith(CustomTxtTrace.class.getCanonicalName())) { + return new CustomEventsTable(((CustomTxtTrace) fTrace).getDefinition(), parent, cacheSize); + } + if (traceType.startsWith(CustomXmlTrace.class.getCanonicalName())) { + return new CustomEventsTable(((CustomXmlTrace) fTrace).getDefinition(), parent, cacheSize); + } + for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { + if (ce.getAttribute(TmfTraceType.ID_ATTR).equals(traceType)) { + final IConfigurationElement[] eventsTableTypeCE = ce.getChildren(TmfTraceType.EVENTS_TABLE_TYPE_ELEM); + if (eventsTableTypeCE.length != 1) { + break; + } + final String eventsTableType = eventsTableTypeCE[0].getAttribute(TmfTraceType.CLASS_ATTR); + if ((eventsTableType == null) || (eventsTableType.length() == 0)) { + break; + } + final Bundle bundle = Platform.getBundle(ce.getContributor().getName()); + final Class c = bundle.loadClass(eventsTableType); + final Class[] constructorArgs = new Class[] { Composite.class, int.class }; + final Constructor constructor = c.getConstructor(constructorArgs); + final Object[] args = new Object[] { parent, cacheSize }; + eventsTable = (TmfEventsTable) constructor.newInstance(args); + break; + } + } + } catch (final InvalidRegistryObjectException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final CoreException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final ClassNotFoundException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final SecurityException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final NoSuchMethodException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final IllegalArgumentException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final InstantiationException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final IllegalAccessException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } catch (final InvocationTargetException e) { + Activator.getDefault().logError("Error getting TmfEventsTable", e); //$NON-NLS-1$ + } + return eventsTable; + } + + /** + * Get the events table for an experiment. If all traces in the experiment + * are of the same type, use the extension point specified event table + * + * @param experiment + * the experiment + * @param parent + * the parent Composite + * @param cacheSize + * the event table cache size + * @return an events table of the appropriate type + */ + private static TmfEventsTable getExperimentEventsTable( + final TmfExperiment experiment, final Composite parent, + final int cacheSize) { + TmfEventsTable eventsTable = null; + String commonTraceType = null; + try { + for (final ITmfTrace trace : experiment.getTraces()) { + final IResource resource = trace.getResource(); + if (resource == null) { + return null; + } + final String traceType = resource.getPersistentProperty(TmfCommonConstants.TRACETYPE); + if ((commonTraceType != null) && !commonTraceType.equals(traceType)) { + return null; + } + commonTraceType = traceType; + } + if (commonTraceType == null) { + return null; + } + if (commonTraceType.startsWith(CustomTxtTrace.class.getCanonicalName())) { + return new CustomEventsTable(((CustomTxtTrace) experiment.getTraces()[0]).getDefinition(), parent, cacheSize); + } + if (commonTraceType.startsWith(CustomXmlTrace.class.getCanonicalName())) { + return new CustomEventsTable(((CustomXmlTrace) experiment.getTraces()[0]).getDefinition(), parent, cacheSize); + } + for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { + if (ce.getAttribute(TmfTraceType.ID_ATTR).equals(commonTraceType)) { + final IConfigurationElement[] eventsTableTypeCE = ce.getChildren(TmfTraceType.EVENTS_TABLE_TYPE_ELEM); + if (eventsTableTypeCE.length != 1) { + break; + } + final String eventsTableType = eventsTableTypeCE[0].getAttribute(TmfTraceType.CLASS_ATTR); + if ((eventsTableType == null) || (eventsTableType.length() == 0)) { + break; + } + final Bundle bundle = Platform.getBundle(ce.getContributor().getName()); + final Class c = bundle.loadClass(eventsTableType); + final Class[] constructorArgs = new Class[] { Composite.class, int.class }; + final Constructor constructor = c.getConstructor(constructorArgs); + final Object[] args = new Object[] { parent, cacheSize }; + eventsTable = (TmfEventsTable) constructor.newInstance(args); + break; + } + } + } catch (final CoreException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final InvalidRegistryObjectException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final SecurityException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final IllegalArgumentException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final ClassNotFoundException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final NoSuchMethodException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final InstantiationException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final IllegalAccessException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } catch (final InvocationTargetException e) { + Activator.getDefault().logError("Error getting TmfEventsTable for experiment", e); //$NON-NLS-1$ + } + return eventsTable; + } + + @Override + public ITmfTrace getTrace() { + return fTrace; + } + + @Override + public IFile getBookmarksFile() { + return fFile; + } + + @Override + public void setFocus() { + fEventsTable.setFocus(); + if (fTrace != null) { + broadcast(new TmfTraceSelectedSignal(this, fTrace)); + } + } + + @Override + @SuppressWarnings("rawtypes") + public Object getAdapter(final Class adapter) { + if (IGotoMarker.class.equals(adapter)) { + return fEventsTable; + } + return super.getAdapter(adapter); + } + + @Override + public void resourceChanged(final IResourceChangeEvent event) { + for (final IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { + if (delta.getResource().equals(fFile)) { + if (delta.getKind() == IResourceDelta.REMOVED) { + final IMarker bookmark = delta.getMarker(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + fEventsTable.removeBookmark(bookmark); + } + }); + } else if (delta.getKind() == IResourceDelta.CHANGED) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + fEventsTable.getTable().refresh(); + } + }); + } + } + } + } + + // ------------------------------------------------------------------------ + // Global commands + // ------------------------------------------------------------------------ + + /** + * Add a bookmark + */ + public void addBookmark() { + fEventsTable.addBookmark(fFile); + } + + + // ------------------------------------------------------------------------ + // Signal handlers + // ------------------------------------------------------------------------ + + /** + * Handler for the Trace Parser Updated signal + * + * @param signal The incoming signal + */ + @SuppressWarnings("unchecked") + @TmfSignalHandler + public void traceParserUpdated(final TmfTraceParserUpdatedSignal signal) { + if (signal.getTraceResource().equals(fFile)) { + broadcast(new TmfTraceClosedSignal(this, fTrace)); + try { + fTrace.getName(); + fTrace = null; + final String traceTypeId = fFile.getPersistentProperty(TmfCommonConstants.TRACETYPE); + if (traceTypeId != null) { + for (final IConfigurationElement ce : TmfTraceType.getTypeElements()) { + if (traceTypeId.equals(ce.getAttribute(TmfTraceType.ID_ATTR))) { + fTrace = (ITmfTrace) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR); + final ITmfEvent event = (TmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); + final String path = fFile.getLocationURI().getPath(); + fTrace.initTrace(null, path, event.getClass()); + break; + } + } + } + } catch (final InvalidRegistryObjectException e) { + Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ + } catch (final TmfTraceException e) { + Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ + } catch (final CoreException e) { + Activator.getDefault().logError("Error handling signal TmfTraceParserUpdatedSignal", e); //$NON-NLS-1$ + } + fEventsTable.dispose(); + if (fTrace != null) { + fEventsTable = createEventsTable(fParent, fTrace.getCacheSize()); + fEventsTable.setTrace(fTrace, true); + broadcast(new TmfTraceOpenedSignal(this, fTrace, fFile, fEventsTable)); + } else { + fEventsTable = new TmfEventsTable(fParent, 0); + } + fParent.layout(); + } + } + + /** + * Handler for the Trace Selected signal + * + * @param signal The incoming signal + */ + @TmfSignalHandler + public void traceSelected(final TmfTraceSelectedSignal signal) { + if ((signal.getSource() != this) && signal.getTrace().equals(fTrace)) { + getSite().getPage().bringToTop(this); + } + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java index 81c914e1ec..264f1f032a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java @@ -1,62 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.editors; - -import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager; -import org.eclipse.ui.part.MultiPageEditorPart; - -/** - * Multi-page editor part abstract class for use in TMF. - * - * @version 1.0 - * @author Patrick Tasse - */ -public abstract class TmfMultiPageEditorPart extends MultiPageEditorPart implements ITmfComponent { - - private final String fName; - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Default constructor - */ - public TmfMultiPageEditorPart() { - super(); - fName = "TmfMultiPageEditorPart"; //$NON-NLS-1$ - TmfSignalManager.register(this); - } - - @Override - public void dispose() { - TmfSignalManager.deregister(this); - super.dispose(); - } - - // ------------------------------------------------------------------------ - // ITmfComponent - // ------------------------------------------------------------------------ - - @Override - public String getName() { - return fName; - } - - @Override - public void broadcast(TmfSignal signal) { - TmfSignalManager.dispatchSignal(signal); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.editors; + +import org.eclipse.linuxtools.tmf.core.component.ITmfComponent; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager; +import org.eclipse.ui.part.MultiPageEditorPart; + +/** + * Multi-page editor part abstract class for use in TMF. + * + * @version 1.0 + * @author Patrick Tasse + */ +public abstract class TmfMultiPageEditorPart extends MultiPageEditorPart implements ITmfComponent { + + private final String fName; + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Default constructor + */ + public TmfMultiPageEditorPart() { + super(); + fName = "TmfMultiPageEditorPart"; //$NON-NLS-1$ + TmfSignalManager.register(this); + } + + @Override + public void dispose() { + TmfSignalManager.deregister(this); + super.dispose(); + } + + // ------------------------------------------------------------------------ + // ITmfComponent + // ------------------------------------------------------------------------ + + @Override + public String getName() { + return fName; + } + + @Override + public void broadcast(TmfSignal signal) { + TmfSignalManager.dispatchSignal(signal); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/project/model/TmfExperimentFolder.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/project/model/TmfExperimentFolder.java index 52a83b54ff..50caab24db 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/project/model/TmfExperimentFolder.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/project/model/TmfExperimentFolder.java @@ -102,33 +102,73 @@ public class TmfExperimentFolder extends TmfProjectModelElement implements IProp } // ------------------------------------------------------------------------ - // IPropertySource2 // ------------------------------------------------------------------------ + // IPropertySource2 + // ------------------------------------------------------------------------ /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource#getEditableValue() - */ @Override public Object getEditableValue() { return null; } + */ + @Override + public Object getEditableValue() { + return null; + } /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyDescriptors() - */ @Override public IPropertyDescriptor[] getPropertyDescriptors() { return (sfDescriptors != null) ? Arrays.copyOf(sfDescriptors, sfDescriptors.length) : null; } + */ + @Override + public IPropertyDescriptor[] getPropertyDescriptors() { + return (sfDescriptors != null) ? Arrays.copyOf(sfDescriptors, sfDescriptors.length) : null; + } + /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java.lang.Object) - */ @Override public Object getPropertyValue(Object id) { if (sfName.equals(id)) return getName(); if (sfPath.equals(id)) return getPath().toString(); if (sfLocation.equals(id)) return getLocation().toString(); return null; } /* + */ + @Override + public Object getPropertyValue(Object id) { + + if (sfName.equals(id)) + return getName(); + + if (sfPath.equals(id)) + return getPath().toString(); + + if (sfLocation.equals(id)) + return getLocation().toString(); + + return null; + } + /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource#resetPropertyValue(java.lang.Object) - */ @Override public void resetPropertyValue(Object id) { } + */ + @Override + public void resetPropertyValue(Object id) { + } /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource#setPropertyValue(java.lang.Object, java.lang.Object) - */ @Override public void setPropertyValue(Object id, Object value) { } + */ + @Override + public void setPropertyValue(Object id, Object value) { + } /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource2#isPropertyResettable(java.lang.Object) - */ @Override public boolean isPropertyResettable(Object id) { return false; } + */ + @Override + public boolean isPropertyResettable(Object id) { + return false; + } /* * (non-Javadoc) * @see org.eclipse.ui.views.properties.IPropertySource2#isPropertySet(java.lang.Object) - */ @Override public boolean isPropertySet(Object id) { return false; } + */ + @Override + public boolean isPropertySet(Object id) { + return false; + } + +} -} \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceClosedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceClosedSignal.java index 0214cf307d..9b744b8495 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceClosedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceClosedSignal.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.signal; - -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -/** - * Signal indicating a trace is now closed - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceClosedSignal extends TmfSignal { - - private final ITmfTrace fTrace; - - /** - * Constructor for a new signal - * - * @param source - * The object sending this signal - * @param trace - * The trace being closed - */ - public TmfTraceClosedSignal(Object source, ITmfTrace trace) { - super(source); - fTrace = trace; - } - - /** - * Get a reference to the trace being closed - * - * @return The trace object - */ - public ITmfTrace getTrace() { - return fTrace; - } - - @Override - public String toString() { - return "[TmfTraceClosedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.signal; + +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +/** + * Signal indicating a trace is now closed + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceClosedSignal extends TmfSignal { + + private final ITmfTrace fTrace; + + /** + * Constructor for a new signal + * + * @param source + * The object sending this signal + * @param trace + * The trace being closed + */ + public TmfTraceClosedSignal(Object source, ITmfTrace trace) { + super(source); + fTrace = trace; + } + + /** + * Get a reference to the trace being closed + * + * @return The trace object + */ + public ITmfTrace getTrace() { + return fTrace; + } + + @Override + public String toString() { + return "[TmfTraceClosedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceOpenedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceOpenedSignal.java index 5a3d6182d9..0323c46e65 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceOpenedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceOpenedSignal.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.signal; - -import org.eclipse.core.resources.IFile; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; - -/** - * Signal indicating a trace has been opened. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceOpenedSignal extends TmfSignal { - - private final ITmfTrace fTrace; - private final IFile fBookmarksFile; - private final ITmfEventsFilterProvider fEventsFilterProvider; - - /** - * Constructor for a new signal. - * - * @param source - * The object sending this signal - * @param trace - * The trace that has been opened - * @param bookmarksFile - * Pointer to the bookmark file - * @param eventsFilterProvider - * Provider for the event filter in use - */ - public TmfTraceOpenedSignal(Object source, ITmfTrace trace, - IFile bookmarksFile, ITmfEventsFilterProvider eventsFilterProvider) { - super(source); - fTrace = trace; - fBookmarksFile = bookmarksFile; - fEventsFilterProvider = eventsFilterProvider; - } - - /** - * Get the trace object concerning this signal - * - * @return The trace - */ - public ITmfTrace getTrace() { - return fTrace; - } - - /** - * Get a pointer to the bookmark file of this trace - * - * @return The IFile object - */ - public IFile getBookmarksFile() { - return fBookmarksFile; - } - - /** - * Get the events filter provider of this trace - * - * @return The EventsFilterProvider - */ - public ITmfEventsFilterProvider getEventsFilterProvider() { - return fEventsFilterProvider; - } - - @Override - public String toString() { - return "[TmfTraceOpenedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.signal; + +import org.eclipse.core.resources.IFile; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; + +/** + * Signal indicating a trace has been opened. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceOpenedSignal extends TmfSignal { + + private final ITmfTrace fTrace; + private final IFile fBookmarksFile; + private final ITmfEventsFilterProvider fEventsFilterProvider; + + /** + * Constructor for a new signal. + * + * @param source + * The object sending this signal + * @param trace + * The trace that has been opened + * @param bookmarksFile + * Pointer to the bookmark file + * @param eventsFilterProvider + * Provider for the event filter in use + */ + public TmfTraceOpenedSignal(Object source, ITmfTrace trace, + IFile bookmarksFile, ITmfEventsFilterProvider eventsFilterProvider) { + super(source); + fTrace = trace; + fBookmarksFile = bookmarksFile; + fEventsFilterProvider = eventsFilterProvider; + } + + /** + * Get the trace object concerning this signal + * + * @return The trace + */ + public ITmfTrace getTrace() { + return fTrace; + } + + /** + * Get a pointer to the bookmark file of this trace + * + * @return The IFile object + */ + public IFile getBookmarksFile() { + return fBookmarksFile; + } + + /** + * Get the events filter provider of this trace + * + * @return The EventsFilterProvider + */ + public ITmfEventsFilterProvider getEventsFilterProvider() { + return fEventsFilterProvider; + } + + @Override + public String toString() { + return "[TmfTraceOpenedSignal (" + fTrace.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceParserUpdatedSignal.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceParserUpdatedSignal.java index f0bb232a97..bec4fb7617 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceParserUpdatedSignal.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/signal/TmfTraceParserUpdatedSignal.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.signal; - -import org.eclipse.core.resources.IResource; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; - -/** - * Signal indicating the trace parser has finished reading a chunk, so the - * parsing has been updated. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfTraceParserUpdatedSignal extends TmfSignal { - - private final IResource fTraceResource; - - /** - * Constructor for the signal. - * - * @param source The object sending this signal - * @param traceResource The trace resource concerning this signal - */ - public TmfTraceParserUpdatedSignal(Object source, IResource traceResource) { - super(source); - fTraceResource = traceResource; - } - - /** - * Get the trace resource object of this signal. - * - * @return The trace resource. - */ - public IResource getTraceResource() { - return fTraceResource; - } - - @Override - public String toString() { - return "[TmfTraceParserUpdatedSignal (" + fTraceResource.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.signal; + +import org.eclipse.core.resources.IResource; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignal; + +/** + * Signal indicating the trace parser has finished reading a chunk, so the + * parsing has been updated. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfTraceParserUpdatedSignal extends TmfSignal { + + private final IResource fTraceResource; + + /** + * Constructor for the signal. + * + * @param source The object sending this signal + * @param traceResource The trace resource concerning this signal + */ + public TmfTraceParserUpdatedSignal(Object source, IResource traceResource) { + super(source); + fTraceResource = traceResource; + } + + /** + * Get the trace resource object of this signal. + * + * @return The trace resource. + */ + public IResource getTraceResource() { + return fTraceResource; + } + + @Override + public String toString() { + return "[TmfTraceParserUpdatedSignal (" + fTraceResource.getName() + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterListener.java index 82046ce4e3..9b5322d8bc 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterListener.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.viewers.events; - -import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; - -/** - * A filter/search event listener - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITmfEventsFilterListener { - - /** - * Notify this listener that a filter has been applied. - * - * @param filter - * The filter that was applied - * @param trace - * The trace on which this filter is applied - */ - public void filterApplied(ITmfFilter filter, ITmfTrace trace); - - /** - * Notify this listener that a new search has been run. - * - * @param filter - * The filter that was applied - * @param trace - * The trace on which this filter is applied - */ - public void searchApplied(ITmfFilter filter, ITmfTrace trace); - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.viewers.events; + +import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; + +/** + * A filter/search event listener + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITmfEventsFilterListener { + + /** + * Notify this listener that a filter has been applied. + * + * @param filter + * The filter that was applied + * @param trace + * The trace on which this filter is applied + */ + public void filterApplied(ITmfFilter filter, ITmfTrace trace); + + /** + * Notify this listener that a new search has been run. + * + * @param filter + * The filter that was applied + * @param trace + * The trace on which this filter is applied + */ + public void searchApplied(ITmfFilter filter, ITmfTrace trace); + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterProvider.java index 5791409385..2aa788d374 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/viewers/events/ITmfEventsFilterProvider.java @@ -1,39 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.viewers.events; - -/** - * A filter/search event provider - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITmfEventsFilterProvider { - - /** - * Add a listener to this provider. - * - * @param listener - * The listener to add - */ - public void addEventsFilterListener(ITmfEventsFilterListener listener); - - /** - * Remove a listener from this provider. - * - * @param listener - * The listener to remove - */ - public void removeEventsFilterListener (ITmfEventsFilterListener listener); - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.viewers.events; + +/** + * A filter/search event provider + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITmfEventsFilterProvider { + + /** + * Add a listener to this provider. + * + * @param listener + * The listener to add + */ + public void addEventsFilterListener(ITmfEventsFilterListener listener); + + /** + * Remove a listener from this provider. + * + * @param listener + * The listener to remove + */ + public void removeEventsFilterListener (ITmfEventsFilterListener listener); + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java index 37c08cc0d2..176d10779d 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java @@ -1,214 +1,214 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - * Bernd Hufmann - Updated to use RGB for the tick color - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.colors; - -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.themes.ColorUtil; - -/** - * Class for storing color settings of a TMF filter. - * - * Application code must explicitly invoke the ColorSetting.dispose() method to release the operating system - * resources managed by each instance when those instances are no longer required. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class ColorSetting { - - private RGB fForegroundRGB; - private RGB fBackgroundRGB; - private RGB fTickColorRGB; - private Color fForegroundColor; - private Color fBackgroundColor; - private Color fDimmedForegroundColor; - private Color fDimmedBackgroundColor; - private Color fTickColor; - private ITmfFilterTreeNode fFilter; - - /** - * Constructor - * - * You must dispose the color setting when it is no longer required. - * - * @param foreground - * The foreground color - * @param background - * The background color - * @param tickColorRGB - * The color for the checkbox ticks - * @param filter - * The filter tree node - */ - public ColorSetting(RGB foreground, RGB background, RGB tickColorRGB, ITmfFilterTreeNode filter) { - fForegroundRGB = foreground; - fBackgroundRGB = background; - fTickColorRGB = tickColorRGB; - fFilter = filter; - Display display = Display.getDefault(); - fForegroundColor = new Color(display, fForegroundRGB); - fBackgroundColor = new Color(display, fBackgroundRGB); - fDimmedForegroundColor = new Color(display, ColorUtil.blend( - fForegroundRGB, fBackgroundRGB)); - fDimmedBackgroundColor = new Color(display, ColorUtil.blend( - fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB())); - fTickColor = new Color(display, fTickColorRGB); - } - - /** - * Dispose the color setting resources - */ - public void dispose() { - fForegroundColor.dispose(); - fBackgroundColor.dispose(); - fDimmedForegroundColor.dispose(); - fDimmedBackgroundColor.dispose(); - fTickColor.dispose(); - } - - /** - * Returns foreground RGB value. - * - * @return the foreground RGB - */ - public RGB getForegroundRGB() { - return fForegroundRGB; - } - - /** - * Sets the foreground RGB value - * - * @param foreground the foreground to set - */ - public void setForegroundRGB(RGB foreground) { - fForegroundRGB = foreground; - fForegroundColor.dispose(); - fDimmedForegroundColor.dispose(); - Display display = Display.getDefault(); - fForegroundColor = new Color(display, fForegroundRGB); - fDimmedForegroundColor = new Color(display, ColorUtil.blend( - fForegroundRGB, fBackgroundRGB)); - } - - /** - * Returns the background RGB value. - * - * @return the background RGB - */ - public RGB getBackgroundRGB() { - return fBackgroundRGB; - } - - /** - * Sets the background RGB value. - * - * @param background the background to set - */ - public void setBackgroundRGB(RGB background) { - fBackgroundRGB = background; - fBackgroundColor.dispose(); - fDimmedBackgroundColor.dispose(); - Display display = Display.getDefault(); - fBackgroundColor = new Color(display, fBackgroundRGB); - fDimmedBackgroundColor = new Color(display, ColorUtil.blend( - fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB())); - } - - /** - * Returns the RGB of the tick color - * - * @return the RGB of the tick color - */ - public RGB getTickColorRGB() { - return fTickColorRGB; - } - - /** - * Sets the RGB of the tick color - * - * @param tickColorRGB the tick color TGB - */ - public void setTickColorRGB(RGB tickColorRGB) { - fTickColorRGB = tickColorRGB; - fTickColor.dispose(); - Display display = Display.getDefault(); - fTickColor = new Color(display, fTickColorRGB); - } - - /** - * Returns the filter implementation. - * @return the filter - */ - public ITmfFilterTreeNode getFilter() { - return fFilter; - } - - /** - * Sets the filter implementation. - * - * @param filter the filter to set - */ - public void setFilter(ITmfFilterTreeNode filter) { - fFilter = filter; - } - - /** - * Returns the foreground color. - * - * @return the foreground color - */ - public Color getForegroundColor() { - return fForegroundColor; - } - - /** - * Returns the background color. - * - * @return the background color - */ - public Color getBackgroundColor() { - return fBackgroundColor; - } - - /** - * Returns the dimmed foreground color. - * - * @return the dimmed foreground color - */ - public Color getDimmedForegroundColor() { - return fDimmedForegroundColor; - } - - /** - * Returns the dimmed background color. - * - * @return the dimmed background color - */ - public Color getDimmedBackgroundColor() { - return fDimmedBackgroundColor; - } - - /** - * Returns the tick color. - * - * @return the tick color - */ - public Color getTickColor() { - return fTickColor; - } -} +/******************************************************************************* + * Copyright (c) 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + * Bernd Hufmann - Updated to use RGB for the tick color + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.colors; + +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.themes.ColorUtil; + +/** + * Class for storing color settings of a TMF filter. + * + * Application code must explicitly invoke the ColorSetting.dispose() method to release the operating system + * resources managed by each instance when those instances are no longer required. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class ColorSetting { + + private RGB fForegroundRGB; + private RGB fBackgroundRGB; + private RGB fTickColorRGB; + private Color fForegroundColor; + private Color fBackgroundColor; + private Color fDimmedForegroundColor; + private Color fDimmedBackgroundColor; + private Color fTickColor; + private ITmfFilterTreeNode fFilter; + + /** + * Constructor + * + * You must dispose the color setting when it is no longer required. + * + * @param foreground + * The foreground color + * @param background + * The background color + * @param tickColorRGB + * The color for the checkbox ticks + * @param filter + * The filter tree node + */ + public ColorSetting(RGB foreground, RGB background, RGB tickColorRGB, ITmfFilterTreeNode filter) { + fForegroundRGB = foreground; + fBackgroundRGB = background; + fTickColorRGB = tickColorRGB; + fFilter = filter; + Display display = Display.getDefault(); + fForegroundColor = new Color(display, fForegroundRGB); + fBackgroundColor = new Color(display, fBackgroundRGB); + fDimmedForegroundColor = new Color(display, ColorUtil.blend( + fForegroundRGB, fBackgroundRGB)); + fDimmedBackgroundColor = new Color(display, ColorUtil.blend( + fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB())); + fTickColor = new Color(display, fTickColorRGB); + } + + /** + * Dispose the color setting resources + */ + public void dispose() { + fForegroundColor.dispose(); + fBackgroundColor.dispose(); + fDimmedForegroundColor.dispose(); + fDimmedBackgroundColor.dispose(); + fTickColor.dispose(); + } + + /** + * Returns foreground RGB value. + * + * @return the foreground RGB + */ + public RGB getForegroundRGB() { + return fForegroundRGB; + } + + /** + * Sets the foreground RGB value + * + * @param foreground the foreground to set + */ + public void setForegroundRGB(RGB foreground) { + fForegroundRGB = foreground; + fForegroundColor.dispose(); + fDimmedForegroundColor.dispose(); + Display display = Display.getDefault(); + fForegroundColor = new Color(display, fForegroundRGB); + fDimmedForegroundColor = new Color(display, ColorUtil.blend( + fForegroundRGB, fBackgroundRGB)); + } + + /** + * Returns the background RGB value. + * + * @return the background RGB + */ + public RGB getBackgroundRGB() { + return fBackgroundRGB; + } + + /** + * Sets the background RGB value. + * + * @param background the background to set + */ + public void setBackgroundRGB(RGB background) { + fBackgroundRGB = background; + fBackgroundColor.dispose(); + fDimmedBackgroundColor.dispose(); + Display display = Display.getDefault(); + fBackgroundColor = new Color(display, fBackgroundRGB); + fDimmedBackgroundColor = new Color(display, ColorUtil.blend( + fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB())); + } + + /** + * Returns the RGB of the tick color + * + * @return the RGB of the tick color + */ + public RGB getTickColorRGB() { + return fTickColorRGB; + } + + /** + * Sets the RGB of the tick color + * + * @param tickColorRGB the tick color TGB + */ + public void setTickColorRGB(RGB tickColorRGB) { + fTickColorRGB = tickColorRGB; + fTickColor.dispose(); + Display display = Display.getDefault(); + fTickColor = new Color(display, fTickColorRGB); + } + + /** + * Returns the filter implementation. + * @return the filter + */ + public ITmfFilterTreeNode getFilter() { + return fFilter; + } + + /** + * Sets the filter implementation. + * + * @param filter the filter to set + */ + public void setFilter(ITmfFilterTreeNode filter) { + fFilter = filter; + } + + /** + * Returns the foreground color. + * + * @return the foreground color + */ + public Color getForegroundColor() { + return fForegroundColor; + } + + /** + * Returns the background color. + * + * @return the background color + */ + public Color getBackgroundColor() { + return fBackgroundColor; + } + + /** + * Returns the dimmed foreground color. + * + * @return the dimmed foreground color + */ + public Color getDimmedForegroundColor() { + return fDimmedForegroundColor; + } + + /** + * Returns the dimmed background color. + * + * @return the dimmed background color + */ + public Color getDimmedBackgroundColor() { + return fDimmedBackgroundColor; + } + + /** + * Returns the tick color. + * + * @return the tick color + */ + public Color getTickColor() { + return fTickColor; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java index b1de6acaeb..c654ee17f4 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java @@ -1,153 +1,153 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - * Bernd Hufmann - Updated to use RGB for the tick color - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.colors; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; - -/** - * Static class for managing color settings. - * - * @version 1.0 - * @author Patrick Tasse - * - */ -public class ColorSettingsManager { - - // The color settings file name - private static final String COLOR_SETTINGS_FILE_NAME = "color_settings.xml"; //$NON-NLS-1$ - - // The path for the color settings file - private static final String COLOR_SETTINGS_PATH_NAME = - Activator.getDefault().getStateLocation().addTrailingSeparator().append(COLOR_SETTINGS_FILE_NAME).toString(); - - // The default color setting - private static final ColorSetting DEFAULT_COLOR_SETTING = new ColorSetting( - Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), - Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(), - Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), - null); - - /** - * Special value for priority if unknown. - */ - public static final int PRIORITY_NONE = Integer.MAX_VALUE; - - // The stored color settings - private static ColorSetting[] fColorSettings = ColorSettingsXML.load(COLOR_SETTINGS_PATH_NAME); - - // The listener list - private static List fListeners = new ArrayList(); - - /** - * Returns an array of color settings. - * - * @return an array of color settings. - */ - public static ColorSetting[] getColorSettings() { - return (fColorSettings != null) ? Arrays.copyOf(fColorSettings, fColorSettings.length) : null; - } - - /** - * Sets the array of color settings. - * - * @param colorSettings A array of color settings to set - */ - public static void setColorSettings(ColorSetting[] colorSettings) { - fColorSettings = (colorSettings != null) ? Arrays.copyOf(colorSettings, colorSettings.length) : null; - ColorSettingsXML.save(COLOR_SETTINGS_PATH_NAME, fColorSettings); - fireColorSettingsChanged(); - } - - /** - * Gets the color settings that matches the filter for given event. - * - * @param event - * The event to check - * - * @return color settings defined for filter if found else default color - * settings - */ - public static ColorSetting getColorSetting(ITmfEvent event) { - for (int i = 0; i < fColorSettings.length; i++) { - ColorSetting colorSetting = fColorSettings[i]; - if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) { - return colorSetting; - } - } - return DEFAULT_COLOR_SETTING; - } - - /** - * Gets the color settings priority for the given event. - * - * @param event A event the event to check - * @return the priority defined for the filter else PRIORITY_NONE - */ - public static int getColorSettingPriority(ITmfEvent event) { - for (int i = 0; i < fColorSettings.length; i++) { - ColorSetting colorSetting = fColorSettings[i]; - if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) { - return i; - } - } - return PRIORITY_NONE; - } - - /** - * Returns the color settings based the priority. - * - * @param priority A priority (index) of color settings - * @return the color settings defined for the priority else default color settings - */ - public static ColorSetting getColorSetting(int priority) { - if (priority < fColorSettings.length) { - return fColorSettings[priority]; - } - return DEFAULT_COLOR_SETTING; - } - - /** - * Adds a color settings listener. - * - * @param listener A listener to add. - */ - public static void addColorSettingsListener(IColorSettingsListener listener) { - if (! fListeners.contains(listener)) { - fListeners.add(listener); - } - } - - /** - * Removes a color settings listener. - * - * @param listener A listener to remove. - */ - public static void removeColorSettingsListener(IColorSettingsListener listener) { - fListeners.remove(listener); - } - - // Notify listeners - private static void fireColorSettingsChanged() { - for (IColorSettingsListener listener : fListeners) { - listener.colorSettingsChanged(fColorSettings); - } - } -} +/******************************************************************************* + * Copyright (c) 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + * Bernd Hufmann - Updated to use RGB for the tick color + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.colors; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; + +/** + * Static class for managing color settings. + * + * @version 1.0 + * @author Patrick Tasse + * + */ +public class ColorSettingsManager { + + // The color settings file name + private static final String COLOR_SETTINGS_FILE_NAME = "color_settings.xml"; //$NON-NLS-1$ + + // The path for the color settings file + private static final String COLOR_SETTINGS_PATH_NAME = + Activator.getDefault().getStateLocation().addTrailingSeparator().append(COLOR_SETTINGS_FILE_NAME).toString(); + + // The default color setting + private static final ColorSetting DEFAULT_COLOR_SETTING = new ColorSetting( + Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), + Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(), + Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), + null); + + /** + * Special value for priority if unknown. + */ + public static final int PRIORITY_NONE = Integer.MAX_VALUE; + + // The stored color settings + private static ColorSetting[] fColorSettings = ColorSettingsXML.load(COLOR_SETTINGS_PATH_NAME); + + // The listener list + private static List fListeners = new ArrayList(); + + /** + * Returns an array of color settings. + * + * @return an array of color settings. + */ + public static ColorSetting[] getColorSettings() { + return (fColorSettings != null) ? Arrays.copyOf(fColorSettings, fColorSettings.length) : null; + } + + /** + * Sets the array of color settings. + * + * @param colorSettings A array of color settings to set + */ + public static void setColorSettings(ColorSetting[] colorSettings) { + fColorSettings = (colorSettings != null) ? Arrays.copyOf(colorSettings, colorSettings.length) : null; + ColorSettingsXML.save(COLOR_SETTINGS_PATH_NAME, fColorSettings); + fireColorSettingsChanged(); + } + + /** + * Gets the color settings that matches the filter for given event. + * + * @param event + * The event to check + * + * @return color settings defined for filter if found else default color + * settings + */ + public static ColorSetting getColorSetting(ITmfEvent event) { + for (int i = 0; i < fColorSettings.length; i++) { + ColorSetting colorSetting = fColorSettings[i]; + if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) { + return colorSetting; + } + } + return DEFAULT_COLOR_SETTING; + } + + /** + * Gets the color settings priority for the given event. + * + * @param event A event the event to check + * @return the priority defined for the filter else PRIORITY_NONE + */ + public static int getColorSettingPriority(ITmfEvent event) { + for (int i = 0; i < fColorSettings.length; i++) { + ColorSetting colorSetting = fColorSettings[i]; + if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) { + return i; + } + } + return PRIORITY_NONE; + } + + /** + * Returns the color settings based the priority. + * + * @param priority A priority (index) of color settings + * @return the color settings defined for the priority else default color settings + */ + public static ColorSetting getColorSetting(int priority) { + if (priority < fColorSettings.length) { + return fColorSettings[priority]; + } + return DEFAULT_COLOR_SETTING; + } + + /** + * Adds a color settings listener. + * + * @param listener A listener to add. + */ + public static void addColorSettingsListener(IColorSettingsListener listener) { + if (! fListeners.contains(listener)) { + fListeners.add(listener); + } + } + + /** + * Removes a color settings listener. + * + * @param listener A listener to remove. + */ + public static void removeColorSettingsListener(IColorSettingsListener listener) { + fListeners.remove(listener); + } + + // Notify listeners + private static void fireColorSettingsChanged() { + for (IColorSettingsListener listener : fListeners) { + listener.colorSettingsChanged(fColorSettings); + } + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsXML.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsXML.java index c7b017ebe2..44d0d04a5b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsXML.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsXML.java @@ -1,224 +1,224 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - * Bernd Hufmann - Updated to use RGB for the tick color - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.colors; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterContentHandler; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; -import org.eclipse.swt.graphics.RGB; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Class for saving and loading of color settings to/from file. - * - * @version 1.0 - * @author Patrick Tasse - * - */ -public class ColorSettingsXML { - - // XML Tags and attributes - private static final String COLOR_SETTINGS_TAG = "COLOR_SETTINGS"; //$NON-NLS-1$ - private static final String COLOR_SETTING_TAG = "COLOR_SETTING"; //$NON-NLS-1$ - private static final String FG_TAG = "FG"; //$NON-NLS-1$ - private static final String BG_TAG = "BG"; //$NON-NLS-1$ - private static final String R_ATTR = "R"; //$NON-NLS-1$ - private static final String G_ATTR = "G"; //$NON-NLS-1$ - private static final String B_ATTR = "B"; //$NON-NLS-1$ - private static final String TICK_TAG = "TICK"; //$NON-NLS-1$ - private static final String FILTER_TAG = "FILTER"; //$NON-NLS-1$ - - /** - * Saves the given color settings to file. - * - * @param pathName A file name with path - * @param colorSettings -An array of color settings to save. - */ - public static void save(String pathName, ColorSetting[] colorSettings) { - try { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - - Element rootElement = document.createElement(COLOR_SETTINGS_TAG); - document.appendChild(rootElement); - - for (ColorSetting colorSetting : colorSettings) { - Element colorSettingElement = document.createElement(COLOR_SETTING_TAG); - rootElement.appendChild(colorSettingElement); - - Element fgElement = document.createElement(FG_TAG); - colorSettingElement.appendChild(fgElement); - RGB foreground = colorSetting.getForegroundRGB(); - fgElement.setAttribute(R_ATTR, Integer.toString(foreground.red)); - fgElement.setAttribute(G_ATTR, Integer.toString(foreground.green)); - fgElement.setAttribute(B_ATTR, Integer.toString(foreground.blue)); - - Element bgElement = document.createElement(BG_TAG); - colorSettingElement.appendChild(bgElement); - RGB background = colorSetting.getBackgroundRGB(); - bgElement.setAttribute(R_ATTR, Integer.toString(background.red)); - bgElement.setAttribute(G_ATTR, Integer.toString(background.green)); - bgElement.setAttribute(B_ATTR, Integer.toString(background.blue)); - - Element tickColorElement = document.createElement(TICK_TAG); - colorSettingElement.appendChild(tickColorElement); - RGB tickColor = colorSetting.getTickColorRGB(); - tickColorElement.setAttribute(R_ATTR, Integer.toString(tickColor.red)); - tickColorElement.setAttribute(G_ATTR, Integer.toString(tickColor.green)); - tickColorElement.setAttribute(B_ATTR, Integer.toString(tickColor.blue)); - - if (colorSetting.getFilter() != null) { - Element filterElement = document.createElement(FILTER_TAG); - colorSettingElement.appendChild(filterElement); - TmfFilterXMLWriter.buildXMLTree(document, colorSetting.getFilter(), filterElement); - } - } - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(new File(pathName)); - transformer.transform(source, result); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ - } catch (TransformerConfigurationException e) { - Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ - } catch (TransformerException e) { - Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ - } - } - - /** - * Loads color settings from file and returns it in an array. - * - * @param pathName A file name with path - * - * @return the color settings array loaded from file - */ - public static ColorSetting[] load(String pathName) { - if (! new File(pathName).canRead()) { - return new ColorSetting[0]; - } - SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - parserFactory.setNamespaceAware(true); - - ColorSettingsContentHandler handler = new ColorSettingsContentHandler(); - try { - XMLReader saxReader = parserFactory.newSAXParser().getXMLReader(); - saxReader.setContentHandler(handler); - saxReader.parse(pathName); - return handler.colorSettings.toArray(new ColorSetting[0]); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ - } catch (SAXException e) { - Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ - } - // In case of error, dispose the partial list of color settings - for (ColorSetting colorSetting : handler.colorSettings) { - colorSetting.dispose(); - } - return new ColorSetting[0]; - } - - // Helper class - private static class ColorSettingsContentHandler extends DefaultHandler { - - private List colorSettings = new ArrayList(0); - private RGB fg = new RGB(0, 0, 0); - private RGB bg = new RGB(255, 255, 255); - private RGB tickColor = new RGB(0, 0, 0); - private ITmfFilterTreeNode filter; - private TmfFilterContentHandler filterContentHandler; - - /* (non-Javadoc) - * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) - throws SAXException { - if (localName.equals(COLOR_SETTINGS_TAG)) { - colorSettings = new ArrayList(); - } else if (localName.equals(COLOR_SETTING_TAG)) { - fg = null; - bg = null; - filter = null; - } else if (localName.equals(FG_TAG)) { - int r = Integer.valueOf(attributes.getValue(R_ATTR)); - int g = Integer.valueOf(attributes.getValue(G_ATTR)); - int b = Integer.valueOf(attributes.getValue(B_ATTR)); - fg = new RGB(r, g, b); - } else if (localName.equals(BG_TAG)) { - int r = Integer.valueOf(attributes.getValue(R_ATTR)); - int g = Integer.valueOf(attributes.getValue(G_ATTR)); - int b = Integer.valueOf(attributes.getValue(B_ATTR)); - bg = new RGB(r, g, b); - } else if (localName.equals(TICK_TAG)) { - int r = Integer.valueOf(attributes.getValue(R_ATTR)); - int g = Integer.valueOf(attributes.getValue(G_ATTR)); - int b = Integer.valueOf(attributes.getValue(B_ATTR)); - tickColor = new RGB(r, g, b); - } else if (localName.equals(FILTER_TAG)) { - filterContentHandler = new TmfFilterContentHandler(); - } else if (filterContentHandler != null) { - filterContentHandler.startElement(uri, localName, qName, attributes); - } - } - - /* (non-Javadoc) - * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - if (localName.equals(COLOR_SETTINGS_TAG)) { - // Nothing to do - } else if (localName.equals(COLOR_SETTING_TAG)) { - ColorSetting colorSetting = new ColorSetting(fg, bg, tickColor, filter); - colorSettings.add(colorSetting); - } else if (localName.equals(FILTER_TAG)) { - filter = filterContentHandler.getTree(); - filterContentHandler = null; - } else if (filterContentHandler != null) { - filterContentHandler.endElement(uri, localName, qName); - } - } - - } -} +/******************************************************************************* + * Copyright (c) 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + * Bernd Hufmann - Updated to use RGB for the tick color + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.colors; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterContentHandler; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; +import org.eclipse.swt.graphics.RGB; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Class for saving and loading of color settings to/from file. + * + * @version 1.0 + * @author Patrick Tasse + * + */ +public class ColorSettingsXML { + + // XML Tags and attributes + private static final String COLOR_SETTINGS_TAG = "COLOR_SETTINGS"; //$NON-NLS-1$ + private static final String COLOR_SETTING_TAG = "COLOR_SETTING"; //$NON-NLS-1$ + private static final String FG_TAG = "FG"; //$NON-NLS-1$ + private static final String BG_TAG = "BG"; //$NON-NLS-1$ + private static final String R_ATTR = "R"; //$NON-NLS-1$ + private static final String G_ATTR = "G"; //$NON-NLS-1$ + private static final String B_ATTR = "B"; //$NON-NLS-1$ + private static final String TICK_TAG = "TICK"; //$NON-NLS-1$ + private static final String FILTER_TAG = "FILTER"; //$NON-NLS-1$ + + /** + * Saves the given color settings to file. + * + * @param pathName A file name with path + * @param colorSettings -An array of color settings to save. + */ + public static void save(String pathName, ColorSetting[] colorSettings) { + try { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + + Element rootElement = document.createElement(COLOR_SETTINGS_TAG); + document.appendChild(rootElement); + + for (ColorSetting colorSetting : colorSettings) { + Element colorSettingElement = document.createElement(COLOR_SETTING_TAG); + rootElement.appendChild(colorSettingElement); + + Element fgElement = document.createElement(FG_TAG); + colorSettingElement.appendChild(fgElement); + RGB foreground = colorSetting.getForegroundRGB(); + fgElement.setAttribute(R_ATTR, Integer.toString(foreground.red)); + fgElement.setAttribute(G_ATTR, Integer.toString(foreground.green)); + fgElement.setAttribute(B_ATTR, Integer.toString(foreground.blue)); + + Element bgElement = document.createElement(BG_TAG); + colorSettingElement.appendChild(bgElement); + RGB background = colorSetting.getBackgroundRGB(); + bgElement.setAttribute(R_ATTR, Integer.toString(background.red)); + bgElement.setAttribute(G_ATTR, Integer.toString(background.green)); + bgElement.setAttribute(B_ATTR, Integer.toString(background.blue)); + + Element tickColorElement = document.createElement(TICK_TAG); + colorSettingElement.appendChild(tickColorElement); + RGB tickColor = colorSetting.getTickColorRGB(); + tickColorElement.setAttribute(R_ATTR, Integer.toString(tickColor.red)); + tickColorElement.setAttribute(G_ATTR, Integer.toString(tickColor.green)); + tickColorElement.setAttribute(B_ATTR, Integer.toString(tickColor.blue)); + + if (colorSetting.getFilter() != null) { + Element filterElement = document.createElement(FILTER_TAG); + colorSettingElement.appendChild(filterElement); + TmfFilterXMLWriter.buildXMLTree(document, colorSetting.getFilter(), filterElement); + } + } + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(new File(pathName)); + transformer.transform(source, result); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ + } catch (TransformerConfigurationException e) { + Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ + } catch (TransformerException e) { + Activator.getDefault().logError("Error saving color xml file: " + pathName, e); //$NON-NLS-1$ + } + } + + /** + * Loads color settings from file and returns it in an array. + * + * @param pathName A file name with path + * + * @return the color settings array loaded from file + */ + public static ColorSetting[] load(String pathName) { + if (! new File(pathName).canRead()) { + return new ColorSetting[0]; + } + SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + parserFactory.setNamespaceAware(true); + + ColorSettingsContentHandler handler = new ColorSettingsContentHandler(); + try { + XMLReader saxReader = parserFactory.newSAXParser().getXMLReader(); + saxReader.setContentHandler(handler); + saxReader.parse(pathName); + return handler.colorSettings.toArray(new ColorSetting[0]); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ + } catch (SAXException e) { + Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$ + } + // In case of error, dispose the partial list of color settings + for (ColorSetting colorSetting : handler.colorSettings) { + colorSetting.dispose(); + } + return new ColorSetting[0]; + } + + // Helper class + private static class ColorSettingsContentHandler extends DefaultHandler { + + private List colorSettings = new ArrayList(0); + private RGB fg = new RGB(0, 0, 0); + private RGB bg = new RGB(255, 255, 255); + private RGB tickColor = new RGB(0, 0, 0); + private ITmfFilterTreeNode filter; + private TmfFilterContentHandler filterContentHandler; + + /* (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { + if (localName.equals(COLOR_SETTINGS_TAG)) { + colorSettings = new ArrayList(); + } else if (localName.equals(COLOR_SETTING_TAG)) { + fg = null; + bg = null; + filter = null; + } else if (localName.equals(FG_TAG)) { + int r = Integer.valueOf(attributes.getValue(R_ATTR)); + int g = Integer.valueOf(attributes.getValue(G_ATTR)); + int b = Integer.valueOf(attributes.getValue(B_ATTR)); + fg = new RGB(r, g, b); + } else if (localName.equals(BG_TAG)) { + int r = Integer.valueOf(attributes.getValue(R_ATTR)); + int g = Integer.valueOf(attributes.getValue(G_ATTR)); + int b = Integer.valueOf(attributes.getValue(B_ATTR)); + bg = new RGB(r, g, b); + } else if (localName.equals(TICK_TAG)) { + int r = Integer.valueOf(attributes.getValue(R_ATTR)); + int g = Integer.valueOf(attributes.getValue(G_ATTR)); + int b = Integer.valueOf(attributes.getValue(B_ATTR)); + tickColor = new RGB(r, g, b); + } else if (localName.equals(FILTER_TAG)) { + filterContentHandler = new TmfFilterContentHandler(); + } else if (filterContentHandler != null) { + filterContentHandler.startElement(uri, localName, qName, attributes); + } + } + + /* (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + if (localName.equals(COLOR_SETTINGS_TAG)) { + // Nothing to do + } else if (localName.equals(COLOR_SETTING_TAG)) { + ColorSetting colorSetting = new ColorSetting(fg, bg, tickColor, filter); + colorSettings.add(colorSetting); + } else if (localName.equals(FILTER_TAG)) { + filter = filterContentHandler.getTree(); + filterContentHandler = null; + } else if (filterContentHandler != null) { + filterContentHandler.endElement(uri, localName, qName); + } + } + + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorsView.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorsView.java index 59d936f448..6f52b3a00b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorsView.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorsView.java @@ -1,583 +1,583 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - * Bernd Hufmann - Updated to use RGB for the tick color - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.colors; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.window.Window; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.ui.views.TmfView; -import org.eclipse.linuxtools.tmf.ui.views.filter.FilterDialog; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphColorScheme; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.MouseAdapter; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.ColorDialog; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IActionBars; - -/** - * Color view implementation. This view provides support for managing color settings for filters. - * - * @version 1.0 - * @author Patrick Tasse - * - */ -public class ColorsView extends TmfView { - - /** ID for the color view */ - public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.colors"; //$NON-NLS-1$ - - private static final Image ADD_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ - private static final Image DELETE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ - private static final Image MOVE_UP_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ - private static final Image MOVE_DOWN_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ - private static final Image IMPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/import_button.gif"); //$NON-NLS-1$ - private static final Image EXPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/export_button.gif"); //$NON-NLS-1$ - - // ------------------------------------------------------------------------ - // Main data structures - // ------------------------------------------------------------------------ - - /** - * The composite shell. - */ - protected Shell fShell; - /** - * The main composite (scrolled composite) - */ - protected ScrolledComposite fScrolledComposite; - /** - * The list composite. - */ - protected Composite fListComposite; - /** - * The filler composite. - */ - protected Composite fFillerComposite; - /** - * The selected color settings row - */ - protected ColorSettingRow fSelectedRow = null; - /** - * The color scheme instance for managing colors - */ - protected TimeGraphColorScheme traceColorScheme = new TimeGraphColorScheme(); - /** - * An action to add a color settings row - */ - protected Action fAddAction; - /** - * An action to delete a color settings row - */ - protected Action fDeleteAction; - /** - * An action to move up a color settings row in the list. - */ - protected Action fMoveUpAction; - /** - * An action to move down a color settings row in the list. - */ - protected Action fMoveDownAction; - /** - * An action to import color settings from file. - */ - protected Action fImportAction; - /** - * An action to export color settings from file. - */ - protected Action fExportAction; - /** - * The list of existing color settings - */ - protected List fColorSettings; - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Default Constructor - */ - public ColorsView() { - super("Colors"); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(Composite) - */ - @Override - public void createPartControl(Composite parent) { - fShell = parent.getShell(); - - fScrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL); - fScrolledComposite.setExpandHorizontal(true); - fScrolledComposite.setExpandVertical(true); - fListComposite = new Composite(fScrolledComposite, SWT.NONE); - fScrolledComposite.setContent(fListComposite); - - GridLayout gl = new GridLayout(); - gl.marginHeight = 0; - gl.marginWidth = 0; - gl.verticalSpacing = 1; - fListComposite.setLayout(gl); - - fColorSettings = new ArrayList(Arrays.asList(ColorSettingsManager.getColorSettings())); - for (ColorSetting colorSetting : fColorSettings) { - new ColorSettingRow(fListComposite, colorSetting); - } - - fFillerComposite = new Composite(fListComposite, SWT.NONE); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.heightHint = 0; - fFillerComposite.setLayoutData(gd); - gl = new GridLayout(); - gl.marginHeight = 1; - gl.marginWidth = 1; - fFillerComposite.setLayout(gl); - Label fillerLabel = new Label(fFillerComposite, SWT.NONE); - fillerLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - fillerLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - fFillerComposite.addPaintListener(new PaintListener() { - @Override - public void paintControl(PaintEvent e) { - if (fSelectedRow == null) { - Color lineColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); - Point p = fFillerComposite.getSize(); - GC gc = e.gc; - gc.setForeground(lineColor); - gc.drawLine(0, 0, p.x - 1, 0); - } - } - }); - - MouseListener mouseListener = new MouseAdapter() { - @Override - public void mouseDown(MouseEvent e) { - fSelectedRow = null; - refresh(); - } - }; - fillerLabel.addMouseListener(mouseListener); - - fScrolledComposite.setMinSize(fListComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - - fillToolBar(); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#setFocus() - */ - @Override - public void setFocus() { - fScrolledComposite.setFocus(); - } - - /** - * Refreshes the view display and updates the view actions enablements. - */ - public void refresh() { - fListComposite.layout(); - fScrolledComposite.setMinSize(fListComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - fListComposite.redraw(0, 0, fListComposite.getBounds().width, fListComposite.getBounds().height, true); - if (fSelectedRow == null) { - fDeleteAction.setEnabled(false); - fMoveUpAction.setEnabled(false); - fMoveDownAction.setEnabled(false); - } else { - fDeleteAction.setEnabled(true); - fMoveUpAction.setEnabled(true); - fMoveDownAction.setEnabled(true); - } - } - - private void fillToolBar() { - - fAddAction = new AddAction(); - fAddAction.setImageDescriptor(ImageDescriptor.createFromImage(ADD_IMAGE)); - fAddAction.setToolTipText(Messages.ColorsView_AddActionToolTipText); - - fDeleteAction = new DeleteAction(); - fDeleteAction.setImageDescriptor(ImageDescriptor.createFromImage(DELETE_IMAGE)); - fDeleteAction.setToolTipText(Messages.ColorsView_DeleteActionToolTipText); - fDeleteAction.setEnabled(false); - - fMoveUpAction = new MoveUpAction(); - fMoveUpAction.setImageDescriptor(ImageDescriptor.createFromImage(MOVE_UP_IMAGE)); - fMoveUpAction.setToolTipText(Messages.ColorsView_MoveUpActionToolTipText); - fMoveUpAction.setEnabled(false); - - fMoveDownAction = new MoveDownAction(); - fMoveDownAction.setImageDescriptor(ImageDescriptor.createFromImage(MOVE_DOWN_IMAGE)); - fMoveDownAction.setToolTipText(Messages.ColorsView_MoveDownActionToolTipText); - fMoveDownAction.setEnabled(false); - - fExportAction = new ExportAction(); - fExportAction.setImageDescriptor(ImageDescriptor.createFromImage(EXPORT_IMAGE)); - fExportAction.setToolTipText(Messages.ColorsView_ExportActionToolTipText); - - fImportAction = new ImportAction(); - fImportAction.setImageDescriptor(ImageDescriptor.createFromImage(IMPORT_IMAGE)); - fImportAction.setToolTipText(Messages.ColorsView_ImportActionToolTipText); - - IActionBars bars = getViewSite().getActionBars(); - IToolBarManager manager = bars.getToolBarManager(); - manager.add(fAddAction); - manager.add(fDeleteAction); - manager.add(fMoveUpAction); - manager.add(fMoveDownAction); - manager.add(new Separator()); - manager.add(fExportAction); - manager.add(fImportAction); - } - - private class AddAction extends Action { - @Override - public void run() { - ColorSetting colorSetting = new ColorSetting( - Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), - Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(), - Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), - null); - ColorSettingRow row = new ColorSettingRow(fListComposite, colorSetting); - if (fSelectedRow == null) { - fColorSettings.add(colorSetting); - row.moveAbove(fFillerComposite); - } else { - fColorSettings.add(fColorSettings.indexOf(fSelectedRow.getColorSetting()), colorSetting); - row.moveAbove(fSelectedRow); - } - fSelectedRow = row; - refresh(); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - } - } - - private class DeleteAction extends Action { - - @Override - public void run() { - if (fSelectedRow != null) { - int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); - fColorSettings.remove(index); - fSelectedRow.fColorSetting.dispose(); - fSelectedRow.dispose(); - if (index < fColorSettings.size()) { - fSelectedRow = (ColorSettingRow) fListComposite.getChildren()[index]; - } else { - fSelectedRow = null; - } - refresh(); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - } - } - } - - private class MoveUpAction extends Action { - @Override - public void run() { - if (fSelectedRow != null) { - int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); - if (index > 0) { - fColorSettings.add(index - 1, fColorSettings.remove(index)); - fSelectedRow.moveAbove(fListComposite.getChildren()[index - 1]); - refresh(); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - } - } - } - } - - private class MoveDownAction extends Action { - @Override - public void run() { - if (fSelectedRow != null) { - int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); - if (index < fColorSettings.size() - 1) { - fColorSettings.add(index + 1, fColorSettings.remove(index)); - - fSelectedRow.moveBelow(fListComposite.getChildren()[index + 1]); - refresh(); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - } - } - } - } - - private class ExportAction extends Action { - @Override - public void run() { - FileDialog fileDialog = new FileDialog(fShell, SWT.SAVE); - fileDialog.setFilterExtensions(new String[] {"*.xml"}); //$NON-NLS-1$ - fileDialog.setOverwrite(true); - String pathName = fileDialog.open(); - if (pathName != null) { - ColorSettingsXML.save(pathName, fColorSettings.toArray(new ColorSetting[0])); - } - } - } - - private class ImportAction extends Action { - @Override - public void run() { - FileDialog fileDialog = new FileDialog(fShell, SWT.OPEN); - fileDialog.setFilterExtensions(new String[] {"*.xml"}); //$NON-NLS-1$ - String pathName = fileDialog.open(); - if (pathName != null) { - ColorSetting[] colorSettings = ColorSettingsXML.load(pathName); - if (colorSettings.length > 0) { - if (fColorSettings.size() > 0) { - boolean overwrite = MessageDialog.openQuestion(fShell, - Messages.ColorsView_ImportOverwriteDialogTitle, - Messages.ColorsView_ImportOverwriteDialogMessage1 + - Messages.ColorsView_ImportOverwriteDialogMessage2); - if (overwrite) { - for (Control control : fListComposite.getChildren()) { - if (control instanceof ColorSettingRow) { - ((ColorSettingRow) control).fColorSetting.dispose(); - control.dispose(); - } - } - fColorSettings = new ArrayList(); - fSelectedRow = null; - } - } - for (ColorSetting colorSetting : colorSettings) { - ColorSettingRow row = new ColorSettingRow(fListComposite, colorSetting); - if (fSelectedRow == null) { - fColorSettings.add(colorSetting); - row.moveAbove(fFillerComposite); - } else { - fColorSettings.add(fColorSettings.indexOf(fSelectedRow.getColorSetting()), colorSetting); - row.moveAbove(fSelectedRow); - } - } - refresh(); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - } - } - } - } - - private class ColorSettingRow extends Composite { - - ColorSetting fColorSetting; - - public ColorSettingRow(final Composite parent, final ColorSetting colorSetting) { - super(parent, SWT.NONE); - fColorSetting = colorSetting; - - setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - GridLayout gl = new GridLayout(7, false); - gl.marginHeight = 1; - gl.marginWidth = 1; - gl.horizontalSpacing = 1; - gl.verticalSpacing = 0; - setLayout(gl); - - final Button fgButton = new Button(this, SWT.PUSH); - fgButton.setText(Messages.ColorsView_ForegroundButtonText); - fgButton.setSize(fgButton.computeSize(SWT.DEFAULT, 19)); - fgButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - final Button bgButton = new Button(this, SWT.PUSH); - bgButton.setText(Messages.ColorsView_BackgroundButtonText); - bgButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - final Composite labelComposite = new Composite(this, SWT.NONE); - labelComposite.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, false)); - gl = new GridLayout(); - gl.marginHeight = 0; - gl.marginWidth = 0; - labelComposite.setLayout(gl); - labelComposite.setBackground(colorSetting.getBackgroundColor()); - - final Label label = new Label(labelComposite, SWT.NONE); - label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true)); - label.setText(" Text "); //$NON-NLS-1$ - label.setForeground(colorSetting.getForegroundColor()); - label.setBackground(colorSetting.getBackgroundColor()); - - fgButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fSelectedRow = ColorSettingRow.this; - refresh(); - ColorDialog dialog = new ColorDialog(fShell); - dialog.setRGB(colorSetting.getForegroundRGB()); - dialog.setText(Messages.ColorsView_ForegroundDialogText); - dialog.open(); - colorSetting.setForegroundRGB(dialog.getRGB()); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - label.setForeground(colorSetting.getForegroundColor()); - }}); - - bgButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fSelectedRow = ColorSettingRow.this; - refresh(); - ColorDialog dialog = new ColorDialog(fShell); - dialog.setRGB(colorSetting.getBackgroundRGB()); - dialog.setText(Messages.ColorsView_BackgroundDialogText); - dialog.open(); - colorSetting.setBackgroundRGB(dialog.getRGB()); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - labelComposite.setBackground(colorSetting.getBackgroundColor()); - label.setBackground(colorSetting.getBackgroundColor()); - }}); - - final Button tickButton = new Button(this, SWT.PUSH); - tickButton.setText(Messages.ColorsView_TickButtonText); - tickButton.setSize(tickButton.computeSize(SWT.DEFAULT, 19)); - tickButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - final Canvas tickCanvas = new Canvas(this, SWT.NONE); - GridData gd = new GridData(SWT.CENTER, SWT.FILL, false, false); - gd.widthHint = 12; - gd.heightHint = bgButton.getSize().y; - tickCanvas.setLayoutData(gd); - tickCanvas.setBackground(traceColorScheme.getBkColor(false, false, false)); - tickCanvas.addPaintListener(new PaintListener() { - @Override - public void paintControl(PaintEvent e) { - Rectangle bounds = tickCanvas.getBounds(); - e.gc.setForeground(traceColorScheme.getColor(TimeGraphColorScheme.MID_LINE)); - int midy = bounds.y + bounds.height / 2 - 1; - //int midy = e.y + e.height / 2; - e.gc.drawLine(e.x, midy, e.x + e.width, midy); - Rectangle rect = new Rectangle(e.x + 1, bounds.y + 2, 0, bounds.height - 6); - for (int i = 1; i <= 3; i++) { - rect.x += i; - rect.width = i; - e.gc.setBackground(fColorSetting.getTickColor()); - e.gc.fillRectangle(rect); - } - }}); - - tickButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fSelectedRow = ColorSettingRow.this; - ColorDialog dialog = new ColorDialog(fShell); - dialog.setRGB(colorSetting.getTickColorRGB()); - dialog.setText(Messages.TickColorDialog_TickColorDialogTitle); - dialog.open(); - colorSetting.setTickColorRGB(dialog.getRGB()); - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - refresh(); - }}); - - final Button filterButton = new Button(this, SWT.PUSH); - filterButton.setText(Messages.ColorsView_FilterButtonText); - filterButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - - final Label filterText = new Label(this, SWT.NONE); - if (colorSetting.getFilter() != null) { - filterText.setText(colorSetting.getFilter().toString()); - filterText.setToolTipText(colorSetting.getFilter().toString()); - } - filterText.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - filterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - filterButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fSelectedRow = ColorSettingRow.this; - refresh(); - FilterDialog dialog = new FilterDialog(fShell); - dialog.setFilter(colorSetting.getFilter()); - dialog.open(); - if (dialog.getReturnCode() == Window.OK) { - if (dialog.getFilter() != null) { - colorSetting.setFilter(dialog.getFilter()); - filterText.setText(dialog.getFilter().toString()); - filterText.setToolTipText(dialog.getFilter().toString()); - } else { - colorSetting.setFilter(null); - filterText.setText(""); //$NON-NLS-1$ - filterText.setToolTipText(""); //$NON-NLS-1$ - } - ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); - refresh(); - } - }}); - - addPaintListener(new PaintListener() { - @Override - public void paintControl(PaintEvent e) { - if (fSelectedRow == ColorSettingRow.this) { - Color borderColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); - Point p = ColorSettingRow.this.getSize(); - Rectangle rect = new Rectangle(0, 0, p.x - 1, p.y - 1); - GC gc = e.gc; - gc.setForeground(borderColor); - gc.drawRectangle(rect); - } - } - }); - - MouseListener mouseListener = new MouseAdapter() { - @Override - public void mouseDown(MouseEvent e) { - fSelectedRow = ColorSettingRow.this; - refresh(); - } - }; - addMouseListener(mouseListener); - label.addMouseListener(mouseListener); - tickCanvas.addMouseListener(mouseListener); - filterText.addMouseListener(mouseListener); - } - - /** - * @return the ColorSetting - */ - public ColorSetting getColorSetting() { - return fColorSetting; - } - - } -} +/******************************************************************************* + * Copyright (c) 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + * Bernd Hufmann - Updated to use RGB for the tick color + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.colors; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.window.Window; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.ui.views.TmfView; +import org.eclipse.linuxtools.tmf.ui.views.filter.FilterDialog; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphColorScheme; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.ColorDialog; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IActionBars; + +/** + * Color view implementation. This view provides support for managing color settings for filters. + * + * @version 1.0 + * @author Patrick Tasse + * + */ +public class ColorsView extends TmfView { + + /** ID for the color view */ + public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.colors"; //$NON-NLS-1$ + + private static final Image ADD_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ + private static final Image DELETE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ + private static final Image MOVE_UP_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/moveup_button.gif"); //$NON-NLS-1$ + private static final Image MOVE_DOWN_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/movedown_button.gif"); //$NON-NLS-1$ + private static final Image IMPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/import_button.gif"); //$NON-NLS-1$ + private static final Image EXPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/export_button.gif"); //$NON-NLS-1$ + + // ------------------------------------------------------------------------ + // Main data structures + // ------------------------------------------------------------------------ + + /** + * The composite shell. + */ + protected Shell fShell; + /** + * The main composite (scrolled composite) + */ + protected ScrolledComposite fScrolledComposite; + /** + * The list composite. + */ + protected Composite fListComposite; + /** + * The filler composite. + */ + protected Composite fFillerComposite; + /** + * The selected color settings row + */ + protected ColorSettingRow fSelectedRow = null; + /** + * The color scheme instance for managing colors + */ + protected TimeGraphColorScheme traceColorScheme = new TimeGraphColorScheme(); + /** + * An action to add a color settings row + */ + protected Action fAddAction; + /** + * An action to delete a color settings row + */ + protected Action fDeleteAction; + /** + * An action to move up a color settings row in the list. + */ + protected Action fMoveUpAction; + /** + * An action to move down a color settings row in the list. + */ + protected Action fMoveDownAction; + /** + * An action to import color settings from file. + */ + protected Action fImportAction; + /** + * An action to export color settings from file. + */ + protected Action fExportAction; + /** + * The list of existing color settings + */ + protected List fColorSettings; + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Default Constructor + */ + public ColorsView() { + super("Colors"); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(Composite) + */ + @Override + public void createPartControl(Composite parent) { + fShell = parent.getShell(); + + fScrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL); + fScrolledComposite.setExpandHorizontal(true); + fScrolledComposite.setExpandVertical(true); + fListComposite = new Composite(fScrolledComposite, SWT.NONE); + fScrolledComposite.setContent(fListComposite); + + GridLayout gl = new GridLayout(); + gl.marginHeight = 0; + gl.marginWidth = 0; + gl.verticalSpacing = 1; + fListComposite.setLayout(gl); + + fColorSettings = new ArrayList(Arrays.asList(ColorSettingsManager.getColorSettings())); + for (ColorSetting colorSetting : fColorSettings) { + new ColorSettingRow(fListComposite, colorSetting); + } + + fFillerComposite = new Composite(fListComposite, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.heightHint = 0; + fFillerComposite.setLayoutData(gd); + gl = new GridLayout(); + gl.marginHeight = 1; + gl.marginWidth = 1; + fFillerComposite.setLayout(gl); + Label fillerLabel = new Label(fFillerComposite, SWT.NONE); + fillerLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + fillerLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + fFillerComposite.addPaintListener(new PaintListener() { + @Override + public void paintControl(PaintEvent e) { + if (fSelectedRow == null) { + Color lineColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); + Point p = fFillerComposite.getSize(); + GC gc = e.gc; + gc.setForeground(lineColor); + gc.drawLine(0, 0, p.x - 1, 0); + } + } + }); + + MouseListener mouseListener = new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + fSelectedRow = null; + refresh(); + } + }; + fillerLabel.addMouseListener(mouseListener); + + fScrolledComposite.setMinSize(fListComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + + fillToolBar(); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#setFocus() + */ + @Override + public void setFocus() { + fScrolledComposite.setFocus(); + } + + /** + * Refreshes the view display and updates the view actions enablements. + */ + public void refresh() { + fListComposite.layout(); + fScrolledComposite.setMinSize(fListComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + fListComposite.redraw(0, 0, fListComposite.getBounds().width, fListComposite.getBounds().height, true); + if (fSelectedRow == null) { + fDeleteAction.setEnabled(false); + fMoveUpAction.setEnabled(false); + fMoveDownAction.setEnabled(false); + } else { + fDeleteAction.setEnabled(true); + fMoveUpAction.setEnabled(true); + fMoveDownAction.setEnabled(true); + } + } + + private void fillToolBar() { + + fAddAction = new AddAction(); + fAddAction.setImageDescriptor(ImageDescriptor.createFromImage(ADD_IMAGE)); + fAddAction.setToolTipText(Messages.ColorsView_AddActionToolTipText); + + fDeleteAction = new DeleteAction(); + fDeleteAction.setImageDescriptor(ImageDescriptor.createFromImage(DELETE_IMAGE)); + fDeleteAction.setToolTipText(Messages.ColorsView_DeleteActionToolTipText); + fDeleteAction.setEnabled(false); + + fMoveUpAction = new MoveUpAction(); + fMoveUpAction.setImageDescriptor(ImageDescriptor.createFromImage(MOVE_UP_IMAGE)); + fMoveUpAction.setToolTipText(Messages.ColorsView_MoveUpActionToolTipText); + fMoveUpAction.setEnabled(false); + + fMoveDownAction = new MoveDownAction(); + fMoveDownAction.setImageDescriptor(ImageDescriptor.createFromImage(MOVE_DOWN_IMAGE)); + fMoveDownAction.setToolTipText(Messages.ColorsView_MoveDownActionToolTipText); + fMoveDownAction.setEnabled(false); + + fExportAction = new ExportAction(); + fExportAction.setImageDescriptor(ImageDescriptor.createFromImage(EXPORT_IMAGE)); + fExportAction.setToolTipText(Messages.ColorsView_ExportActionToolTipText); + + fImportAction = new ImportAction(); + fImportAction.setImageDescriptor(ImageDescriptor.createFromImage(IMPORT_IMAGE)); + fImportAction.setToolTipText(Messages.ColorsView_ImportActionToolTipText); + + IActionBars bars = getViewSite().getActionBars(); + IToolBarManager manager = bars.getToolBarManager(); + manager.add(fAddAction); + manager.add(fDeleteAction); + manager.add(fMoveUpAction); + manager.add(fMoveDownAction); + manager.add(new Separator()); + manager.add(fExportAction); + manager.add(fImportAction); + } + + private class AddAction extends Action { + @Override + public void run() { + ColorSetting colorSetting = new ColorSetting( + Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), + Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(), + Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(), + null); + ColorSettingRow row = new ColorSettingRow(fListComposite, colorSetting); + if (fSelectedRow == null) { + fColorSettings.add(colorSetting); + row.moveAbove(fFillerComposite); + } else { + fColorSettings.add(fColorSettings.indexOf(fSelectedRow.getColorSetting()), colorSetting); + row.moveAbove(fSelectedRow); + } + fSelectedRow = row; + refresh(); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + } + } + + private class DeleteAction extends Action { + + @Override + public void run() { + if (fSelectedRow != null) { + int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); + fColorSettings.remove(index); + fSelectedRow.fColorSetting.dispose(); + fSelectedRow.dispose(); + if (index < fColorSettings.size()) { + fSelectedRow = (ColorSettingRow) fListComposite.getChildren()[index]; + } else { + fSelectedRow = null; + } + refresh(); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + } + } + } + + private class MoveUpAction extends Action { + @Override + public void run() { + if (fSelectedRow != null) { + int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); + if (index > 0) { + fColorSettings.add(index - 1, fColorSettings.remove(index)); + fSelectedRow.moveAbove(fListComposite.getChildren()[index - 1]); + refresh(); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + } + } + } + } + + private class MoveDownAction extends Action { + @Override + public void run() { + if (fSelectedRow != null) { + int index = fColorSettings.indexOf(fSelectedRow.getColorSetting()); + if (index < fColorSettings.size() - 1) { + fColorSettings.add(index + 1, fColorSettings.remove(index)); + + fSelectedRow.moveBelow(fListComposite.getChildren()[index + 1]); + refresh(); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + } + } + } + } + + private class ExportAction extends Action { + @Override + public void run() { + FileDialog fileDialog = new FileDialog(fShell, SWT.SAVE); + fileDialog.setFilterExtensions(new String[] {"*.xml"}); //$NON-NLS-1$ + fileDialog.setOverwrite(true); + String pathName = fileDialog.open(); + if (pathName != null) { + ColorSettingsXML.save(pathName, fColorSettings.toArray(new ColorSetting[0])); + } + } + } + + private class ImportAction extends Action { + @Override + public void run() { + FileDialog fileDialog = new FileDialog(fShell, SWT.OPEN); + fileDialog.setFilterExtensions(new String[] {"*.xml"}); //$NON-NLS-1$ + String pathName = fileDialog.open(); + if (pathName != null) { + ColorSetting[] colorSettings = ColorSettingsXML.load(pathName); + if (colorSettings.length > 0) { + if (fColorSettings.size() > 0) { + boolean overwrite = MessageDialog.openQuestion(fShell, + Messages.ColorsView_ImportOverwriteDialogTitle, + Messages.ColorsView_ImportOverwriteDialogMessage1 + + Messages.ColorsView_ImportOverwriteDialogMessage2); + if (overwrite) { + for (Control control : fListComposite.getChildren()) { + if (control instanceof ColorSettingRow) { + ((ColorSettingRow) control).fColorSetting.dispose(); + control.dispose(); + } + } + fColorSettings = new ArrayList(); + fSelectedRow = null; + } + } + for (ColorSetting colorSetting : colorSettings) { + ColorSettingRow row = new ColorSettingRow(fListComposite, colorSetting); + if (fSelectedRow == null) { + fColorSettings.add(colorSetting); + row.moveAbove(fFillerComposite); + } else { + fColorSettings.add(fColorSettings.indexOf(fSelectedRow.getColorSetting()), colorSetting); + row.moveAbove(fSelectedRow); + } + } + refresh(); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + } + } + } + } + + private class ColorSettingRow extends Composite { + + ColorSetting fColorSetting; + + public ColorSettingRow(final Composite parent, final ColorSetting colorSetting) { + super(parent, SWT.NONE); + fColorSetting = colorSetting; + + setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + GridLayout gl = new GridLayout(7, false); + gl.marginHeight = 1; + gl.marginWidth = 1; + gl.horizontalSpacing = 1; + gl.verticalSpacing = 0; + setLayout(gl); + + final Button fgButton = new Button(this, SWT.PUSH); + fgButton.setText(Messages.ColorsView_ForegroundButtonText); + fgButton.setSize(fgButton.computeSize(SWT.DEFAULT, 19)); + fgButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + final Button bgButton = new Button(this, SWT.PUSH); + bgButton.setText(Messages.ColorsView_BackgroundButtonText); + bgButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + final Composite labelComposite = new Composite(this, SWT.NONE); + labelComposite.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, false)); + gl = new GridLayout(); + gl.marginHeight = 0; + gl.marginWidth = 0; + labelComposite.setLayout(gl); + labelComposite.setBackground(colorSetting.getBackgroundColor()); + + final Label label = new Label(labelComposite, SWT.NONE); + label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true)); + label.setText(" Text "); //$NON-NLS-1$ + label.setForeground(colorSetting.getForegroundColor()); + label.setBackground(colorSetting.getBackgroundColor()); + + fgButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fSelectedRow = ColorSettingRow.this; + refresh(); + ColorDialog dialog = new ColorDialog(fShell); + dialog.setRGB(colorSetting.getForegroundRGB()); + dialog.setText(Messages.ColorsView_ForegroundDialogText); + dialog.open(); + colorSetting.setForegroundRGB(dialog.getRGB()); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + label.setForeground(colorSetting.getForegroundColor()); + }}); + + bgButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fSelectedRow = ColorSettingRow.this; + refresh(); + ColorDialog dialog = new ColorDialog(fShell); + dialog.setRGB(colorSetting.getBackgroundRGB()); + dialog.setText(Messages.ColorsView_BackgroundDialogText); + dialog.open(); + colorSetting.setBackgroundRGB(dialog.getRGB()); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + labelComposite.setBackground(colorSetting.getBackgroundColor()); + label.setBackground(colorSetting.getBackgroundColor()); + }}); + + final Button tickButton = new Button(this, SWT.PUSH); + tickButton.setText(Messages.ColorsView_TickButtonText); + tickButton.setSize(tickButton.computeSize(SWT.DEFAULT, 19)); + tickButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + final Canvas tickCanvas = new Canvas(this, SWT.NONE); + GridData gd = new GridData(SWT.CENTER, SWT.FILL, false, false); + gd.widthHint = 12; + gd.heightHint = bgButton.getSize().y; + tickCanvas.setLayoutData(gd); + tickCanvas.setBackground(traceColorScheme.getBkColor(false, false, false)); + tickCanvas.addPaintListener(new PaintListener() { + @Override + public void paintControl(PaintEvent e) { + Rectangle bounds = tickCanvas.getBounds(); + e.gc.setForeground(traceColorScheme.getColor(TimeGraphColorScheme.MID_LINE)); + int midy = bounds.y + bounds.height / 2 - 1; + //int midy = e.y + e.height / 2; + e.gc.drawLine(e.x, midy, e.x + e.width, midy); + Rectangle rect = new Rectangle(e.x + 1, bounds.y + 2, 0, bounds.height - 6); + for (int i = 1; i <= 3; i++) { + rect.x += i; + rect.width = i; + e.gc.setBackground(fColorSetting.getTickColor()); + e.gc.fillRectangle(rect); + } + }}); + + tickButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fSelectedRow = ColorSettingRow.this; + ColorDialog dialog = new ColorDialog(fShell); + dialog.setRGB(colorSetting.getTickColorRGB()); + dialog.setText(Messages.TickColorDialog_TickColorDialogTitle); + dialog.open(); + colorSetting.setTickColorRGB(dialog.getRGB()); + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + refresh(); + }}); + + final Button filterButton = new Button(this, SWT.PUSH); + filterButton.setText(Messages.ColorsView_FilterButtonText); + filterButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + + final Label filterText = new Label(this, SWT.NONE); + if (colorSetting.getFilter() != null) { + filterText.setText(colorSetting.getFilter().toString()); + filterText.setToolTipText(colorSetting.getFilter().toString()); + } + filterText.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + filterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + filterButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fSelectedRow = ColorSettingRow.this; + refresh(); + FilterDialog dialog = new FilterDialog(fShell); + dialog.setFilter(colorSetting.getFilter()); + dialog.open(); + if (dialog.getReturnCode() == Window.OK) { + if (dialog.getFilter() != null) { + colorSetting.setFilter(dialog.getFilter()); + filterText.setText(dialog.getFilter().toString()); + filterText.setToolTipText(dialog.getFilter().toString()); + } else { + colorSetting.setFilter(null); + filterText.setText(""); //$NON-NLS-1$ + filterText.setToolTipText(""); //$NON-NLS-1$ + } + ColorSettingsManager.setColorSettings(fColorSettings.toArray(new ColorSetting[0])); + refresh(); + } + }}); + + addPaintListener(new PaintListener() { + @Override + public void paintControl(PaintEvent e) { + if (fSelectedRow == ColorSettingRow.this) { + Color borderColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); + Point p = ColorSettingRow.this.getSize(); + Rectangle rect = new Rectangle(0, 0, p.x - 1, p.y - 1); + GC gc = e.gc; + gc.setForeground(borderColor); + gc.drawRectangle(rect); + } + } + }); + + MouseListener mouseListener = new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + fSelectedRow = ColorSettingRow.this; + refresh(); + } + }; + addMouseListener(mouseListener); + label.addMouseListener(mouseListener); + tickCanvas.addMouseListener(mouseListener); + filterText.addMouseListener(mouseListener); + } + + /** + * @return the ColorSetting + */ + public ColorSetting getColorSetting() { + return fColorSetting; + } + + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/IColorSettingsListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/IColorSettingsListener.java index 45da242e4d..897d0ddda3 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/IColorSettingsListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/IColorSettingsListener.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.colors; - -/** - * A color change listener - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface IColorSettingsListener { - - /** - * Notify the listener that the color settings have changed. - * - * @param colorSettings - * The new color settings - */ - public void colorSettingsChanged(ColorSetting[] colorSettings); -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.colors; + +/** + * A color change listener + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface IColorSettingsListener { + + /** + * Notify the listener that the color settings have changed. + * + * @param colorSettings + * The new color settings + */ + public void colorSettingsChanged(ColorSetting[] colorSettings); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterDialog.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterDialog.java index 5e83e058fe..4dcfb2c506 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterDialog.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterDialog.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; - -/** - * The dialog for user-defined filters. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class FilterDialog extends Dialog { - - TmfFilterNode fRoot; - FilterViewer fViewer; - - /** - * Constructor. - * - * @param shell - * The shell to which this dialog is attached - */ - public FilterDialog(Shell shell) { - super(shell); - setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - @Override - protected Control createDialogArea(Composite parent) { - getShell().setText(Messages.FilterDialog_FilterDialogTitle); - getShell().setMinimumSize(getShell().computeSize(500, 200)); - Composite composite = (Composite) super.createDialogArea(parent); - - fViewer = new FilterViewer(composite, SWT.BORDER); - fViewer.setInput(fRoot); - return composite; - } - - /** - * @param filter the filter to set - */ - public void setFilter(ITmfFilterTreeNode filter) { - fRoot = new TmfFilterNode(null); - if (filter != null) { - fRoot.addChild(filter.clone()); - } - if (fViewer != null) { - fViewer.setInput(fRoot); - } - } - - /** - * @return the filter - */ - public ITmfFilterTreeNode getFilter() { - if (fRoot != null && fRoot.hasChildren()) { - return fRoot.getChild(0).clone(); - } - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +/** + * The dialog for user-defined filters. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class FilterDialog extends Dialog { + + TmfFilterNode fRoot; + FilterViewer fViewer; + + /** + * Constructor. + * + * @param shell + * The shell to which this dialog is attached + */ + public FilterDialog(Shell shell) { + super(shell); + setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + @Override + protected Control createDialogArea(Composite parent) { + getShell().setText(Messages.FilterDialog_FilterDialogTitle); + getShell().setMinimumSize(getShell().computeSize(500, 200)); + Composite composite = (Composite) super.createDialogArea(parent); + + fViewer = new FilterViewer(composite, SWT.BORDER); + fViewer.setInput(fRoot); + return composite; + } + + /** + * @param filter the filter to set + */ + public void setFilter(ITmfFilterTreeNode filter) { + fRoot = new TmfFilterNode(null); + if (filter != null) { + fRoot.addChild(filter.clone()); + } + if (fViewer != null) { + fViewer.setInput(fRoot); + } + } + + /** + * @return the filter + */ + public ITmfFilterTreeNode getFilter() { + if (fRoot != null && fRoot.hasChildren()) { + return fRoot.getChild(0).clone(); + } + return null; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java index 3356882ea2..427e8fff7c 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java @@ -1,78 +1,78 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLParser; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; -import org.xml.sax.SAXException; - -/** - * Central filter manager - * - * @version 1.0 - * @author Patrick Tasse - */ -public class FilterManager { - - private static final String SAVED_FILTERS_FILE_NAME = "saved_filters.xml"; //$NON-NLS-1$ - private static final String SAVED_FILTERS_PATH_NAME = - Activator.getDefault().getStateLocation().addTrailingSeparator().append(SAVED_FILTERS_FILE_NAME).toString(); - - private static ITmfFilterTreeNode fRoot = new TmfFilterRootNode(); - static { - try { - fRoot = new TmfFilterXMLParser(SAVED_FILTERS_PATH_NAME).getTree(); - } catch (FileNotFoundException e) { - } catch (SAXException e) { - Activator.getDefault().logError("Error parsing saved filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error parsing saved filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ - } - } - - /** - * Retrieve the currently saved filters - * - * @return The array of filters - */ - public static ITmfFilterTreeNode[] getSavedFilters() { - return fRoot.clone().getChildren(); - } - - /** - * Set the passed filters as the currently saved ones. - * - * @param filters - * The filters to save - */ - public static void setSavedFilters(ITmfFilterTreeNode[] filters) { - fRoot = new TmfFilterRootNode(); - for (ITmfFilterTreeNode filter : filters) { - fRoot.addChild(filter.clone()); - } - try { - TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot); - writerXML.saveTree(SAVED_FILTERS_PATH_NAME); - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error saving filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ - } - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLParser; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; +import org.xml.sax.SAXException; + +/** + * Central filter manager + * + * @version 1.0 + * @author Patrick Tasse + */ +public class FilterManager { + + private static final String SAVED_FILTERS_FILE_NAME = "saved_filters.xml"; //$NON-NLS-1$ + private static final String SAVED_FILTERS_PATH_NAME = + Activator.getDefault().getStateLocation().addTrailingSeparator().append(SAVED_FILTERS_FILE_NAME).toString(); + + private static ITmfFilterTreeNode fRoot = new TmfFilterRootNode(); + static { + try { + fRoot = new TmfFilterXMLParser(SAVED_FILTERS_PATH_NAME).getTree(); + } catch (FileNotFoundException e) { + } catch (SAXException e) { + Activator.getDefault().logError("Error parsing saved filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error parsing saved filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ + } + } + + /** + * Retrieve the currently saved filters + * + * @return The array of filters + */ + public static ITmfFilterTreeNode[] getSavedFilters() { + return fRoot.clone().getChildren(); + } + + /** + * Set the passed filters as the currently saved ones. + * + * @param filters + * The filters to save + */ + public static void setSavedFilters(ITmfFilterTreeNode[] filters) { + fRoot = new TmfFilterRootNode(); + for (ITmfFilterTreeNode filter : filters) { + fRoot.addChild(filter.clone()); + } + try { + TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot); + writerXML.saveTree(SAVED_FILTERS_PATH_NAME); + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error saving filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$ + } + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeContentProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeContentProvider.java index 73c758448e..9907611931 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeContentProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeContentProvider.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import java.util.ArrayList; - -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; - -/** - * This is the Content Provider of our tree - * - * @version 1.0 - * @author Yuriy Vashchuk - */ -public class FilterTreeContentProvider implements ITreeContentProvider { - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - @Override - public void dispose() { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) - */ - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getElements(java.lang.Object) - */ - @Override - public Object[] getElements(Object inputElement) { - if (inputElement instanceof ITmfFilterTreeNode) { - ArrayList result = new ArrayList(); - for(int i = 0; i < ((ITmfFilterTreeNode)inputElement).getChildrenCount(); i++) { - result.add(((ITmfFilterTreeNode)inputElement).getChild(i)); - } - - return result.toArray(); - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - @Override - public Object[] getChildren(Object parentElement) { - ArrayList result = new ArrayList(); - for(int i = 0; i < ((ITmfFilterTreeNode)parentElement).getChildrenCount(); i++) { - result.add(((ITmfFilterTreeNode)parentElement).getChild(i)); - } - return result.toArray(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - @Override - public Object getParent(Object element) { - return ((ITmfFilterTreeNode) element).getParent(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - @Override - public boolean hasChildren(Object element) { - return ((ITmfFilterTreeNode) element).hasChildren(); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import java.util.ArrayList; + +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; + +/** + * This is the Content Provider of our tree + * + * @version 1.0 + * @author Yuriy Vashchuk + */ +public class FilterTreeContentProvider implements ITreeContentProvider { + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IContentProvider#dispose() + */ + @Override + public void dispose() { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) + */ + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#getElements(java.lang.Object) + */ + @Override + public Object[] getElements(Object inputElement) { + if (inputElement instanceof ITmfFilterTreeNode) { + ArrayList result = new ArrayList(); + for(int i = 0; i < ((ITmfFilterTreeNode)inputElement).getChildrenCount(); i++) { + result.add(((ITmfFilterTreeNode)inputElement).getChild(i)); + } + + return result.toArray(); + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) + */ + @Override + public Object[] getChildren(Object parentElement) { + ArrayList result = new ArrayList(); + for(int i = 0; i < ((ITmfFilterTreeNode)parentElement).getChildrenCount(); i++) { + result.add(((ITmfFilterTreeNode)parentElement).getChild(i)); + } + return result.toArray(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) + */ + @Override + public Object getParent(Object element) { + return ((ITmfFilterTreeNode) element).getParent(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) + */ + @Override + public boolean hasChildren(Object element) { + return ((ITmfFilterTreeNode) element).hasChildren(); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeLabelProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeLabelProvider.java index 2d4095b1f3..e4d60a5574 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeLabelProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterTreeLabelProvider.java @@ -1,150 +1,150 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; -import org.eclipse.swt.graphics.Image; - -/** - * This is the Label Provider for our Filter Tree - * - * @version 1.0 - * @author Yuriy Vashchuk - */ -public class FilterTreeLabelProvider implements ILabelProvider { - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) - */ - @Override - public void addListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() - */ - @Override - public void dispose() { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String) - */ - @Override - public boolean isLabelProperty(Object element, String property) { - // TODO Auto-generated method stub - return false; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) - */ - @Override - public void removeListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) - */ - @Override - public Image getImage(Object element) { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) - */ - @Override - public String getText(Object element) { - String label = null; - - if (element instanceof TmfFilterNode) { - - TmfFilterNode node = (TmfFilterNode) element; - label = node.getNodeName() + " " + node.getFilterName(); //$NON-NLS-1$ - - } else if (element instanceof TmfFilterEventTypeNode) { - - TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) element; - label = "WITH " + node.getNodeName() + (node.getName() != null ? " " + node.getName() : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - } else if (element instanceof TmfFilterAndNode) { - - TmfFilterAndNode node = (TmfFilterAndNode) element; - label = (node.isNot() ? "NOT " : "") + node.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$ - - } else if (element instanceof TmfFilterOrNode) { - - TmfFilterOrNode node = (TmfFilterOrNode) element; - label = (node.isNot() ? "NOT " : "") + node.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$ - - } else if (element instanceof TmfFilterContainsNode) { - - TmfFilterContainsNode node = (TmfFilterContainsNode) element; - label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - node.getNodeName() + - (node.getValue() != null && node.getValue().length() > 0 ? " \"" + node.getValue() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - } else if (element instanceof TmfFilterEqualsNode) { - - TmfFilterEqualsNode node = (TmfFilterEqualsNode) element; - label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - node.getNodeName() + - (node.getValue() != null && node.getValue().length() > 0 ? " \"" + node.getValue() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - } else if (element instanceof TmfFilterMatchesNode) { - - TmfFilterMatchesNode node = (TmfFilterMatchesNode) element; - label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - node.getNodeName() + - (node.getRegex() != null && node.getRegex().length() > 0 ? " \"" + node.getRegex() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - } else if (element instanceof TmfFilterCompareNode) { - - TmfFilterCompareNode node = (TmfFilterCompareNode) element; - label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ - (node.getResult() < 0 ? "<" : (node.getResult() > 0 ? ">" : "=")) + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - (node.getValue() != null && node.getValue().length() > 0 ? - (node.getType() == Type.ALPHA ? " \"" + node.getValue() + "\"" : //$NON-NLS-1$ //$NON-NLS-2$ - (node.getType() == Type.TIMESTAMP ? " [" + node.getValue() + "]" : //$NON-NLS-1$ //$NON-NLS-2$ - " " + node.getValue())) : ""); //$NON-NLS-1$//$NON-NLS-2$ - - } - return label; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; +import org.eclipse.swt.graphics.Image; + +/** + * This is the Label Provider for our Filter Tree + * + * @version 1.0 + * @author Yuriy Vashchuk + */ +public class FilterTreeLabelProvider implements ILabelProvider { + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) + */ + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() + */ + @Override + public void dispose() { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String) + */ + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) + */ + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) + */ + @Override + public Image getImage(Object element) { + // TODO Auto-generated method stub + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) + */ + @Override + public String getText(Object element) { + String label = null; + + if (element instanceof TmfFilterNode) { + + TmfFilterNode node = (TmfFilterNode) element; + label = node.getNodeName() + " " + node.getFilterName(); //$NON-NLS-1$ + + } else if (element instanceof TmfFilterEventTypeNode) { + + TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) element; + label = "WITH " + node.getNodeName() + (node.getName() != null ? " " + node.getName() : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + } else if (element instanceof TmfFilterAndNode) { + + TmfFilterAndNode node = (TmfFilterAndNode) element; + label = (node.isNot() ? "NOT " : "") + node.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$ + + } else if (element instanceof TmfFilterOrNode) { + + TmfFilterOrNode node = (TmfFilterOrNode) element; + label = (node.isNot() ? "NOT " : "") + node.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$ + + } else if (element instanceof TmfFilterContainsNode) { + + TmfFilterContainsNode node = (TmfFilterContainsNode) element; + label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + node.getNodeName() + + (node.getValue() != null && node.getValue().length() > 0 ? " \"" + node.getValue() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + } else if (element instanceof TmfFilterEqualsNode) { + + TmfFilterEqualsNode node = (TmfFilterEqualsNode) element; + label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + node.getNodeName() + + (node.getValue() != null && node.getValue().length() > 0 ? " \"" + node.getValue() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + } else if (element instanceof TmfFilterMatchesNode) { + + TmfFilterMatchesNode node = (TmfFilterMatchesNode) element; + label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + node.getNodeName() + + (node.getRegex() != null && node.getRegex().length() > 0 ? " \"" + node.getRegex() + "\"" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + } else if (element instanceof TmfFilterCompareNode) { + + TmfFilterCompareNode node = (TmfFilterCompareNode) element; + label = (node.isNot() ? "NOT " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + (node.getField() != null ? node.getField() + " " : "") + //$NON-NLS-1$ //$NON-NLS-2$ + (node.getResult() < 0 ? "<" : (node.getResult() > 0 ? ">" : "=")) + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + (node.getValue() != null && node.getValue().length() > 0 ? + (node.getType() == Type.ALPHA ? " \"" + node.getValue() + "\"" : //$NON-NLS-1$ //$NON-NLS-2$ + (node.getType() == Type.TIMESTAMP ? " [" + node.getValue() + "]" : //$NON-NLS-1$ //$NON-NLS-2$ + " " + node.getValue())) : ""); //$NON-NLS-1$//$NON-NLS-2$ + + } + return label; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterView.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterView.java index 73fcb6be3d..f66a817a3b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterView.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterView.java @@ -1,307 +1,307 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Yuriy Vashchuk - Initial API and implementation - * based on Francois Chouinard ProjectView code. - */ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLParser; -import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; -import org.eclipse.linuxtools.tmf.ui.views.TmfView; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IActionBars; -import org.xml.sax.SAXException; - -/** - * View that contain UI to the TMF filter. - * - * @version 1.0 - * @author Yuriy Vashchuk - */ -public class FilterView extends TmfView { - - /** ID for the Filter view */ - public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.filter"; //$NON-NLS-1$ - - private static final Image SAVE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/save_button.gif"); //$NON-NLS-1$ - private static final Image ADD_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ - private static final Image DELETE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ - private static final Image IMPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/import_button.gif"); //$NON-NLS-1$ - private static final Image EXPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/export_button.gif"); //$NON-NLS-1$ - - // ------------------------------------------------------------------------ - // Main data structures - // ------------------------------------------------------------------------ - - private FilterViewer fViewer; - private final ITmfFilterTreeNode fRoot; - - private final IWorkspace fWorkspace; - - private SaveAction fSaveAction; - private AddAction fAddAction; - private DeleteAction fDeleteAction; - private ExportAction fExportAction; - private ImportAction fImportAction; - - /** - * Getter for the Filter Tree Root - * - * @return The root of builded tree - */ - public ITmfFilterTreeNode getFilterRoot() { - return fRoot; - } - - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Default Constructor - */ - public FilterView() { - super("Filter"); //$NON-NLS-1$ - - fWorkspace = ResourcesPlugin.getWorkspace(); - try { - fWorkspace.getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); - } catch (CoreException e) { - Activator.getDefault().logError("Error refreshing workspace", e); //$NON-NLS-1$ - } - - fRoot = new TmfFilterRootNode(); - for (ITmfFilterTreeNode node : FilterManager.getSavedFilters()) { - fRoot.addChild(node); - } - } - - - /** - * Refresh the tree widget - */ - public void refresh() { - fViewer.refresh(); - } - - /** - * Setter for selection - * - * @param node The node to select - */ - public void setSelection(ITmfFilterTreeNode node) { - fViewer.setSelection(node, true); - } - - // ------------------------------------------------------------------------ - // ViewPart - // ------------------------------------------------------------------------ - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(Composite) - */ - @Override - public void createPartControl(Composite parent) { - - fViewer = new FilterViewer(parent, SWT.NONE); - fViewer.setInput(fRoot); - - contributeToActionBars(); - - fViewer.addSelectionChangedListener(new ISelectionChangedListener() { - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { - fDeleteAction.setEnabled(true); - fExportAction.setEnabled(true); - } else { - fDeleteAction.setEnabled(false); - fExportAction.setEnabled(false); - } - } - }); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.part.WorkbenchPart#setFocus() - */ - @Override - public void setFocus() { - fViewer.setFocus(); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "[FilterView]"; //$NON-NLS-1$ - } - - - /** - * Builds the menu toolbar - */ - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - //fillLocalPullDown(bars.getMenuManager()); - fillLocalToolBar(bars.getToolBarManager()); - } - - - /** - * Build the popup menu - * - * @param manager The manager to build - */ - private void fillLocalToolBar(IToolBarManager manager) { - - fSaveAction = new SaveAction(); - fSaveAction.setImageDescriptor(ImageDescriptor.createFromImage(SAVE_IMAGE)); - fSaveAction.setToolTipText(Messages.FilterView_SaveActionToolTipText); - - fAddAction = new AddAction(); - fAddAction.setImageDescriptor(ImageDescriptor.createFromImage(ADD_IMAGE)); - fAddAction.setToolTipText(Messages.FilterView_AddActionToolTipText); - - fDeleteAction = new DeleteAction(); - fDeleteAction.setImageDescriptor(ImageDescriptor.createFromImage(DELETE_IMAGE)); - fDeleteAction.setToolTipText(Messages.FilterView_DeleteActionToolTipText); - fDeleteAction.setEnabled(false); - - fExportAction = new ExportAction(); - fExportAction.setImageDescriptor(ImageDescriptor.createFromImage(EXPORT_IMAGE)); - fExportAction.setToolTipText(Messages.FilterView_ExportActionToolTipText); - - fImportAction = new ImportAction(); - fImportAction.setImageDescriptor(ImageDescriptor.createFromImage(IMPORT_IMAGE)); - fImportAction.setToolTipText(Messages.FilterView_ImportActionToolTipText); - - manager.add(fSaveAction); - manager.add(new Separator()); - manager.add(fAddAction); - manager.add(fDeleteAction); - manager.add(new Separator()); - manager.add(fExportAction); - manager.add(fImportAction); - } - - private class SaveAction extends Action { - @Override - public void run() { - FilterManager.setSavedFilters(fRoot.getChildren()); - } - } - - private class AddAction extends Action { - @Override - public void run() { - - TmfFilterNode newNode = new TmfFilterNode(fRoot, ""); //$NON-NLS-1$ - refresh(); - setSelection(newNode); - } - } - - private class DeleteAction extends Action { - @Override - public void run() { - ITmfFilterTreeNode node = fViewer.getSelection(); - if (node != null) { - node.remove(); - } - refresh(); - } - } - - private class ExportAction extends Action { - @Override - public void run() { - try { - FileDialog dlg = new FileDialog(new Shell(), SWT.SAVE); - dlg.setFilterNames(new String[] {Messages.FilterView_FileDialogFilterName + " (*.filter.xml)"}); //$NON-NLS-1$ - dlg.setFilterExtensions(new String[] {"*.filter.xml"}); //$NON-NLS-1$ - - String fn = dlg.open(); - if (fn != null) { - TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot); - writerXML.saveTree(fn); - } - - } catch (ParserConfigurationException e) { - Activator.getDefault().logError("Error parsing filter xml file", e); //$NON-NLS-1$ - } - } - } - - private class ImportAction extends Action { - @Override - public void run() { - if (fViewer != null) { - ITmfFilterTreeNode root = null; - try { - FileDialog dlg = new FileDialog(new Shell(), SWT.OPEN); - dlg.setFilterNames(new String[] {Messages.FilterView_FileDialogFilterName + " (*.filter.xml)"}); //$NON-NLS-1$ - dlg.setFilterExtensions(new String[] {"*.filter.xml"}); //$NON-NLS-1$ - - TmfFilterXMLParser parserXML = null; - String fn = dlg.open(); - if (fn != null) { - parserXML = new TmfFilterXMLParser(fn); - root = parserXML.getTree(); - } - - } catch (SAXException e) { - Activator.getDefault().logError("Error importing filter xml file", e); //$NON-NLS-1$ - } catch (IOException e) { - Activator.getDefault().logError("Error importing filter xml file", e); //$NON-NLS-1$ - } - - if (root != null) { - for (ITmfFilterTreeNode node : root.getChildren()) { - if (node instanceof TmfFilterNode) { - fRoot.addChild(node); - refresh(); - fViewer.setSelection(node); - } - } - } - } - } - } - +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yuriy Vashchuk - Initial API and implementation + * based on Francois Chouinard ProjectView code. + */ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLParser; +import org.eclipse.linuxtools.tmf.core.filter.xml.TmfFilterXMLWriter; +import org.eclipse.linuxtools.tmf.ui.views.TmfView; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IActionBars; +import org.xml.sax.SAXException; + +/** + * View that contain UI to the TMF filter. + * + * @version 1.0 + * @author Yuriy Vashchuk + */ +public class FilterView extends TmfView { + + /** ID for the Filter view */ + public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.filter"; //$NON-NLS-1$ + + private static final Image SAVE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/save_button.gif"); //$NON-NLS-1$ + private static final Image ADD_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/add_button.gif"); //$NON-NLS-1$ + private static final Image DELETE_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/delete_button.gif"); //$NON-NLS-1$ + private static final Image IMPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/import_button.gif"); //$NON-NLS-1$ + private static final Image EXPORT_IMAGE = Activator.getDefault().getImageFromPath("/icons/elcl16/export_button.gif"); //$NON-NLS-1$ + + // ------------------------------------------------------------------------ + // Main data structures + // ------------------------------------------------------------------------ + + private FilterViewer fViewer; + private final ITmfFilterTreeNode fRoot; + + private final IWorkspace fWorkspace; + + private SaveAction fSaveAction; + private AddAction fAddAction; + private DeleteAction fDeleteAction; + private ExportAction fExportAction; + private ImportAction fImportAction; + + /** + * Getter for the Filter Tree Root + * + * @return The root of builded tree + */ + public ITmfFilterTreeNode getFilterRoot() { + return fRoot; + } + + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Default Constructor + */ + public FilterView() { + super("Filter"); //$NON-NLS-1$ + + fWorkspace = ResourcesPlugin.getWorkspace(); + try { + fWorkspace.getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); + } catch (CoreException e) { + Activator.getDefault().logError("Error refreshing workspace", e); //$NON-NLS-1$ + } + + fRoot = new TmfFilterRootNode(); + for (ITmfFilterTreeNode node : FilterManager.getSavedFilters()) { + fRoot.addChild(node); + } + } + + + /** + * Refresh the tree widget + */ + public void refresh() { + fViewer.refresh(); + } + + /** + * Setter for selection + * + * @param node The node to select + */ + public void setSelection(ITmfFilterTreeNode node) { + fViewer.setSelection(node, true); + } + + // ------------------------------------------------------------------------ + // ViewPart + // ------------------------------------------------------------------------ + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(Composite) + */ + @Override + public void createPartControl(Composite parent) { + + fViewer = new FilterViewer(parent, SWT.NONE); + fViewer.setInput(fRoot); + + contributeToActionBars(); + + fViewer.addSelectionChangedListener(new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { + fDeleteAction.setEnabled(true); + fExportAction.setEnabled(true); + } else { + fDeleteAction.setEnabled(false); + fExportAction.setEnabled(false); + } + } + }); + } + + /* (non-Javadoc) + * @see org.eclipse.ui.part.WorkbenchPart#setFocus() + */ + @Override + public void setFocus() { + fViewer.setFocus(); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "[FilterView]"; //$NON-NLS-1$ + } + + + /** + * Builds the menu toolbar + */ + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + //fillLocalPullDown(bars.getMenuManager()); + fillLocalToolBar(bars.getToolBarManager()); + } + + + /** + * Build the popup menu + * + * @param manager The manager to build + */ + private void fillLocalToolBar(IToolBarManager manager) { + + fSaveAction = new SaveAction(); + fSaveAction.setImageDescriptor(ImageDescriptor.createFromImage(SAVE_IMAGE)); + fSaveAction.setToolTipText(Messages.FilterView_SaveActionToolTipText); + + fAddAction = new AddAction(); + fAddAction.setImageDescriptor(ImageDescriptor.createFromImage(ADD_IMAGE)); + fAddAction.setToolTipText(Messages.FilterView_AddActionToolTipText); + + fDeleteAction = new DeleteAction(); + fDeleteAction.setImageDescriptor(ImageDescriptor.createFromImage(DELETE_IMAGE)); + fDeleteAction.setToolTipText(Messages.FilterView_DeleteActionToolTipText); + fDeleteAction.setEnabled(false); + + fExportAction = new ExportAction(); + fExportAction.setImageDescriptor(ImageDescriptor.createFromImage(EXPORT_IMAGE)); + fExportAction.setToolTipText(Messages.FilterView_ExportActionToolTipText); + + fImportAction = new ImportAction(); + fImportAction.setImageDescriptor(ImageDescriptor.createFromImage(IMPORT_IMAGE)); + fImportAction.setToolTipText(Messages.FilterView_ImportActionToolTipText); + + manager.add(fSaveAction); + manager.add(new Separator()); + manager.add(fAddAction); + manager.add(fDeleteAction); + manager.add(new Separator()); + manager.add(fExportAction); + manager.add(fImportAction); + } + + private class SaveAction extends Action { + @Override + public void run() { + FilterManager.setSavedFilters(fRoot.getChildren()); + } + } + + private class AddAction extends Action { + @Override + public void run() { + + TmfFilterNode newNode = new TmfFilterNode(fRoot, ""); //$NON-NLS-1$ + refresh(); + setSelection(newNode); + } + } + + private class DeleteAction extends Action { + @Override + public void run() { + ITmfFilterTreeNode node = fViewer.getSelection(); + if (node != null) { + node.remove(); + } + refresh(); + } + } + + private class ExportAction extends Action { + @Override + public void run() { + try { + FileDialog dlg = new FileDialog(new Shell(), SWT.SAVE); + dlg.setFilterNames(new String[] {Messages.FilterView_FileDialogFilterName + " (*.filter.xml)"}); //$NON-NLS-1$ + dlg.setFilterExtensions(new String[] {"*.filter.xml"}); //$NON-NLS-1$ + + String fn = dlg.open(); + if (fn != null) { + TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot); + writerXML.saveTree(fn); + } + + } catch (ParserConfigurationException e) { + Activator.getDefault().logError("Error parsing filter xml file", e); //$NON-NLS-1$ + } + } + } + + private class ImportAction extends Action { + @Override + public void run() { + if (fViewer != null) { + ITmfFilterTreeNode root = null; + try { + FileDialog dlg = new FileDialog(new Shell(), SWT.OPEN); + dlg.setFilterNames(new String[] {Messages.FilterView_FileDialogFilterName + " (*.filter.xml)"}); //$NON-NLS-1$ + dlg.setFilterExtensions(new String[] {"*.filter.xml"}); //$NON-NLS-1$ + + TmfFilterXMLParser parserXML = null; + String fn = dlg.open(); + if (fn != null) { + parserXML = new TmfFilterXMLParser(fn); + root = parserXML.getTree(); + } + + } catch (SAXException e) { + Activator.getDefault().logError("Error importing filter xml file", e); //$NON-NLS-1$ + } catch (IOException e) { + Activator.getDefault().logError("Error importing filter xml file", e); //$NON-NLS-1$ + } + + if (root != null) { + for (ITmfFilterTreeNode node : root.getChildren()) { + if (node instanceof TmfFilterNode) { + fRoot.addChild(node); + refresh(); + fViewer.setSelection(node); + } + } + } + } + } + } + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterViewer.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterViewer.java index 7fb527de7d..84908aec3c 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterViewer.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterViewer.java @@ -1,1105 +1,1105 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.filter; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtEvent; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlEvent; -import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.ITmfEventType; -import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; -import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterTreeNode; -import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.TreeItem; - -class FilterViewer extends Composite { - - private static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$ - private static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$ - - private TreeViewer fViewer; - private Composite fComposite; - - public FilterViewer(Composite parent, int style) { - super(parent, style); - - setLayout(new FillLayout()); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - setLayoutData(gd); - - final SashForm sash = new SashForm(this, SWT.HORIZONTAL); - - // Create the tree viewer to display the filter tree - fViewer = new TreeViewer(sash, SWT.NONE); - fViewer.setContentProvider(new FilterTreeContentProvider()); - fViewer.setLabelProvider(new FilterTreeLabelProvider()); - fViewer.setInput(new TmfFilterRootNode()); - - // Create the empty filter node properties panel - fComposite = new Composite(sash, SWT.NONE); - GridLayout gl = new GridLayout(); - gl.marginHeight = 0; - gl.marginWidth = 0; - fComposite.setLayout(gl); - - createContextMenu(); - - fViewer.addSelectionChangedListener(new ISelectionChangedListener() { - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { - // Update the filter node properties panel to the selection - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - ITmfFilterTreeNode node = (ITmfFilterTreeNode) selection.getFirstElement(); - updateFilterNodeComposite(node); - // Highlight the selection's children - highlightTreeItems(fViewer.getTree().getSelection()[0].getItems()); - } else { - updateFilterNodeComposite(null); - } - } - }); - - fViewer.getTree().addPaintListener(new PaintListener() { - @Override - public void paintControl(PaintEvent e) { - TmfFilterTreeNode root = (TmfFilterTreeNode) fViewer.getInput(); - if (root == null || root.getChildrenCount() == 0) { - e.gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); - e.gc.drawText(Messages.FilterViewer_EmptyTreeHintText, 5, 0); - } - } - }); - } - - /** - * Create the context menu for the tree viewer - */ - private void createContextMenu() { - // Adds root context menu - MenuManager menuManager = new MenuManager(); - menuManager.setRemoveAllWhenShown(true); - menuManager.addMenuListener(new IMenuListener() { - @Override - public void menuAboutToShow(IMenuManager manager) { - fillContextMenu(manager); - } - }); - - // Context - Menu contextMenu = menuManager.createContextMenu(fViewer.getTree()); - - // Publish it - fViewer.getTree().setMenu(contextMenu); - } - - /** - * Fill the context menu for the tree viewer - */ - protected void fillContextMenu(IMenuManager manager) { - final ISelection selection = fViewer.getSelection(); - ITmfFilterTreeNode filterTreeNode = null; - if (selection instanceof StructuredSelection) { - Object element = ((StructuredSelection) selection).getFirstElement(); - if (element instanceof ITmfFilterTreeNode) { - filterTreeNode = (ITmfFilterTreeNode) element; - } - } - - final ITmfFilterTreeNode selectedNode = filterTreeNode; - - if (selectedNode != null) { - - fillContextMenuForNode(selectedNode, manager); - - if (selectedNode.getValidChildren().size() > 0) { - manager.add(new Separator()); - } - - Action deleteAction = new Action() { - @Override - public void run() { - selectedNode.remove(); - fViewer.refresh(); - } - }; - deleteAction.setText(Messages.FilterViewer_DeleteActionText); - manager.add(deleteAction); - - manager.add(new Separator()); - } - - if (fViewer.getInput() instanceof TmfFilterRootNode || selectedNode == null) { - final ITmfFilterTreeNode root = (ITmfFilterTreeNode) fViewer.getInput(); - - fillContextMenuForNode(root, manager); - } - } - - /** - * Fill the context menu with the valid children of the provided node - */ - protected void fillContextMenuForNode(final ITmfFilterTreeNode node, IMenuManager manager) { - for (final String child : node.getValidChildren()) { - final Action action = new Action() { - @Override - public void run() { - ITmfFilterTreeNode newNode = null; - if (TmfFilterNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterNode(node, ""); //$NON-NLS-1$ - } else if (TmfFilterEventTypeNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterEventTypeNode(node); - } else if (TmfFilterAndNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterAndNode(node); - } else if (TmfFilterOrNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterOrNode(node); - } else if (TmfFilterContainsNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterContainsNode(node); - } else if (TmfFilterEqualsNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterEqualsNode(node); - } else if (TmfFilterMatchesNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterMatchesNode(node); - } else if (TmfFilterCompareNode.NODE_NAME.equals(child)) { - newNode = new TmfFilterCompareNode(node); - } - if (newNode != null) { - fViewer.refresh(); - fViewer.setSelection(new StructuredSelection(newNode), true); - } - } - }; - if (TmfFilterNode.NODE_NAME.equals(child)) { - action.setText(Messages.FilterViewer_NewPrefix + " " + child); //$NON-NLS-1$ - } else { - action.setText(child); - } - manager.add(action); - } - } - - /** - * Create the appropriate filter node properties composite - */ - private void updateFilterNodeComposite(ITmfFilterTreeNode node) { - for (Control control : fComposite.getChildren()) { - control.dispose(); - } - - if (node instanceof TmfFilterNode) { - new FilterNodeComposite(fComposite, (TmfFilterNode) node); - } else if (node instanceof TmfFilterEventTypeNode) { - new FilterEventTypeNodeComposite(fComposite, (TmfFilterEventTypeNode) node); - } else if (node instanceof TmfFilterAndNode) { - new FilterAndNodeComposite(fComposite, (TmfFilterAndNode) node); - } else if (node instanceof TmfFilterOrNode) { - new FilterOrNodeComposite(fComposite, (TmfFilterOrNode) node); - } else if (node instanceof TmfFilterContainsNode) { - new FilterContainsNodeComposite(fComposite, (TmfFilterContainsNode) node); - } else if (node instanceof TmfFilterEqualsNode) { - new FilterEqualsNodeComposite(fComposite, (TmfFilterEqualsNode) node); - } else if (node instanceof TmfFilterMatchesNode) { - new FilterMatchesNodeComposite(fComposite, (TmfFilterMatchesNode) node); - } else if (node instanceof TmfFilterCompareNode) { - new FilterCompareNodeComposite(fComposite, (TmfFilterCompareNode) node); - } else { - new FilterBaseNodeComposite(fComposite); - } - fComposite.layout(); - } - - /** - * Highlight the provided tree items - */ - private void highlightTreeItems(TreeItem[] items) { - resetTreeItems(fViewer.getTree().getItems()); - for (TreeItem item : items) { - item.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE)); - } - - } - - /** - * Reset the provided tree items (remove highlight) - */ - private void resetTreeItems(TreeItem[] items) { - for (TreeItem item : items) { - item.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - resetTreeItems(item.getItems()); - } - } - - public void setInput(ITmfFilterTreeNode root) { - fViewer.setInput(root); - fViewer.expandAll(); - - updateFilterNodeComposite(null); - } - - public ITmfFilterTreeNode getInput() { - return (ITmfFilterTreeNode) fViewer.getInput(); - } - - public void refresh() { - fViewer.refresh(); - } - - public void setSelection(ITmfFilterTreeNode node, boolean reveal) { - fViewer.setSelection(new StructuredSelection(node), reveal); - } - - public void setSelection(ITmfFilterTreeNode node) { - fViewer.setSelection(new StructuredSelection(node)); - } - - public ITmfFilterTreeNode getSelection() { - final ISelection selection = fViewer.getSelection(); - ITmfFilterTreeNode filterTreeNode = null; - if (selection instanceof StructuredSelection) { - Object element = ((StructuredSelection) selection).getFirstElement(); - if (element instanceof ITmfFilterTreeNode) { - filterTreeNode = (ITmfFilterTreeNode) element; - } - } - - final ITmfFilterTreeNode selectedNode = filterTreeNode; - return selectedNode; - } - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - fViewer.addSelectionChangedListener(listener); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - fViewer.removeSelectionChangedListener(listener); - } - - private class FilterBaseNodeComposite extends Composite { - - FilterBaseNodeComposite(Composite parent) { - super(parent, SWT.NONE); - setLayout(new GridLayout(2, false)); - setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - } - - protected String[] getFieldsList(ITmfFilterTreeNode node) { - ArrayList fieldsList = new ArrayList(); - while (node != null) { - if (node instanceof TmfFilterEventTypeNode) { - TmfFilterEventTypeNode eventTypeNode = (TmfFilterEventTypeNode) node; - for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { - if (ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR).equals(eventTypeNode.getEventType())) { - try { - ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); - ITmfEventType eventType = event.getType(); - if (eventType != null) { - for (String field : eventType.getRootField().getFieldNames()) { - fieldsList.add(field); - } - } - } catch (CoreException e) { - } - if (fieldsList.size() == 0) { - fieldsList.add(ITmfEvent.EVENT_FIELD_TIMESTAMP); - fieldsList.add(ITmfEvent.EVENT_FIELD_SOURCE); - fieldsList.add(ITmfEvent.EVENT_FIELD_TYPE); - fieldsList.add(ITmfEvent.EVENT_FIELD_REFERENCE); - fieldsList.add(ITmfEvent.EVENT_FIELD_CONTENT); - } - return fieldsList.toArray(new String[0]); - } - } - if (eventTypeNode.getEventType() != null && eventTypeNode.getEventType().startsWith(CustomTxtEvent.class.getCanonicalName())) { - for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { - if (eventTypeNode.getEventType().equals(CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName)) { //$NON-NLS-1$ - for (OutputColumn output : def.outputs) { - fieldsList.add(output.name); - } - return fieldsList.toArray(new String[0]); - } - } - } - if (eventTypeNode.getEventType() != null && eventTypeNode.getEventType().startsWith(CustomXmlEvent.class.getCanonicalName())) { - for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { - if (eventTypeNode.getEventType().equals(CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName)) { //$NON-NLS-1$ - for (OutputColumn output : def.outputs) { - fieldsList.add(output.name); - } - return fieldsList.toArray(new String[0]); - } - } - } - } - node = node.getParent(); - } - - fieldsList.add(Messages.FilterViewer_CommonCategory); - fieldsList.add(ITmfEvent.EVENT_FIELD_TIMESTAMP); - fieldsList.add(ITmfEvent.EVENT_FIELD_SOURCE); - fieldsList.add(ITmfEvent.EVENT_FIELD_TYPE); - fieldsList.add(ITmfEvent.EVENT_FIELD_REFERENCE); - fieldsList.add(ITmfEvent.EVENT_FIELD_CONTENT); - fieldsList.add(""); //$NON-NLS-1$ - - for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { - try { - ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); - ITmfEventType eventType = event.getType(); - if (eventType != null && eventType.getFieldNames().length > 0) { - fieldsList.add("[" + TmfTraceType.getCategoryName(ce.getAttribute(TmfTraceType.CATEGORY_ATTR)) + //$NON-NLS-1$ - " : " + ce.getAttribute(TmfTraceType.NAME_ATTR) + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - for (String field : eventType.getFieldNames()) { - fieldsList.add(field); - } - fieldsList.add(""); //$NON-NLS-1$ - } - } catch (CoreException e) { - } - } - for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { - if (def.outputs.size() > 0) { - fieldsList.add("[" + CUSTOM_TXT_CATEGORY + //$NON-NLS-1$ - " : " + def.definitionName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - for (OutputColumn output : def.outputs) { - fieldsList.add(output.name); - } - fieldsList.add(""); //$NON-NLS-1$ - } - } - for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { - if (def.outputs.size() > 0) { - fieldsList.add("[" + CUSTOM_XML_CATEGORY + //$NON-NLS-1$ - " : " + def.definitionName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - for (OutputColumn output : def.outputs) { - fieldsList.add(output.name); - } - fieldsList.add(""); //$NON-NLS-1$ - } - } - return fieldsList.toArray(new String[0]); - } - } - - private class FilterNodeComposite extends FilterBaseNodeComposite { - TmfFilterNode fNode; - Text fNameText; - - FilterNodeComposite(Composite parent, TmfFilterNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NameLabel); - - fNameText = new Text(this, SWT.BORDER); - fNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (node.getFilterName() != null && node.getFilterName().length() > 0) { - fNameText.setText(node.getFilterName()); - } else { - fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fNameText.setText(Messages.FilterViewer_FilterNameHint); - } - fNameText.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - if (fNode.getFilterName() == null || fNode.getFilterName().length() == 0) { - fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fNameText.setText(Messages.FilterViewer_FilterNameHint); - } - } - @Override - public void focusGained(FocusEvent e) { - if (fNameText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNameText.setText(""); //$NON-NLS-1$ - } - fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - } - }); - fNameText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (! fNameText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNode.setFilterName(fNameText.getText()); - fViewer.refresh(fNode); - } - } - }); - } - } - - private class FilterEventTypeNodeComposite extends FilterBaseNodeComposite { - TmfFilterEventTypeNode fNode; - Combo fTypeCombo; - Map fEventsTypeMap; - - FilterEventTypeNodeComposite(Composite parent, TmfFilterEventTypeNode node) { - super(parent); - fNode = node; - fEventsTypeMap = getEventsTypeMap(); - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_TypeLabel); - - fTypeCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY); - fTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - fTypeCombo.setItems(fEventsTypeMap.keySet().toArray(new String[0])); - if (fNode.getEventType() != null) { - for (Entry eventTypeEntry : fEventsTypeMap.entrySet()) { - Object value = eventTypeEntry.getValue(); - if (value instanceof IConfigurationElement) { - IConfigurationElement ce = (IConfigurationElement) value; - if (ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR).equals(fNode.getEventType())) { - fTypeCombo.setText(eventTypeEntry.getKey()); - } - } else if (value instanceof CustomTxtTraceDefinition) { - CustomTxtTraceDefinition def = (CustomTxtTraceDefinition) value; - String eventType = CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$ - if (eventType.equals(fNode.getEventType())) { - fTypeCombo.setText(eventTypeEntry.getKey()); - } - } else if (value instanceof CustomXmlTraceDefinition) { - CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) value; - String eventType = CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$ - if (eventType.equals(fNode.getEventType())) { - fTypeCombo.setText(eventTypeEntry.getKey()); - } - } - } - } - fTypeCombo.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - for (Entry eventTypeEntry : fEventsTypeMap.entrySet()) { - if (eventTypeEntry.getKey().equals(fTypeCombo.getText())) { - Object value = eventTypeEntry.getValue(); - if (value instanceof IConfigurationElement) { - IConfigurationElement ce = (IConfigurationElement) value; - fNode.setEventType(ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR)); - fNode.setName(ce.getAttribute(TmfTraceType.NAME_ATTR)); - } else if (value instanceof CustomTxtTraceDefinition) { - CustomTxtTraceDefinition def = (CustomTxtTraceDefinition) value; - fNode.setEventType(CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName); //$NON-NLS-1$ - fNode.setName(def.definitionName); - } else if (value instanceof CustomXmlTraceDefinition) { - CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) value; - fNode.setEventType(CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName); //$NON-NLS-1$ - fNode.setName(def.definitionName); - } - fViewer.refresh(fNode); - break; - } - } - } - }); - } - - protected Map getEventsTypeMap() { - Map eventsTypeMap = new LinkedHashMap(); - for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { - String categoryName = TmfTraceType.getCategoryName(ce.getAttribute(TmfTraceType.CATEGORY_ATTR)); - String text = categoryName + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR); //$NON-NLS-1$ - eventsTypeMap.put(text, ce); - } - for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { - String text = CUSTOM_TXT_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$ - eventsTypeMap.put(text, def); - } - for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { - String text = CUSTOM_XML_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$ - eventsTypeMap.put(text, def); - } - return eventsTypeMap; - } - } - - private class FilterAndNodeComposite extends FilterBaseNodeComposite { - TmfFilterAndNode fNode; - Button fNotButton; - - FilterAndNodeComposite(Composite parent, TmfFilterAndNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - } - } - - private class FilterOrNodeComposite extends FilterBaseNodeComposite { - TmfFilterOrNode fNode; - Button fNotButton; - - FilterOrNodeComposite(Composite parent, TmfFilterOrNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - } - } - - private class FilterContainsNodeComposite extends FilterBaseNodeComposite { - TmfFilterContainsNode fNode; - Button fNotButton; - Combo fFieldCombo; - Text fValueText; - Button fIgnoreCaseButton; - - FilterContainsNodeComposite(Composite parent, TmfFilterContainsNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_FieldLabel); - - fFieldCombo = new Combo(this, SWT.DROP_DOWN); - fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - fFieldCombo.setItems(getFieldsList(fNode)); - if (fNode.getField() != null) { - fFieldCombo.setText(fNode.getField()); - } - fFieldCombo.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - fNode.setField(fFieldCombo.getText()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_ValueLabel); - - fValueText = new Text(this, SWT.BORDER); - fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (node.getValue() != null && node.getValue().length() > 0) { - fValueText.setText(node.getValue()); - } else { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - fValueText.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - if (fNode.getValue() == null || fNode.getValue().length() == 0) { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - } - @Override - public void focusGained(FocusEvent e) { - if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fValueText.setText(""); //$NON-NLS-1$ - } - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - } - }); - fValueText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNode.setValue(fValueText.getText()); - fViewer.refresh(fNode); - } - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - - fIgnoreCaseButton = new Button(this, SWT.CHECK); - fIgnoreCaseButton.setSelection(fNode.isIgnoreCase()); - fIgnoreCaseButton.setText(Messages.FilterViewer_IgnoreCaseButtonText); - fIgnoreCaseButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fIgnoreCaseButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setIgnoreCase(fIgnoreCaseButton.getSelection()); - fViewer.refresh(fNode); - } - }); - } - } - - private class FilterEqualsNodeComposite extends FilterBaseNodeComposite { - TmfFilterEqualsNode fNode; - Button fNotButton; - Combo fFieldCombo; - Text fValueText; - Button fIgnoreCaseButton; - - FilterEqualsNodeComposite(Composite parent, TmfFilterEqualsNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_FieldLabel); - - fFieldCombo = new Combo(this, SWT.DROP_DOWN); - fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - fFieldCombo.setItems(getFieldsList(fNode)); - if (fNode.getField() != null) { - fFieldCombo.setText(fNode.getField()); - } - fFieldCombo.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - fNode.setField(fFieldCombo.getText()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_ValueLabel); - - fValueText = new Text(this, SWT.BORDER); - fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (node.getValue() != null && node.getValue().length() > 0) { - fValueText.setText(node.getValue()); - } else { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - fValueText.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - if (fNode.getValue() == null || fNode.getValue().length() == 0) { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - } - @Override - public void focusGained(FocusEvent e) { - if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fValueText.setText(""); //$NON-NLS-1$ - } - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - } - }); - fValueText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNode.setValue(fValueText.getText()); - fViewer.refresh(fNode); - } - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - - fIgnoreCaseButton = new Button(this, SWT.CHECK); - fIgnoreCaseButton.setSelection(fNode.isIgnoreCase()); - fIgnoreCaseButton.setText(Messages.FilterViewer_IgnoreCaseButtonText); - fIgnoreCaseButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fIgnoreCaseButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setIgnoreCase(fIgnoreCaseButton.getSelection()); - fViewer.refresh(fNode); - } - }); - } - } - - private class FilterMatchesNodeComposite extends FilterBaseNodeComposite { - TmfFilterMatchesNode fNode; - Button fNotButton; - Combo fFieldCombo; - Text fRegexText; - - FilterMatchesNodeComposite(Composite parent, TmfFilterMatchesNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_FieldLabel); - - fFieldCombo = new Combo(this, SWT.DROP_DOWN); - fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - fFieldCombo.setItems(getFieldsList(fNode)); - if (fNode.getField() != null) { - fFieldCombo.setText(fNode.getField()); - } - fFieldCombo.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - fNode.setField(fFieldCombo.getText()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_RegexLabel); - - fRegexText = new Text(this, SWT.BORDER); - fRegexText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (node.getRegex() != null && node.getRegex().length() > 0) { - fRegexText.setText(node.getRegex()); - } else { - fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fRegexText.setText(Messages.FilterViewer_RegexHint); - } - fRegexText.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - if (fNode.getRegex() == null || fNode.getRegex().length() == 0) { - fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fRegexText.setText(Messages.FilterViewer_RegexHint); - } - } - @Override - public void focusGained(FocusEvent e) { - if (fRegexText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fRegexText.setText(""); //$NON-NLS-1$ - } - fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - } - }); - fRegexText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (! fRegexText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNode.setRegex(fRegexText.getText()); - fViewer.refresh(fNode); - } - } - }); - } - } - - private class FilterCompareNodeComposite extends FilterBaseNodeComposite { - TmfFilterCompareNode fNode; - Button fNotButton; - Combo fFieldCombo; - Text fValueText; - Button fLTButton; - Button fEQButton; - Button fGTButton; - Button fNumButton; - Button fAlphaButton; - Button fTimestampButton; - - FilterCompareNodeComposite(Composite parent, TmfFilterCompareNode node) { - super(parent); - fNode = node; - - Label label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_NotLabel); - - fNotButton = new Button(this, SWT.CHECK); - fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNotButton.setSelection(fNode.isNot()); - fNotButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - fNode.setNot(fNotButton.getSelection()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_FieldLabel); - - fFieldCombo = new Combo(this, SWT.DROP_DOWN); - fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - fFieldCombo.setItems(getFieldsList(fNode)); - if (fNode.getField() != null) { - fFieldCombo.setText(fNode.getField()); - } - fFieldCombo.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - fNode.setField(fFieldCombo.getText()); - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_ResultLabel); - - Composite resultGroup = new Composite(this, SWT.NONE); - GridLayout rggl = new GridLayout(3, true); - rggl.marginHeight = 0; - rggl.marginWidth = 0; - resultGroup.setLayout(rggl); - resultGroup.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - - fLTButton = new Button(resultGroup, SWT.RADIO); - fLTButton.setSelection(fNode.getResult() < 0); - fLTButton.setText("<"); //$NON-NLS-1$ - fLTButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fLTButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fLTButton.getSelection()) { - fNode.setResult(-1); - } - fViewer.refresh(fNode); - } - }); - - fEQButton = new Button(resultGroup, SWT.RADIO); - fEQButton.setSelection(fNode.getResult() == 0); - fEQButton.setText("="); //$NON-NLS-1$ - fEQButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fEQButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fEQButton.getSelection()) { - fNode.setResult(0); - } - fViewer.refresh(fNode); - } - }); - - fGTButton = new Button(resultGroup, SWT.RADIO); - fGTButton.setSelection(fNode.getResult() > 0); - fGTButton.setText(">"); //$NON-NLS-1$ - fGTButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fGTButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fGTButton.getSelection()) { - fNode.setResult(1); - } - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_TypeLabel); - - Composite typeGroup = new Composite(this, SWT.NONE); - GridLayout tggl = new GridLayout(3, false); - tggl.marginHeight = 0; - tggl.marginWidth = 0; - typeGroup.setLayout(tggl); - typeGroup.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - - fNumButton = new Button(typeGroup, SWT.RADIO); - fNumButton.setSelection(fNode.getType() == Type.NUM); - fNumButton.setText(Messages.FilterViewer_NumButtonText); - fNumButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fNumButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fNumButton.getSelection()) { - fNode.setType(Type.NUM); - } - fViewer.refresh(fNode); - } - }); - - fAlphaButton = new Button(typeGroup, SWT.RADIO); - fAlphaButton.setSelection(fNode.getType() == Type.ALPHA); - fAlphaButton.setText(Messages.FilterViewer_AlphaButtonText); - fAlphaButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fAlphaButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fAlphaButton.getSelection()) { - fNode.setType(Type.ALPHA); - } - fViewer.refresh(fNode); - } - }); - - fTimestampButton = new Button(typeGroup, SWT.RADIO); - fTimestampButton.setSelection(fNode.getType() == Type.TIMESTAMP); - fTimestampButton.setText(Messages.FilterViewer_TimestampButtonText); - fTimestampButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - fTimestampButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (fTimestampButton.getSelection()) { - fNode.setType(Type.TIMESTAMP); - } - fViewer.refresh(fNode); - } - }); - - label = new Label(this, SWT.NONE); - label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - label.setText(Messages.FilterViewer_ValueLabel); - - fValueText = new Text(this, SWT.BORDER); - fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (node.getValue() != null && node.getValue().length() > 0) { - fValueText.setText(node.getValue()); - } else { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - fValueText.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - if (fNode.getValue() == null || fNode.getValue().length() == 0) { - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); - fValueText.setText(Messages.FilterViewer_ValueHint); - } - } - @Override - public void focusGained(FocusEvent e) { - if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fValueText.setText(""); //$NON-NLS-1$ - } - fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - } - }); - fValueText.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { - fNode.setValue(fValueText.getText()); - fViewer.refresh(fNode); - } - } - }); - } - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.filter; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IMenuListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTraceDefinition.OutputColumn; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtEvent; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlEvent; +import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.ITmfEventType; +import org.eclipse.linuxtools.tmf.core.filter.model.ITmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterAndNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterCompareNode.Type; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterContainsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEqualsNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterEventTypeNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterMatchesNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterOrNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterRootNode; +import org.eclipse.linuxtools.tmf.core.filter.model.TmfFilterTreeNode; +import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.TreeItem; + +class FilterViewer extends Composite { + + private static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$ + private static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$ + + private TreeViewer fViewer; + private Composite fComposite; + + public FilterViewer(Composite parent, int style) { + super(parent, style); + + setLayout(new FillLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + setLayoutData(gd); + + final SashForm sash = new SashForm(this, SWT.HORIZONTAL); + + // Create the tree viewer to display the filter tree + fViewer = new TreeViewer(sash, SWT.NONE); + fViewer.setContentProvider(new FilterTreeContentProvider()); + fViewer.setLabelProvider(new FilterTreeLabelProvider()); + fViewer.setInput(new TmfFilterRootNode()); + + // Create the empty filter node properties panel + fComposite = new Composite(sash, SWT.NONE); + GridLayout gl = new GridLayout(); + gl.marginHeight = 0; + gl.marginWidth = 0; + fComposite.setLayout(gl); + + createContextMenu(); + + fViewer.addSelectionChangedListener(new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (!(event.getSelection().isEmpty()) && event.getSelection() instanceof IStructuredSelection) { + // Update the filter node properties panel to the selection + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + ITmfFilterTreeNode node = (ITmfFilterTreeNode) selection.getFirstElement(); + updateFilterNodeComposite(node); + // Highlight the selection's children + highlightTreeItems(fViewer.getTree().getSelection()[0].getItems()); + } else { + updateFilterNodeComposite(null); + } + } + }); + + fViewer.getTree().addPaintListener(new PaintListener() { + @Override + public void paintControl(PaintEvent e) { + TmfFilterTreeNode root = (TmfFilterTreeNode) fViewer.getInput(); + if (root == null || root.getChildrenCount() == 0) { + e.gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); + e.gc.drawText(Messages.FilterViewer_EmptyTreeHintText, 5, 0); + } + } + }); + } + + /** + * Create the context menu for the tree viewer + */ + private void createContextMenu() { + // Adds root context menu + MenuManager menuManager = new MenuManager(); + menuManager.setRemoveAllWhenShown(true); + menuManager.addMenuListener(new IMenuListener() { + @Override + public void menuAboutToShow(IMenuManager manager) { + fillContextMenu(manager); + } + }); + + // Context + Menu contextMenu = menuManager.createContextMenu(fViewer.getTree()); + + // Publish it + fViewer.getTree().setMenu(contextMenu); + } + + /** + * Fill the context menu for the tree viewer + */ + protected void fillContextMenu(IMenuManager manager) { + final ISelection selection = fViewer.getSelection(); + ITmfFilterTreeNode filterTreeNode = null; + if (selection instanceof StructuredSelection) { + Object element = ((StructuredSelection) selection).getFirstElement(); + if (element instanceof ITmfFilterTreeNode) { + filterTreeNode = (ITmfFilterTreeNode) element; + } + } + + final ITmfFilterTreeNode selectedNode = filterTreeNode; + + if (selectedNode != null) { + + fillContextMenuForNode(selectedNode, manager); + + if (selectedNode.getValidChildren().size() > 0) { + manager.add(new Separator()); + } + + Action deleteAction = new Action() { + @Override + public void run() { + selectedNode.remove(); + fViewer.refresh(); + } + }; + deleteAction.setText(Messages.FilterViewer_DeleteActionText); + manager.add(deleteAction); + + manager.add(new Separator()); + } + + if (fViewer.getInput() instanceof TmfFilterRootNode || selectedNode == null) { + final ITmfFilterTreeNode root = (ITmfFilterTreeNode) fViewer.getInput(); + + fillContextMenuForNode(root, manager); + } + } + + /** + * Fill the context menu with the valid children of the provided node + */ + protected void fillContextMenuForNode(final ITmfFilterTreeNode node, IMenuManager manager) { + for (final String child : node.getValidChildren()) { + final Action action = new Action() { + @Override + public void run() { + ITmfFilterTreeNode newNode = null; + if (TmfFilterNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterNode(node, ""); //$NON-NLS-1$ + } else if (TmfFilterEventTypeNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterEventTypeNode(node); + } else if (TmfFilterAndNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterAndNode(node); + } else if (TmfFilterOrNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterOrNode(node); + } else if (TmfFilterContainsNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterContainsNode(node); + } else if (TmfFilterEqualsNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterEqualsNode(node); + } else if (TmfFilterMatchesNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterMatchesNode(node); + } else if (TmfFilterCompareNode.NODE_NAME.equals(child)) { + newNode = new TmfFilterCompareNode(node); + } + if (newNode != null) { + fViewer.refresh(); + fViewer.setSelection(new StructuredSelection(newNode), true); + } + } + }; + if (TmfFilterNode.NODE_NAME.equals(child)) { + action.setText(Messages.FilterViewer_NewPrefix + " " + child); //$NON-NLS-1$ + } else { + action.setText(child); + } + manager.add(action); + } + } + + /** + * Create the appropriate filter node properties composite + */ + private void updateFilterNodeComposite(ITmfFilterTreeNode node) { + for (Control control : fComposite.getChildren()) { + control.dispose(); + } + + if (node instanceof TmfFilterNode) { + new FilterNodeComposite(fComposite, (TmfFilterNode) node); + } else if (node instanceof TmfFilterEventTypeNode) { + new FilterEventTypeNodeComposite(fComposite, (TmfFilterEventTypeNode) node); + } else if (node instanceof TmfFilterAndNode) { + new FilterAndNodeComposite(fComposite, (TmfFilterAndNode) node); + } else if (node instanceof TmfFilterOrNode) { + new FilterOrNodeComposite(fComposite, (TmfFilterOrNode) node); + } else if (node instanceof TmfFilterContainsNode) { + new FilterContainsNodeComposite(fComposite, (TmfFilterContainsNode) node); + } else if (node instanceof TmfFilterEqualsNode) { + new FilterEqualsNodeComposite(fComposite, (TmfFilterEqualsNode) node); + } else if (node instanceof TmfFilterMatchesNode) { + new FilterMatchesNodeComposite(fComposite, (TmfFilterMatchesNode) node); + } else if (node instanceof TmfFilterCompareNode) { + new FilterCompareNodeComposite(fComposite, (TmfFilterCompareNode) node); + } else { + new FilterBaseNodeComposite(fComposite); + } + fComposite.layout(); + } + + /** + * Highlight the provided tree items + */ + private void highlightTreeItems(TreeItem[] items) { + resetTreeItems(fViewer.getTree().getItems()); + for (TreeItem item : items) { + item.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE)); + } + + } + + /** + * Reset the provided tree items (remove highlight) + */ + private void resetTreeItems(TreeItem[] items) { + for (TreeItem item : items) { + item.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + resetTreeItems(item.getItems()); + } + } + + public void setInput(ITmfFilterTreeNode root) { + fViewer.setInput(root); + fViewer.expandAll(); + + updateFilterNodeComposite(null); + } + + public ITmfFilterTreeNode getInput() { + return (ITmfFilterTreeNode) fViewer.getInput(); + } + + public void refresh() { + fViewer.refresh(); + } + + public void setSelection(ITmfFilterTreeNode node, boolean reveal) { + fViewer.setSelection(new StructuredSelection(node), reveal); + } + + public void setSelection(ITmfFilterTreeNode node) { + fViewer.setSelection(new StructuredSelection(node)); + } + + public ITmfFilterTreeNode getSelection() { + final ISelection selection = fViewer.getSelection(); + ITmfFilterTreeNode filterTreeNode = null; + if (selection instanceof StructuredSelection) { + Object element = ((StructuredSelection) selection).getFirstElement(); + if (element instanceof ITmfFilterTreeNode) { + filterTreeNode = (ITmfFilterTreeNode) element; + } + } + + final ITmfFilterTreeNode selectedNode = filterTreeNode; + return selectedNode; + } + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + fViewer.addSelectionChangedListener(listener); + } + + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + fViewer.removeSelectionChangedListener(listener); + } + + private class FilterBaseNodeComposite extends Composite { + + FilterBaseNodeComposite(Composite parent) { + super(parent, SWT.NONE); + setLayout(new GridLayout(2, false)); + setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + } + + protected String[] getFieldsList(ITmfFilterTreeNode node) { + ArrayList fieldsList = new ArrayList(); + while (node != null) { + if (node instanceof TmfFilterEventTypeNode) { + TmfFilterEventTypeNode eventTypeNode = (TmfFilterEventTypeNode) node; + for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { + if (ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR).equals(eventTypeNode.getEventType())) { + try { + ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); + ITmfEventType eventType = event.getType(); + if (eventType != null) { + for (String field : eventType.getRootField().getFieldNames()) { + fieldsList.add(field); + } + } + } catch (CoreException e) { + } + if (fieldsList.size() == 0) { + fieldsList.add(ITmfEvent.EVENT_FIELD_TIMESTAMP); + fieldsList.add(ITmfEvent.EVENT_FIELD_SOURCE); + fieldsList.add(ITmfEvent.EVENT_FIELD_TYPE); + fieldsList.add(ITmfEvent.EVENT_FIELD_REFERENCE); + fieldsList.add(ITmfEvent.EVENT_FIELD_CONTENT); + } + return fieldsList.toArray(new String[0]); + } + } + if (eventTypeNode.getEventType() != null && eventTypeNode.getEventType().startsWith(CustomTxtEvent.class.getCanonicalName())) { + for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { + if (eventTypeNode.getEventType().equals(CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName)) { //$NON-NLS-1$ + for (OutputColumn output : def.outputs) { + fieldsList.add(output.name); + } + return fieldsList.toArray(new String[0]); + } + } + } + if (eventTypeNode.getEventType() != null && eventTypeNode.getEventType().startsWith(CustomXmlEvent.class.getCanonicalName())) { + for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { + if (eventTypeNode.getEventType().equals(CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName)) { //$NON-NLS-1$ + for (OutputColumn output : def.outputs) { + fieldsList.add(output.name); + } + return fieldsList.toArray(new String[0]); + } + } + } + } + node = node.getParent(); + } + + fieldsList.add(Messages.FilterViewer_CommonCategory); + fieldsList.add(ITmfEvent.EVENT_FIELD_TIMESTAMP); + fieldsList.add(ITmfEvent.EVENT_FIELD_SOURCE); + fieldsList.add(ITmfEvent.EVENT_FIELD_TYPE); + fieldsList.add(ITmfEvent.EVENT_FIELD_REFERENCE); + fieldsList.add(ITmfEvent.EVENT_FIELD_CONTENT); + fieldsList.add(""); //$NON-NLS-1$ + + for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { + try { + ITmfEvent event = (ITmfEvent) ce.createExecutableExtension(TmfTraceType.EVENT_TYPE_ATTR); + ITmfEventType eventType = event.getType(); + if (eventType != null && eventType.getFieldNames().length > 0) { + fieldsList.add("[" + TmfTraceType.getCategoryName(ce.getAttribute(TmfTraceType.CATEGORY_ATTR)) + //$NON-NLS-1$ + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR) + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + for (String field : eventType.getFieldNames()) { + fieldsList.add(field); + } + fieldsList.add(""); //$NON-NLS-1$ + } + } catch (CoreException e) { + } + } + for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { + if (def.outputs.size() > 0) { + fieldsList.add("[" + CUSTOM_TXT_CATEGORY + //$NON-NLS-1$ + " : " + def.definitionName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + for (OutputColumn output : def.outputs) { + fieldsList.add(output.name); + } + fieldsList.add(""); //$NON-NLS-1$ + } + } + for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { + if (def.outputs.size() > 0) { + fieldsList.add("[" + CUSTOM_XML_CATEGORY + //$NON-NLS-1$ + " : " + def.definitionName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + for (OutputColumn output : def.outputs) { + fieldsList.add(output.name); + } + fieldsList.add(""); //$NON-NLS-1$ + } + } + return fieldsList.toArray(new String[0]); + } + } + + private class FilterNodeComposite extends FilterBaseNodeComposite { + TmfFilterNode fNode; + Text fNameText; + + FilterNodeComposite(Composite parent, TmfFilterNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NameLabel); + + fNameText = new Text(this, SWT.BORDER); + fNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (node.getFilterName() != null && node.getFilterName().length() > 0) { + fNameText.setText(node.getFilterName()); + } else { + fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fNameText.setText(Messages.FilterViewer_FilterNameHint); + } + fNameText.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + if (fNode.getFilterName() == null || fNode.getFilterName().length() == 0) { + fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fNameText.setText(Messages.FilterViewer_FilterNameHint); + } + } + @Override + public void focusGained(FocusEvent e) { + if (fNameText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNameText.setText(""); //$NON-NLS-1$ + } + fNameText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + } + }); + fNameText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (! fNameText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNode.setFilterName(fNameText.getText()); + fViewer.refresh(fNode); + } + } + }); + } + } + + private class FilterEventTypeNodeComposite extends FilterBaseNodeComposite { + TmfFilterEventTypeNode fNode; + Combo fTypeCombo; + Map fEventsTypeMap; + + FilterEventTypeNodeComposite(Composite parent, TmfFilterEventTypeNode node) { + super(parent); + fNode = node; + fEventsTypeMap = getEventsTypeMap(); + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_TypeLabel); + + fTypeCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY); + fTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + fTypeCombo.setItems(fEventsTypeMap.keySet().toArray(new String[0])); + if (fNode.getEventType() != null) { + for (Entry eventTypeEntry : fEventsTypeMap.entrySet()) { + Object value = eventTypeEntry.getValue(); + if (value instanceof IConfigurationElement) { + IConfigurationElement ce = (IConfigurationElement) value; + if (ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR).equals(fNode.getEventType())) { + fTypeCombo.setText(eventTypeEntry.getKey()); + } + } else if (value instanceof CustomTxtTraceDefinition) { + CustomTxtTraceDefinition def = (CustomTxtTraceDefinition) value; + String eventType = CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$ + if (eventType.equals(fNode.getEventType())) { + fTypeCombo.setText(eventTypeEntry.getKey()); + } + } else if (value instanceof CustomXmlTraceDefinition) { + CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) value; + String eventType = CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$ + if (eventType.equals(fNode.getEventType())) { + fTypeCombo.setText(eventTypeEntry.getKey()); + } + } + } + } + fTypeCombo.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + for (Entry eventTypeEntry : fEventsTypeMap.entrySet()) { + if (eventTypeEntry.getKey().equals(fTypeCombo.getText())) { + Object value = eventTypeEntry.getValue(); + if (value instanceof IConfigurationElement) { + IConfigurationElement ce = (IConfigurationElement) value; + fNode.setEventType(ce.getAttribute(TmfTraceType.EVENT_TYPE_ATTR)); + fNode.setName(ce.getAttribute(TmfTraceType.NAME_ATTR)); + } else if (value instanceof CustomTxtTraceDefinition) { + CustomTxtTraceDefinition def = (CustomTxtTraceDefinition) value; + fNode.setEventType(CustomTxtEvent.class.getCanonicalName() + ":" + def.definitionName); //$NON-NLS-1$ + fNode.setName(def.definitionName); + } else if (value instanceof CustomXmlTraceDefinition) { + CustomXmlTraceDefinition def = (CustomXmlTraceDefinition) value; + fNode.setEventType(CustomXmlEvent.class.getCanonicalName() + ":" + def.definitionName); //$NON-NLS-1$ + fNode.setName(def.definitionName); + } + fViewer.refresh(fNode); + break; + } + } + } + }); + } + + protected Map getEventsTypeMap() { + Map eventsTypeMap = new LinkedHashMap(); + for (IConfigurationElement ce : TmfTraceType.getTypeElements()) { + String categoryName = TmfTraceType.getCategoryName(ce.getAttribute(TmfTraceType.CATEGORY_ATTR)); + String text = categoryName + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR); //$NON-NLS-1$ + eventsTypeMap.put(text, ce); + } + for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { + String text = CUSTOM_TXT_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$ + eventsTypeMap.put(text, def); + } + for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { + String text = CUSTOM_XML_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$ + eventsTypeMap.put(text, def); + } + return eventsTypeMap; + } + } + + private class FilterAndNodeComposite extends FilterBaseNodeComposite { + TmfFilterAndNode fNode; + Button fNotButton; + + FilterAndNodeComposite(Composite parent, TmfFilterAndNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + } + } + + private class FilterOrNodeComposite extends FilterBaseNodeComposite { + TmfFilterOrNode fNode; + Button fNotButton; + + FilterOrNodeComposite(Composite parent, TmfFilterOrNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + } + } + + private class FilterContainsNodeComposite extends FilterBaseNodeComposite { + TmfFilterContainsNode fNode; + Button fNotButton; + Combo fFieldCombo; + Text fValueText; + Button fIgnoreCaseButton; + + FilterContainsNodeComposite(Composite parent, TmfFilterContainsNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_FieldLabel); + + fFieldCombo = new Combo(this, SWT.DROP_DOWN); + fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + fFieldCombo.setItems(getFieldsList(fNode)); + if (fNode.getField() != null) { + fFieldCombo.setText(fNode.getField()); + } + fFieldCombo.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + fNode.setField(fFieldCombo.getText()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_ValueLabel); + + fValueText = new Text(this, SWT.BORDER); + fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (node.getValue() != null && node.getValue().length() > 0) { + fValueText.setText(node.getValue()); + } else { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + fValueText.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + if (fNode.getValue() == null || fNode.getValue().length() == 0) { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + } + @Override + public void focusGained(FocusEvent e) { + if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fValueText.setText(""); //$NON-NLS-1$ + } + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + } + }); + fValueText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNode.setValue(fValueText.getText()); + fViewer.refresh(fNode); + } + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + + fIgnoreCaseButton = new Button(this, SWT.CHECK); + fIgnoreCaseButton.setSelection(fNode.isIgnoreCase()); + fIgnoreCaseButton.setText(Messages.FilterViewer_IgnoreCaseButtonText); + fIgnoreCaseButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fIgnoreCaseButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setIgnoreCase(fIgnoreCaseButton.getSelection()); + fViewer.refresh(fNode); + } + }); + } + } + + private class FilterEqualsNodeComposite extends FilterBaseNodeComposite { + TmfFilterEqualsNode fNode; + Button fNotButton; + Combo fFieldCombo; + Text fValueText; + Button fIgnoreCaseButton; + + FilterEqualsNodeComposite(Composite parent, TmfFilterEqualsNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_FieldLabel); + + fFieldCombo = new Combo(this, SWT.DROP_DOWN); + fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + fFieldCombo.setItems(getFieldsList(fNode)); + if (fNode.getField() != null) { + fFieldCombo.setText(fNode.getField()); + } + fFieldCombo.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + fNode.setField(fFieldCombo.getText()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_ValueLabel); + + fValueText = new Text(this, SWT.BORDER); + fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (node.getValue() != null && node.getValue().length() > 0) { + fValueText.setText(node.getValue()); + } else { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + fValueText.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + if (fNode.getValue() == null || fNode.getValue().length() == 0) { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + } + @Override + public void focusGained(FocusEvent e) { + if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fValueText.setText(""); //$NON-NLS-1$ + } + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + } + }); + fValueText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNode.setValue(fValueText.getText()); + fViewer.refresh(fNode); + } + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + + fIgnoreCaseButton = new Button(this, SWT.CHECK); + fIgnoreCaseButton.setSelection(fNode.isIgnoreCase()); + fIgnoreCaseButton.setText(Messages.FilterViewer_IgnoreCaseButtonText); + fIgnoreCaseButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fIgnoreCaseButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setIgnoreCase(fIgnoreCaseButton.getSelection()); + fViewer.refresh(fNode); + } + }); + } + } + + private class FilterMatchesNodeComposite extends FilterBaseNodeComposite { + TmfFilterMatchesNode fNode; + Button fNotButton; + Combo fFieldCombo; + Text fRegexText; + + FilterMatchesNodeComposite(Composite parent, TmfFilterMatchesNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_FieldLabel); + + fFieldCombo = new Combo(this, SWT.DROP_DOWN); + fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + fFieldCombo.setItems(getFieldsList(fNode)); + if (fNode.getField() != null) { + fFieldCombo.setText(fNode.getField()); + } + fFieldCombo.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + fNode.setField(fFieldCombo.getText()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_RegexLabel); + + fRegexText = new Text(this, SWT.BORDER); + fRegexText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (node.getRegex() != null && node.getRegex().length() > 0) { + fRegexText.setText(node.getRegex()); + } else { + fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fRegexText.setText(Messages.FilterViewer_RegexHint); + } + fRegexText.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + if (fNode.getRegex() == null || fNode.getRegex().length() == 0) { + fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fRegexText.setText(Messages.FilterViewer_RegexHint); + } + } + @Override + public void focusGained(FocusEvent e) { + if (fRegexText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fRegexText.setText(""); //$NON-NLS-1$ + } + fRegexText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + } + }); + fRegexText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (! fRegexText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNode.setRegex(fRegexText.getText()); + fViewer.refresh(fNode); + } + } + }); + } + } + + private class FilterCompareNodeComposite extends FilterBaseNodeComposite { + TmfFilterCompareNode fNode; + Button fNotButton; + Combo fFieldCombo; + Text fValueText; + Button fLTButton; + Button fEQButton; + Button fGTButton; + Button fNumButton; + Button fAlphaButton; + Button fTimestampButton; + + FilterCompareNodeComposite(Composite parent, TmfFilterCompareNode node) { + super(parent); + fNode = node; + + Label label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_NotLabel); + + fNotButton = new Button(this, SWT.CHECK); + fNotButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNotButton.setSelection(fNode.isNot()); + fNotButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + fNode.setNot(fNotButton.getSelection()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_FieldLabel); + + fFieldCombo = new Combo(this, SWT.DROP_DOWN); + fFieldCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + fFieldCombo.setItems(getFieldsList(fNode)); + if (fNode.getField() != null) { + fFieldCombo.setText(fNode.getField()); + } + fFieldCombo.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + fNode.setField(fFieldCombo.getText()); + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_ResultLabel); + + Composite resultGroup = new Composite(this, SWT.NONE); + GridLayout rggl = new GridLayout(3, true); + rggl.marginHeight = 0; + rggl.marginWidth = 0; + resultGroup.setLayout(rggl); + resultGroup.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + + fLTButton = new Button(resultGroup, SWT.RADIO); + fLTButton.setSelection(fNode.getResult() < 0); + fLTButton.setText("<"); //$NON-NLS-1$ + fLTButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fLTButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fLTButton.getSelection()) { + fNode.setResult(-1); + } + fViewer.refresh(fNode); + } + }); + + fEQButton = new Button(resultGroup, SWT.RADIO); + fEQButton.setSelection(fNode.getResult() == 0); + fEQButton.setText("="); //$NON-NLS-1$ + fEQButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fEQButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fEQButton.getSelection()) { + fNode.setResult(0); + } + fViewer.refresh(fNode); + } + }); + + fGTButton = new Button(resultGroup, SWT.RADIO); + fGTButton.setSelection(fNode.getResult() > 0); + fGTButton.setText(">"); //$NON-NLS-1$ + fGTButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fGTButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fGTButton.getSelection()) { + fNode.setResult(1); + } + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_TypeLabel); + + Composite typeGroup = new Composite(this, SWT.NONE); + GridLayout tggl = new GridLayout(3, false); + tggl.marginHeight = 0; + tggl.marginWidth = 0; + typeGroup.setLayout(tggl); + typeGroup.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + + fNumButton = new Button(typeGroup, SWT.RADIO); + fNumButton.setSelection(fNode.getType() == Type.NUM); + fNumButton.setText(Messages.FilterViewer_NumButtonText); + fNumButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fNumButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fNumButton.getSelection()) { + fNode.setType(Type.NUM); + } + fViewer.refresh(fNode); + } + }); + + fAlphaButton = new Button(typeGroup, SWT.RADIO); + fAlphaButton.setSelection(fNode.getType() == Type.ALPHA); + fAlphaButton.setText(Messages.FilterViewer_AlphaButtonText); + fAlphaButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fAlphaButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fAlphaButton.getSelection()) { + fNode.setType(Type.ALPHA); + } + fViewer.refresh(fNode); + } + }); + + fTimestampButton = new Button(typeGroup, SWT.RADIO); + fTimestampButton.setSelection(fNode.getType() == Type.TIMESTAMP); + fTimestampButton.setText(Messages.FilterViewer_TimestampButtonText); + fTimestampButton.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + fTimestampButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (fTimestampButton.getSelection()) { + fNode.setType(Type.TIMESTAMP); + } + fViewer.refresh(fNode); + } + }); + + label = new Label(this, SWT.NONE); + label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); + label.setText(Messages.FilterViewer_ValueLabel); + + fValueText = new Text(this, SWT.BORDER); + fValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (node.getValue() != null && node.getValue().length() > 0) { + fValueText.setText(node.getValue()); + } else { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + fValueText.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + if (fNode.getValue() == null || fNode.getValue().length() == 0) { + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); + fValueText.setText(Messages.FilterViewer_ValueHint); + } + } + @Override + public void focusGained(FocusEvent e) { + if (fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fValueText.setText(""); //$NON-NLS-1$ + } + fValueText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); + } + }); + fValueText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (! fValueText.getForeground().equals(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY))) { + fNode.setValue(fValueText.getText()); + fViewer.refresh(fNode); + } + } + }); + } + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java index b6559c5b3d..d7f05ea435 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java @@ -1,273 +1,273 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.timechart; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Vector; - -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * An entry (row) in the time chart analysis view - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeChartAnalysisEntry implements ITimeGraphEntry { - - private final ITmfTrace fTrace; - private final Vector fTraceEvents; - private int fPower = 0; // 2^fPower nanoseconds per vector position - private long fReferenceTime = -1; // time corresponding to beginning of index 0 - private long fStartTime = -1; // time of first event - private long fStopTime = -1; // time of last event - private long fLastRank = -1; // rank of last processed trace event - - TimeChartAnalysisEntry(ITmfTrace trace, int modelSize) { - fTrace = trace; - fTraceEvents = new Vector(modelSize); - } - - @Override - public ITimeGraphEntry[] getChildren() { - return null; - } - - @Override - public ITimeGraphEntry getParent() { - return null; - } - - @Override - public boolean hasChildren() { - return false; - } - - @Override - public String getName() { - return fTrace.getName(); - } - - @Override - public long getStartTime() { - return fStartTime; - } - - @Override - public long getEndTime() { - return fStopTime; - } - - @Override - public boolean hasTimeEvents() { - return true; - } - - @Override - public Iterator getTimeEventsIterator() { - return new EntryIterator(0, Long.MAX_VALUE, 0); - } - - @Override - public Iterator getTimeEventsIterator(long startTime, long stopTime, long maxDuration) { - return new EntryIterator(startTime, stopTime, maxDuration); - } - - private class EntryIterator implements Iterator { - private final long fIteratorStartTime; - private final long fIteratorStopTime; - private final long fIteratorMaxDuration; - private long lastTime = -1; - private TimeChartEvent next = null; - private Iterator nestedIterator = null; - - public EntryIterator(long startTime, long stopTime, long maxDuration) { - fIteratorStartTime = startTime; - fIteratorStopTime = stopTime; - fIteratorMaxDuration = maxDuration; - } - - @Override - public boolean hasNext() { - synchronized (fTraceEvents) { - if (next != null) { - return true; - } - if (nestedIterator != null) { - if (nestedIterator.hasNext()) { - return true; - } - nestedIterator = null; - } - long time = (lastTime == -1) ? fStartTime : lastTime; - int index = (fReferenceTime == -1) ? 0 : (int) ((time - fReferenceTime) >> fPower); - while (index < fTraceEvents.size()) { - TimeChartEvent event = fTraceEvents.get(index++); - if (event != null && (lastTime == -1 || event.getTime() > time)) { - if (event.getTime() + event.getDuration() >= fIteratorStartTime && event.getTime() <= fIteratorStopTime) { - if (event.getItemizedEntry() == null || event.getDuration() <= fIteratorMaxDuration) { - lastTime = event.getTime() + event.getDuration(); - next = event; - return true; - } - nestedIterator = event.getItemizedEntry().getTimeEventsIterator(fIteratorStartTime, fIteratorStopTime, fIteratorMaxDuration); - return nestedIterator.hasNext(); - } - } - } - return false; - } - } - - @Override - public TimeChartEvent next() { - synchronized (fTraceEvents) { - if (nestedIterator != null) { - TimeChartEvent event = (TimeChartEvent) nestedIterator.next(); - lastTime = event.getTime() + event.getDuration(); - return event; - } - if (hasNext()) { - TimeChartEvent event = next; - next = null; - return event; - } - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - } - - /** - * Add a time event to the time chart entry - * - * @param timeEvent - * The event to add - */ - public void addTraceEvent(ITimeEvent timeEvent) { - long time = timeEvent.getTime(); - synchronized (fTraceEvents) { - long index = (fReferenceTime == -1) ? 0 : (time - fReferenceTime) >> fPower; - if (index < 0) { - if (fTraceEvents.capacity() - fTraceEvents.size() < -index) { - int powershift = (-index + fTraceEvents.size() <= 2 * fTraceEvents.capacity()) ? 1 : - (int) Math.ceil(Math.log((double) (-index + fTraceEvents.size()) / fTraceEvents.capacity()) / Math.log(2)); - merge(powershift); - index = (int) ((time - fReferenceTime) >> fPower); - } - shift((int) -index); - index = 0; - fTraceEvents.set(0, (TimeChartEvent) timeEvent); - } else if (index < fTraceEvents.capacity()) { - if (index >= fTraceEvents.size()) { - fTraceEvents.setSize((int) index + 1); - } - } else { - int powershift = (index < 2 * fTraceEvents.capacity()) ? 1 : - (int) Math.ceil(Math.log((double) (index + 1) / fTraceEvents.capacity()) / Math.log(2)); - merge(powershift); - index = (int) ((time - fReferenceTime) >> fPower); - fTraceEvents.setSize((int) index + 1); - } - TimeChartEvent event = fTraceEvents.get((int) index); - if (event == null) { - fTraceEvents.set((int) index, (TimeChartEvent) timeEvent); - } else { - if (event.getItemizedEntry() == null) { - event.merge((TimeChartEvent) timeEvent); - } else { - event.mergeDecorations((TimeChartEvent) timeEvent); - event.getItemizedEntry().addTraceEvent(timeEvent); - } - } - if (fReferenceTime == -1 || time < fReferenceTime) { - fReferenceTime = (time >> fPower) << fPower; - } - if (fStartTime == -1 || time < fStartTime) { - fStartTime = time; - } - if (fStopTime == -1 || time > fStopTime) { - fStopTime = time; - } - } - } - - private void merge(int powershift) { - fPower += powershift; - fReferenceTime = (fReferenceTime >> fPower) << fPower; - int index = 0; - for (int i = 0; i < fTraceEvents.size(); i++) { - TimeChartEvent event = fTraceEvents.get(i); - if (event != null) { - index = (int) ((event.getTime() - fReferenceTime) >> fPower); - TimeChartEvent mergedEvent = fTraceEvents.get(index); - if (mergedEvent == null) { - fTraceEvents.set(index, event); - } else { - mergedEvent.merge(event); - } - if (i != index) { - fTraceEvents.set(i, null); - } - } - } - fTraceEvents.setSize(index + 1); - } - - private void shift(int indexshift) { - int oldSize = fTraceEvents.size(); - fTraceEvents.setSize(oldSize + indexshift); - for (int i = oldSize - 1; i >= 0; i--) { - fTraceEvents.set(i + indexshift, fTraceEvents.get(i)); - } - for (int i = 0; i < indexshift; i++) { - fTraceEvents.set(i, null); - } - } - - /** - * Retrieve the trace associated with this entry - * - * @return The trace object - */ - public ITmfTrace getTrace() { - return fTrace; - } - - /** - * Set the last rank of the entry - * - * @param rank - * The rank to set - */ - public void setLastRank(long rank) { - fLastRank = rank; - } - - /** - * Retrieve the last rank of the entry - * - * @return The last rank - */ - public long getLastRank() { - return fLastRank; - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.timechart; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Vector; + +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * An entry (row) in the time chart analysis view + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeChartAnalysisEntry implements ITimeGraphEntry { + + private final ITmfTrace fTrace; + private final Vector fTraceEvents; + private int fPower = 0; // 2^fPower nanoseconds per vector position + private long fReferenceTime = -1; // time corresponding to beginning of index 0 + private long fStartTime = -1; // time of first event + private long fStopTime = -1; // time of last event + private long fLastRank = -1; // rank of last processed trace event + + TimeChartAnalysisEntry(ITmfTrace trace, int modelSize) { + fTrace = trace; + fTraceEvents = new Vector(modelSize); + } + + @Override + public ITimeGraphEntry[] getChildren() { + return null; + } + + @Override + public ITimeGraphEntry getParent() { + return null; + } + + @Override + public boolean hasChildren() { + return false; + } + + @Override + public String getName() { + return fTrace.getName(); + } + + @Override + public long getStartTime() { + return fStartTime; + } + + @Override + public long getEndTime() { + return fStopTime; + } + + @Override + public boolean hasTimeEvents() { + return true; + } + + @Override + public Iterator getTimeEventsIterator() { + return new EntryIterator(0, Long.MAX_VALUE, 0); + } + + @Override + public Iterator getTimeEventsIterator(long startTime, long stopTime, long maxDuration) { + return new EntryIterator(startTime, stopTime, maxDuration); + } + + private class EntryIterator implements Iterator { + private final long fIteratorStartTime; + private final long fIteratorStopTime; + private final long fIteratorMaxDuration; + private long lastTime = -1; + private TimeChartEvent next = null; + private Iterator nestedIterator = null; + + public EntryIterator(long startTime, long stopTime, long maxDuration) { + fIteratorStartTime = startTime; + fIteratorStopTime = stopTime; + fIteratorMaxDuration = maxDuration; + } + + @Override + public boolean hasNext() { + synchronized (fTraceEvents) { + if (next != null) { + return true; + } + if (nestedIterator != null) { + if (nestedIterator.hasNext()) { + return true; + } + nestedIterator = null; + } + long time = (lastTime == -1) ? fStartTime : lastTime; + int index = (fReferenceTime == -1) ? 0 : (int) ((time - fReferenceTime) >> fPower); + while (index < fTraceEvents.size()) { + TimeChartEvent event = fTraceEvents.get(index++); + if (event != null && (lastTime == -1 || event.getTime() > time)) { + if (event.getTime() + event.getDuration() >= fIteratorStartTime && event.getTime() <= fIteratorStopTime) { + if (event.getItemizedEntry() == null || event.getDuration() <= fIteratorMaxDuration) { + lastTime = event.getTime() + event.getDuration(); + next = event; + return true; + } + nestedIterator = event.getItemizedEntry().getTimeEventsIterator(fIteratorStartTime, fIteratorStopTime, fIteratorMaxDuration); + return nestedIterator.hasNext(); + } + } + } + return false; + } + } + + @Override + public TimeChartEvent next() { + synchronized (fTraceEvents) { + if (nestedIterator != null) { + TimeChartEvent event = (TimeChartEvent) nestedIterator.next(); + lastTime = event.getTime() + event.getDuration(); + return event; + } + if (hasNext()) { + TimeChartEvent event = next; + next = null; + return event; + } + throw new NoSuchElementException(); + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + } + + /** + * Add a time event to the time chart entry + * + * @param timeEvent + * The event to add + */ + public void addTraceEvent(ITimeEvent timeEvent) { + long time = timeEvent.getTime(); + synchronized (fTraceEvents) { + long index = (fReferenceTime == -1) ? 0 : (time - fReferenceTime) >> fPower; + if (index < 0) { + if (fTraceEvents.capacity() - fTraceEvents.size() < -index) { + int powershift = (-index + fTraceEvents.size() <= 2 * fTraceEvents.capacity()) ? 1 : + (int) Math.ceil(Math.log((double) (-index + fTraceEvents.size()) / fTraceEvents.capacity()) / Math.log(2)); + merge(powershift); + index = (int) ((time - fReferenceTime) >> fPower); + } + shift((int) -index); + index = 0; + fTraceEvents.set(0, (TimeChartEvent) timeEvent); + } else if (index < fTraceEvents.capacity()) { + if (index >= fTraceEvents.size()) { + fTraceEvents.setSize((int) index + 1); + } + } else { + int powershift = (index < 2 * fTraceEvents.capacity()) ? 1 : + (int) Math.ceil(Math.log((double) (index + 1) / fTraceEvents.capacity()) / Math.log(2)); + merge(powershift); + index = (int) ((time - fReferenceTime) >> fPower); + fTraceEvents.setSize((int) index + 1); + } + TimeChartEvent event = fTraceEvents.get((int) index); + if (event == null) { + fTraceEvents.set((int) index, (TimeChartEvent) timeEvent); + } else { + if (event.getItemizedEntry() == null) { + event.merge((TimeChartEvent) timeEvent); + } else { + event.mergeDecorations((TimeChartEvent) timeEvent); + event.getItemizedEntry().addTraceEvent(timeEvent); + } + } + if (fReferenceTime == -1 || time < fReferenceTime) { + fReferenceTime = (time >> fPower) << fPower; + } + if (fStartTime == -1 || time < fStartTime) { + fStartTime = time; + } + if (fStopTime == -1 || time > fStopTime) { + fStopTime = time; + } + } + } + + private void merge(int powershift) { + fPower += powershift; + fReferenceTime = (fReferenceTime >> fPower) << fPower; + int index = 0; + for (int i = 0; i < fTraceEvents.size(); i++) { + TimeChartEvent event = fTraceEvents.get(i); + if (event != null) { + index = (int) ((event.getTime() - fReferenceTime) >> fPower); + TimeChartEvent mergedEvent = fTraceEvents.get(index); + if (mergedEvent == null) { + fTraceEvents.set(index, event); + } else { + mergedEvent.merge(event); + } + if (i != index) { + fTraceEvents.set(i, null); + } + } + } + fTraceEvents.setSize(index + 1); + } + + private void shift(int indexshift) { + int oldSize = fTraceEvents.size(); + fTraceEvents.setSize(oldSize + indexshift); + for (int i = oldSize - 1; i >= 0; i--) { + fTraceEvents.set(i + indexshift, fTraceEvents.get(i)); + } + for (int i = 0; i < indexshift; i++) { + fTraceEvents.set(i, null); + } + } + + /** + * Retrieve the trace associated with this entry + * + * @return The trace object + */ + public ITmfTrace getTrace() { + return fTrace; + } + + /** + * Set the last rank of the entry + * + * @param rank + * The rank to set + */ + public void setLastRank(long rank) { + fLastRank = rank; + } + + /** + * Retrieve the last rank of the entry + * + * @return The last rank + */ + public long getLastRank() { + return fLastRank; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisProvider.java index 2af8116ebe..6c69dabfc7 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisProvider.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.timechart; - -import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSetting; -import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Display; - -/** - * Provider for a time chart analysis view - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeChartAnalysisProvider extends TimeGraphPresentationProvider { - - private static final Color BOOKMARK_INNER_COLOR = new Color(Display.getDefault(), 115, 165, 224); - private static final Color BOOKMARK_OUTER_COLOR = new Color(Display.getDefault(), 2, 70, 140); - private static final Color SEARCH_MATCH_COLOR = new Color(Display.getDefault(), 177, 118, 14); - - private int lastX = Integer.MIN_VALUE; - private int currX = Integer.MIN_VALUE; - private int lastPriority; - private int lastBookmarkX = Integer.MIN_VALUE; - - @Override - public StateItem[] getStateTable() { - - ColorSetting[] settings = ColorSettingsManager.getColorSettings(); - StateItem[] stateItems = new StateItem[settings.length]; - for (int i = 0; i < settings.length; i++) { - stateItems[i] = new StateItem(settings[i].getTickColorRGB()); - } - return stateItems; - } - - @Override - public int getStateTableIndex(ITimeEvent event) { - int priority = ((TimeChartEvent) event).getColorSettingPriority(); - if (currX == lastX) { - priority = Math.min(priority, lastPriority); - } - lastPriority = priority; - return priority; - } - - @Override - public void postDrawEvent(ITimeEvent event, Rectangle rect, GC gc) { - if (! ((TimeChartEvent) event).isVisible()) { - return; - } - lastX = currX; - currX = rect.x; - if (lastBookmarkX == rect.x || ((TimeChartEvent) event).isBookmarked()) { - drawBookmark(rect, gc); - lastBookmarkX = rect.x; - } else if (lastBookmarkX == rect.x - 1) { - Rectangle r = new Rectangle(lastBookmarkX, rect.y, rect.width, rect.height); - drawBookmark(r, gc); - } else { - lastBookmarkX = Integer.MIN_VALUE; - } - if (((TimeChartEvent) event).isSearchMatch()) { - drawSearchMatch(rect, gc); - } - } - - private static void drawBookmark(Rectangle r, GC gc) { - gc.setForeground(BOOKMARK_OUTER_COLOR); - gc.drawLine(r.x - 1, r.y - 2, r.x - 1, r.y + 2); - gc.drawLine(r.x + 1, r.y - 2, r.x + 1, r.y + 2); - gc.drawPoint(r.x, r.y - 2); - gc.setForeground(BOOKMARK_INNER_COLOR); - gc.drawLine(r.x, r.y - 1, r.x, r.y + 1); - gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); - gc.drawPoint(r.x - 1, r.y + 3); - gc.drawPoint(r.x, r.y + 2); - gc.drawPoint(r.x + 1, r.y + 3); - } - - private static void drawSearchMatch(Rectangle r, GC gc) { - gc.setForeground(SEARCH_MATCH_COLOR); - gc.drawPoint(r.x, r.y + r.height); - gc.drawLine(r.x - 1, r.y + r.height + 1, r.x + 1, r.y + r.height + 1); - gc.drawLine(r.x - 2, r.y + r.height + 2, r.x + 2, r.y + r.height + 2); - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.timechart; + +import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSetting; +import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Display; + +/** + * Provider for a time chart analysis view + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeChartAnalysisProvider extends TimeGraphPresentationProvider { + + private static final Color BOOKMARK_INNER_COLOR = new Color(Display.getDefault(), 115, 165, 224); + private static final Color BOOKMARK_OUTER_COLOR = new Color(Display.getDefault(), 2, 70, 140); + private static final Color SEARCH_MATCH_COLOR = new Color(Display.getDefault(), 177, 118, 14); + + private int lastX = Integer.MIN_VALUE; + private int currX = Integer.MIN_VALUE; + private int lastPriority; + private int lastBookmarkX = Integer.MIN_VALUE; + + @Override + public StateItem[] getStateTable() { + + ColorSetting[] settings = ColorSettingsManager.getColorSettings(); + StateItem[] stateItems = new StateItem[settings.length]; + for (int i = 0; i < settings.length; i++) { + stateItems[i] = new StateItem(settings[i].getTickColorRGB()); + } + return stateItems; + } + + @Override + public int getStateTableIndex(ITimeEvent event) { + int priority = ((TimeChartEvent) event).getColorSettingPriority(); + if (currX == lastX) { + priority = Math.min(priority, lastPriority); + } + lastPriority = priority; + return priority; + } + + @Override + public void postDrawEvent(ITimeEvent event, Rectangle rect, GC gc) { + if (! ((TimeChartEvent) event).isVisible()) { + return; + } + lastX = currX; + currX = rect.x; + if (lastBookmarkX == rect.x || ((TimeChartEvent) event).isBookmarked()) { + drawBookmark(rect, gc); + lastBookmarkX = rect.x; + } else if (lastBookmarkX == rect.x - 1) { + Rectangle r = new Rectangle(lastBookmarkX, rect.y, rect.width, rect.height); + drawBookmark(r, gc); + } else { + lastBookmarkX = Integer.MIN_VALUE; + } + if (((TimeChartEvent) event).isSearchMatch()) { + drawSearchMatch(rect, gc); + } + } + + private static void drawBookmark(Rectangle r, GC gc) { + gc.setForeground(BOOKMARK_OUTER_COLOR); + gc.drawLine(r.x - 1, r.y - 2, r.x - 1, r.y + 2); + gc.drawLine(r.x + 1, r.y - 2, r.x + 1, r.y + 2); + gc.drawPoint(r.x, r.y - 2); + gc.setForeground(BOOKMARK_INNER_COLOR); + gc.drawLine(r.x, r.y - 1, r.x, r.y + 1); + gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); + gc.drawPoint(r.x - 1, r.y + 3); + gc.drawPoint(r.x, r.y + 2); + gc.drawPoint(r.x + 1, r.y + 3); + } + + private static void drawSearchMatch(Rectangle r, GC gc) { + gc.setForeground(SEARCH_MATCH_COLOR); + gc.drawPoint(r.x, r.y + r.height); + gc.drawLine(r.x - 1, r.y + r.height + 1, r.x + 1, r.y + r.height + 1); + gc.drawLine(r.x - 2, r.y + r.height + 2, r.x + 2, r.y + r.height + 2); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java index 7ff3d58956..7c2c9e391e 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java @@ -1,138 +1,138 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.timechart; - -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; - -/** - * Provider for decorations in the time chart view - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeChartDecorationProvider { - - private final IFile fBookmarksFile; - private final Set fBookmarksSet = new HashSet(); - private ITmfFilter fFilterFilter; - private ITmfFilter fSearchFilter; - - /** - * Constructor - * - * @param bookmarksFile - * Bookmark file associated with the trace - */ - public TimeChartDecorationProvider(IFile bookmarksFile) { - fBookmarksFile = bookmarksFile; - refreshBookmarks(); - } - - /** - * Retrieve the bookmark file that was assigned to this provider - * - * @return The bookmark file - */ - public IFile getBookmarksFile() { - return fBookmarksFile; - } - - /** - * Verify if the selected rank has a bookmark assigned to it. - * - * @param rank - * The rank to check for - * @return If there is a bookmark there - */ - public boolean isBookmark(long rank) { - return fBookmarksSet.contains(rank); - } - - /** - * Refresh the bookmark display. - */ - public void refreshBookmarks() { - try { - fBookmarksSet.clear(); - for (IMarker bookmark : fBookmarksFile.findMarkers( - IMarker.BOOKMARK, false, IResource.DEPTH_ZERO)) { - int location = bookmark.getAttribute(IMarker.LOCATION, -1); - if (location != -1) { - Long rank = (long) location; - fBookmarksSet.add(rank); - } - } - } catch (CoreException e) { - Activator.getDefault().logError("Error refreshing bookmarks", e); //$NON-NLS-1$ - } - } - - /** - * Notify that a filter is now applied on the view. - * - * @param filter - * The filter that was applied - */ - public void filterApplied(ITmfFilter filter) { - fFilterFilter = filter; - } - - /** - * Check if an event is currently visible in the view or not. - * - * @param event - * The event to check for - * @return If the event is visible or not - */ - public boolean isVisible(ITmfEvent event) { - if (fFilterFilter != null) { - return fFilterFilter.matches(event); - } - return true; - } - - /** - * Notify that a search is applied on the view. - * - * @param filter - * The search filter that was applied - */ - public void searchApplied(ITmfFilter filter) { - fSearchFilter = filter; - } - - /** - * Verify if the currently active search filter applies to the given event - * or not. - * - * @param event - * The event to check for - * @return If the event matches - */ - public boolean isSearchMatch(ITmfEvent event) { - if (fSearchFilter != null) { - return fSearchFilter.matches(event); - } - return false; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.timechart; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; + +/** + * Provider for decorations in the time chart view + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeChartDecorationProvider { + + private final IFile fBookmarksFile; + private final Set fBookmarksSet = new HashSet(); + private ITmfFilter fFilterFilter; + private ITmfFilter fSearchFilter; + + /** + * Constructor + * + * @param bookmarksFile + * Bookmark file associated with the trace + */ + public TimeChartDecorationProvider(IFile bookmarksFile) { + fBookmarksFile = bookmarksFile; + refreshBookmarks(); + } + + /** + * Retrieve the bookmark file that was assigned to this provider + * + * @return The bookmark file + */ + public IFile getBookmarksFile() { + return fBookmarksFile; + } + + /** + * Verify if the selected rank has a bookmark assigned to it. + * + * @param rank + * The rank to check for + * @return If there is a bookmark there + */ + public boolean isBookmark(long rank) { + return fBookmarksSet.contains(rank); + } + + /** + * Refresh the bookmark display. + */ + public void refreshBookmarks() { + try { + fBookmarksSet.clear(); + for (IMarker bookmark : fBookmarksFile.findMarkers( + IMarker.BOOKMARK, false, IResource.DEPTH_ZERO)) { + int location = bookmark.getAttribute(IMarker.LOCATION, -1); + if (location != -1) { + Long rank = (long) location; + fBookmarksSet.add(rank); + } + } + } catch (CoreException e) { + Activator.getDefault().logError("Error refreshing bookmarks", e); //$NON-NLS-1$ + } + } + + /** + * Notify that a filter is now applied on the view. + * + * @param filter + * The filter that was applied + */ + public void filterApplied(ITmfFilter filter) { + fFilterFilter = filter; + } + + /** + * Check if an event is currently visible in the view or not. + * + * @param event + * The event to check for + * @return If the event is visible or not + */ + public boolean isVisible(ITmfEvent event) { + if (fFilterFilter != null) { + return fFilterFilter.matches(event); + } + return true; + } + + /** + * Notify that a search is applied on the view. + * + * @param filter + * The search filter that was applied + */ + public void searchApplied(ITmfFilter filter) { + fSearchFilter = filter; + } + + /** + * Verify if the currently active search filter applies to the given event + * or not. + * + * @param event + * The event to check for + * @return If the event matches + */ + public boolean isSearchMatch(ITmfEvent event) { + if (fSearchFilter != null) { + return fSearchFilter.matches(event); + } + return false; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java index 86a92a8772..3b4385dc2a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java @@ -1,375 +1,375 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.timechart; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * Event in the time chart view - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeChartEvent implements ITimeEvent { - - private static final byte TIMESTAMP_SCALE = -9; - - private final TimeChartAnalysisEntry fParentEntry; - private long fTime; - private long fDuration; - private long fFirstRank; - private long fLastRank; - private final RankRangeList fRankRangeList; - private long fNbEvents; - private int fColorSettingPriority; - private boolean fIsBookmark; - private boolean fIsVisible; - private boolean fIsSearchMatch; - private TimeChartAnalysisEntry fItemizedEntry; - private boolean fItemizing; - - /** - * Standard constructor - * - * @param parentEntry - * The parent entry - * @param event - * The event from which this time chart event originates - * @param rank - * The rank of the event in the trace - * @param decorationProvider - * The decoration provider to use - */ - public TimeChartEvent(TimeChartAnalysisEntry parentEntry, ITmfEvent event, - long rank, TimeChartDecorationProvider decorationProvider) { - fParentEntry = parentEntry; - fTime = event.getTimestamp().normalize(0, TIMESTAMP_SCALE).getValue(); - fDuration = 0; - fFirstRank = fLastRank = rank; - fRankRangeList = new RankRangeList(rank); - fNbEvents = 1; - fColorSettingPriority = ColorSettingsManager.getColorSettingPriority(event); - fIsBookmark = decorationProvider.isBookmark(rank); - fIsVisible = decorationProvider.isVisible(event); - fIsSearchMatch = decorationProvider.isSearchMatch(event); - } - - @Override - public ITimeGraphEntry getEntry() { - return fParentEntry; - } - - @Override - public long getTime() { - return fTime; - } - - @Override - public long getDuration() { - return fDuration; - } - - /** - * Retrieve the rank of the trace event which started this time event. - * - * @return The rank of the beginning - */ - public long getFirstRank() { - return fFirstRank; - } - - /** - * Retrieve the rank of the trace event which *finished* this time event. - * - * @return The rank of the end - */ - public long getLastRank() { - return fLastRank; - } - - /** - * Get the list of rank ranges corresponding to this time event. - * - * @return The rank range list - */ - public RankRangeList getRankRangeList() { - return fRankRangeList; - } - - /** - * Merge another time event with this one. - * - * @param event - * The other event - */ - public void merge(TimeChartEvent event) { - mergeDecorations(event); - if (fTime == event.getTime() && fDuration == event.getDuration()) { - return; - } - long endTime = Math.max(fTime + fDuration, event.getTime() + event.getDuration()); - fTime = Math.min(fTime, event.getTime()); - fDuration = endTime - fTime; - fFirstRank = Math.min(fFirstRank, event.fFirstRank); - fLastRank = Math.max(fLastRank, event.fLastRank); - fNbEvents += event.fNbEvents; - fItemizedEntry = null; - synchronized (fRankRangeList) { - fRankRangeList.merge(event.getRankRangeList()); - } - } - - /** - * Merge the decorations of another time event with the decorations of this - * one. - * - * @param event - * The other event - */ - public void mergeDecorations(TimeChartEvent event) { - fColorSettingPriority = Math.min(fColorSettingPriority, event.getColorSettingPriority()); - fIsBookmark |= event.fIsBookmark; - fIsVisible |= event.fIsVisible; - fIsSearchMatch |= event.fIsSearchMatch; - } - - /** - * Get the number of time events that have been merged with this one (starts - * counting at 1 if no merge happened). - * - * @return The current number of events in the bath - */ - public long getNbEvents() { - return fNbEvents; - } - - /** - * Retrieve the color setting priority. - * - * @return The priority - */ - public int getColorSettingPriority() { - return fColorSettingPriority; - } - - /** - * Set the color setting priority. - * - * @param priority - * The priority to set - */ - public void setColorSettingPriority(int priority) { - fColorSettingPriority = priority; - } - - /** - * Check if this time event is bookmarked - * - * @return Y/N - */ - public boolean isBookmarked() { - return fIsBookmark; - } - - /** - * Set this time event to be bookmarked or not. - * - * @param isBookmarked - * Should time time event become a bookmark, or not - */ - public void setIsBookmarked(boolean isBookmarked) { - fIsBookmark = isBookmarked; - } - - /** - * Check if this time is currently visible or not. - * - * @return If the event is visible - */ - public boolean isVisible() { - return fIsVisible; - } - - /** - * Set this time event to visible (or to non-visible). - * - * @param isVisible The new status - */ - public void setIsVisible(boolean isVisible) { - fIsVisible = isVisible; - } - - /** - * Check if the time event matches the current search. - * - * @return If it matches, Y/N - */ - public boolean isSearchMatch() { - return fIsSearchMatch; - } - - /** - * Mark this event as matching (or non-matching) the current search. - * - * @param isSearchMatch - * The new matching status - */ - public void setIsSearchMatch(boolean isSearchMatch) { - fIsSearchMatch = isSearchMatch; - } - - /** - * Set this event's itemized entry. - * - * @param timeAnalysisEntry - * The entry to set - */ - public void setItemizedEntry(TimeChartAnalysisEntry timeAnalysisEntry) { - fItemizedEntry = timeAnalysisEntry; - } - - /** - * Retrieve this event's itemized entry. - * - * @return The itemized entry that was previously set - */ - public TimeChartAnalysisEntry getItemizedEntry() { - return fItemizedEntry; - } - - /** - * @return Has this time event been set to itemizing? - */ - public boolean isItemizing() { - return fItemizing; - } - - /** - * Set this event's itemizing flag to true or false. - * - * @param itemizing - * The new value - */ - public void setItemizing(boolean itemizing) { - fItemizing = itemizing; - } - - /** - * Inner class to define a range in terms of ranks in the trace. - * - * @version 1.0 - * @author Patrick Tasse - */ - public class RankRange { - private long firstRank; - private long lastRank; - - /** - * Standard constructor - * - * @param firstRank - * The first (earliest) rank of the range - * @param lastRank - * The last (latest) rank of the range - */ - public RankRange(long firstRank, long lastRank) { - this.firstRank = firstRank; - this.lastRank = lastRank; - } - - /** - * Retrieve the start rank of this range. - * - * @return The first rank - */ - public long getFirstRank() { - return firstRank; - } - - /** - * Retrieve the end rank of this range - * - * @return The end rank - */ - public long getLastRank() { - return lastRank; - } - - /** - * Calculate the minimal distance between two RankRange's - * - * @param range - * The other range - * @return The distance, in "number of events" between the two ranges - */ - public long distanceFrom(RankRange range) { - if (range.lastRank < fFirstRank) { - return fFirstRank - range.lastRank; - } else if (range.firstRank > fLastRank) { - return range.firstRank - fLastRank; - } else { - return 0; - } - } - - @Override - public String toString() { - return "["+firstRank+","+lastRank+"]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - private class RankRangeList extends ArrayList { - - private static final long serialVersionUID = 6060485531208535986L; - - public RankRangeList(long rank) { - super(1); - add(new RankRange(rank, rank)); - } - - public void merge(RankRangeList rankRangeList) { - long threshold = fParentEntry.getTrace().getCacheSize(); - for (RankRange newRange : rankRangeList) { - boolean merged = false; - for (RankRange oldRange : fRankRangeList) { - if (newRange.distanceFrom(oldRange) <= threshold) { - oldRange.firstRank = Math.min(oldRange.firstRank, newRange.firstRank); - oldRange.lastRank = Math.max(oldRange.lastRank, newRange.lastRank); - merged = true; - break; - } - } - if (!merged) { - add(newRange); - } - } - Iterator iterator = fRankRangeList.iterator(); - RankRange previous = null; - while (iterator.hasNext()) { - RankRange range = iterator.next(); - if (previous != null && range.distanceFrom(previous) <= threshold) { - previous.firstRank = Math.min(previous.firstRank, range.firstRank); - previous.lastRank = Math.max(previous.lastRank, range.lastRank); - iterator.remove(); - } - previous = range; - } - } - } -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.timechart; + +import java.util.ArrayList; +import java.util.Iterator; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * Event in the time chart view + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeChartEvent implements ITimeEvent { + + private static final byte TIMESTAMP_SCALE = -9; + + private final TimeChartAnalysisEntry fParentEntry; + private long fTime; + private long fDuration; + private long fFirstRank; + private long fLastRank; + private final RankRangeList fRankRangeList; + private long fNbEvents; + private int fColorSettingPriority; + private boolean fIsBookmark; + private boolean fIsVisible; + private boolean fIsSearchMatch; + private TimeChartAnalysisEntry fItemizedEntry; + private boolean fItemizing; + + /** + * Standard constructor + * + * @param parentEntry + * The parent entry + * @param event + * The event from which this time chart event originates + * @param rank + * The rank of the event in the trace + * @param decorationProvider + * The decoration provider to use + */ + public TimeChartEvent(TimeChartAnalysisEntry parentEntry, ITmfEvent event, + long rank, TimeChartDecorationProvider decorationProvider) { + fParentEntry = parentEntry; + fTime = event.getTimestamp().normalize(0, TIMESTAMP_SCALE).getValue(); + fDuration = 0; + fFirstRank = fLastRank = rank; + fRankRangeList = new RankRangeList(rank); + fNbEvents = 1; + fColorSettingPriority = ColorSettingsManager.getColorSettingPriority(event); + fIsBookmark = decorationProvider.isBookmark(rank); + fIsVisible = decorationProvider.isVisible(event); + fIsSearchMatch = decorationProvider.isSearchMatch(event); + } + + @Override + public ITimeGraphEntry getEntry() { + return fParentEntry; + } + + @Override + public long getTime() { + return fTime; + } + + @Override + public long getDuration() { + return fDuration; + } + + /** + * Retrieve the rank of the trace event which started this time event. + * + * @return The rank of the beginning + */ + public long getFirstRank() { + return fFirstRank; + } + + /** + * Retrieve the rank of the trace event which *finished* this time event. + * + * @return The rank of the end + */ + public long getLastRank() { + return fLastRank; + } + + /** + * Get the list of rank ranges corresponding to this time event. + * + * @return The rank range list + */ + public RankRangeList getRankRangeList() { + return fRankRangeList; + } + + /** + * Merge another time event with this one. + * + * @param event + * The other event + */ + public void merge(TimeChartEvent event) { + mergeDecorations(event); + if (fTime == event.getTime() && fDuration == event.getDuration()) { + return; + } + long endTime = Math.max(fTime + fDuration, event.getTime() + event.getDuration()); + fTime = Math.min(fTime, event.getTime()); + fDuration = endTime - fTime; + fFirstRank = Math.min(fFirstRank, event.fFirstRank); + fLastRank = Math.max(fLastRank, event.fLastRank); + fNbEvents += event.fNbEvents; + fItemizedEntry = null; + synchronized (fRankRangeList) { + fRankRangeList.merge(event.getRankRangeList()); + } + } + + /** + * Merge the decorations of another time event with the decorations of this + * one. + * + * @param event + * The other event + */ + public void mergeDecorations(TimeChartEvent event) { + fColorSettingPriority = Math.min(fColorSettingPriority, event.getColorSettingPriority()); + fIsBookmark |= event.fIsBookmark; + fIsVisible |= event.fIsVisible; + fIsSearchMatch |= event.fIsSearchMatch; + } + + /** + * Get the number of time events that have been merged with this one (starts + * counting at 1 if no merge happened). + * + * @return The current number of events in the bath + */ + public long getNbEvents() { + return fNbEvents; + } + + /** + * Retrieve the color setting priority. + * + * @return The priority + */ + public int getColorSettingPriority() { + return fColorSettingPriority; + } + + /** + * Set the color setting priority. + * + * @param priority + * The priority to set + */ + public void setColorSettingPriority(int priority) { + fColorSettingPriority = priority; + } + + /** + * Check if this time event is bookmarked + * + * @return Y/N + */ + public boolean isBookmarked() { + return fIsBookmark; + } + + /** + * Set this time event to be bookmarked or not. + * + * @param isBookmarked + * Should time time event become a bookmark, or not + */ + public void setIsBookmarked(boolean isBookmarked) { + fIsBookmark = isBookmarked; + } + + /** + * Check if this time is currently visible or not. + * + * @return If the event is visible + */ + public boolean isVisible() { + return fIsVisible; + } + + /** + * Set this time event to visible (or to non-visible). + * + * @param isVisible The new status + */ + public void setIsVisible(boolean isVisible) { + fIsVisible = isVisible; + } + + /** + * Check if the time event matches the current search. + * + * @return If it matches, Y/N + */ + public boolean isSearchMatch() { + return fIsSearchMatch; + } + + /** + * Mark this event as matching (or non-matching) the current search. + * + * @param isSearchMatch + * The new matching status + */ + public void setIsSearchMatch(boolean isSearchMatch) { + fIsSearchMatch = isSearchMatch; + } + + /** + * Set this event's itemized entry. + * + * @param timeAnalysisEntry + * The entry to set + */ + public void setItemizedEntry(TimeChartAnalysisEntry timeAnalysisEntry) { + fItemizedEntry = timeAnalysisEntry; + } + + /** + * Retrieve this event's itemized entry. + * + * @return The itemized entry that was previously set + */ + public TimeChartAnalysisEntry getItemizedEntry() { + return fItemizedEntry; + } + + /** + * @return Has this time event been set to itemizing? + */ + public boolean isItemizing() { + return fItemizing; + } + + /** + * Set this event's itemizing flag to true or false. + * + * @param itemizing + * The new value + */ + public void setItemizing(boolean itemizing) { + fItemizing = itemizing; + } + + /** + * Inner class to define a range in terms of ranks in the trace. + * + * @version 1.0 + * @author Patrick Tasse + */ + public class RankRange { + private long firstRank; + private long lastRank; + + /** + * Standard constructor + * + * @param firstRank + * The first (earliest) rank of the range + * @param lastRank + * The last (latest) rank of the range + */ + public RankRange(long firstRank, long lastRank) { + this.firstRank = firstRank; + this.lastRank = lastRank; + } + + /** + * Retrieve the start rank of this range. + * + * @return The first rank + */ + public long getFirstRank() { + return firstRank; + } + + /** + * Retrieve the end rank of this range + * + * @return The end rank + */ + public long getLastRank() { + return lastRank; + } + + /** + * Calculate the minimal distance between two RankRange's + * + * @param range + * The other range + * @return The distance, in "number of events" between the two ranges + */ + public long distanceFrom(RankRange range) { + if (range.lastRank < fFirstRank) { + return fFirstRank - range.lastRank; + } else if (range.firstRank > fLastRank) { + return range.firstRank - fLastRank; + } else { + return 0; + } + } + + @Override + public String toString() { + return "["+firstRank+","+lastRank+"]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + + private class RankRangeList extends ArrayList { + + private static final long serialVersionUID = 6060485531208535986L; + + public RankRangeList(long rank) { + super(1); + add(new RankRange(rank, rank)); + } + + public void merge(RankRangeList rankRangeList) { + long threshold = fParentEntry.getTrace().getCacheSize(); + for (RankRange newRange : rankRangeList) { + boolean merged = false; + for (RankRange oldRange : fRankRangeList) { + if (newRange.distanceFrom(oldRange) <= threshold) { + oldRange.firstRank = Math.min(oldRange.firstRank, newRange.firstRank); + oldRange.lastRank = Math.max(oldRange.lastRank, newRange.lastRank); + merged = true; + break; + } + } + if (!merged) { + add(newRange); + } + } + Iterator iterator = fRankRangeList.iterator(); + RankRange previous = null; + while (iterator.hasNext()) { + RankRange range = iterator.next(); + if (previous != null && range.distanceFrom(previous) <= threshold) { + previous.firstRank = Math.min(previous.firstRank, range.firstRank); + previous.lastRank = Math.max(previous.lastRank, range.lastRank); + iterator.remove(); + } + previous = range; + } + } + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartView.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartView.java index 69e2899bd1..1b4423ebdd 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartView.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartView.java @@ -1,700 +1,700 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.views.timechart; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IMarkerDelta; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; -import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; -import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; -import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfTraceSelectedSignal; -import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal; -import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.linuxtools.tmf.ui.editors.ITmfTraceEditor; -import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceClosedSignal; -import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceOpenedSignal; -import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterListener; -import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; -import org.eclipse.linuxtools.tmf.ui.views.TmfView; -import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSetting; -import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; -import org.eclipse.linuxtools.tmf.ui.views.colors.IColorSettingsListener; -import org.eclipse.linuxtools.tmf.ui.views.timechart.TimeChartEvent.RankRange; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphSelectionListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphSelectionEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphViewer; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorReference; - -/** - * Generic Time Chart view, which is similar to a Gantt chart for trace analysis - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeChartView extends TmfView implements ITimeGraphRangeListener, - ITimeGraphSelectionListener, ITimeGraphTimeListener, - IColorSettingsListener, IResourceChangeListener, - ITmfEventsFilterListener { - - /** TimeChartView's ID */ - public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.timechart"; //$NON-NLS-1$ - - private static final int TIMESTAMP_SCALE = -9; - - private final int fDisplayWidth; - private TimeGraphViewer fViewer; - private final ArrayList fTimeAnalysisEntries = new ArrayList(); - private final Map, TimeChartDecorationProvider> fDecorationProviders = new HashMap, TimeChartDecorationProvider>(); - private ArrayList fDecorateThreads; - private long fStartTime = 0; - private long fStopTime = Long.MAX_VALUE; - private boolean fRefreshBusy = false; - private boolean fRefreshPending = false; - private boolean fRedrawBusy = false; - private boolean fRedrawPending = false; - private final Object fSyncObj = new Object(); - private ITimeGraphPresentationProvider fPresentationProvider; - - /** - * Default constructor - */ - public TimeChartView() { - super("Time Chart"); //$NON-NLS-1$ - fDisplayWidth = Display.getDefault().getBounds().width; - } - - @Override - public void createPartControl(Composite parent) { - fViewer = new TimeGraphViewer(parent, SWT.NONE); - fPresentationProvider = new TimeChartAnalysisProvider(); - fViewer.setTimeGraphProvider(fPresentationProvider); - fViewer.setTimeCalendarFormat(true); - fViewer.addTimeListener(this); - fViewer.addRangeListener(this); - fViewer.addSelectionListener(this); - fViewer.setMinimumItemWidth(1); - - IEditorReference[] editorReferences = getSite().getPage().getEditorReferences(); - for (IEditorReference editorReference : editorReferences) { - IEditorPart editor = editorReference.getEditor(false); - if (editor instanceof ITmfTraceEditor) { - ITmfTrace trace = ((ITmfTraceEditor) editor).getTrace(); - if (trace != null) { - IFile bookmarksFile = ((ITmfTraceEditor) editor).getBookmarksFile(); - TimeChartAnalysisEntry timeAnalysisEntry = new TimeChartAnalysisEntry(trace, fDisplayWidth * 2); - fTimeAnalysisEntries.add(timeAnalysisEntry); - fDecorationProviders.put(trace, new TimeChartDecorationProvider(bookmarksFile)); - Thread thread = new ProcessTraceThread(timeAnalysisEntry); - thread.start(); - } - } - } - fViewer.setInput(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); - - fDecorateThreads = new ArrayList(); - ColorSettingsManager.addColorSettingsListener(this); - ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); - } - - @Override - public void dispose() { - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - for (DecorateThread thread : fDecorateThreads) { - thread.cancel(); - } - ColorSettingsManager.removeColorSettingsListener(this); - super.dispose(); - } - - @Override - public void setFocus() { - fViewer.setFocus(); - } - - private class ProcessTraceThread extends Thread { - - private final TimeChartAnalysisEntry fTimeAnalysisEntry; - - public ProcessTraceThread(TimeChartAnalysisEntry timeAnalysisEntry) { - super("ProcessTraceJob:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ - fTimeAnalysisEntry = timeAnalysisEntry; - } - - @Override - public void run() { - updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, 0, Long.MAX_VALUE); - } - } - - private void updateTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry, long stopRank, long startTime, long stopTime) { - ITmfTrace trace = timeAnalysisEntry.getTrace(); - TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); - if (decorationProvider == null) { - return; // the trace has been closed - } - ITmfContext context = null; - // TmfTimestamp lastTimestamp = null; - boolean done = false; - while (!done) { - synchronized (timeAnalysisEntry) { - if (timeAnalysisEntry.getLastRank() >= trace.getNbEvents()) { - done = true; - break; - } - if (context == null || context.getRank() != timeAnalysisEntry.getLastRank()) { - if (context != null) { - context.dispose(); - } - if (timeAnalysisEntry.getLastRank() != -1) { - context = trace.seekEvent(timeAnalysisEntry.getLastRank()); - } else { - // context = trace.seekLocation(null); - context = trace.seekEvent(0); - } - } - while (true) { - long rank = context.getRank(); - ITmfEvent event = trace.getNext(context); - if (event == null) { - done = true; - break; - } - // if (!event.getTimestamp().equals(lastTimestamp)) { - TimeChartEvent timeEvent = new TimeChartEvent(timeAnalysisEntry, event, rank, decorationProvider); - if (timeEvent.getTime() >= startTime && timeEvent.getTime() <= stopTime) { - timeAnalysisEntry.addTraceEvent(timeEvent); - } - // lastTimestamp = event.getTimestamp(); - // } *** commented out so that color setting priority gets - // set even if the event has same time - if (context.getRank() == trace.getNbEvents() || context.getRank() == stopRank) { - done = true; - break; - } - if (context.getRank() % trace.getCacheSize() == 1) { - // break for UI refresh - break; - } - } - // timeAnalysisEntry.setLastRank(Math.min(trace.getNbEvents(), - // stopRank)); - timeAnalysisEntry.setLastRank(context.getRank()); - } - redrawViewer(true); - } - if (context != null) { - context.dispose(); - } - } - - private void refreshViewer() { - synchronized (fSyncObj) { - if (fRefreshBusy) { - fRefreshPending = true; - return; - } - fRefreshBusy = true; - } - // Perform the refresh on the UI thread - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fViewer.getControl().isDisposed()) { - return; - } - fViewer.setInput(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); - fViewer.resetStartFinishTime(); - synchronized (fSyncObj) { - fRefreshBusy = false; - if (fRefreshPending) { - fRefreshPending = false; - refreshViewer(); - } - } - } - }); - } - - private void redrawViewer(boolean resetTimeIntervals) { - synchronized (fSyncObj) { - if (fRedrawBusy) { - fRedrawPending = true; - return; - } - fRedrawBusy = true; - } - final boolean reset = resetTimeIntervals; - // Perform the refresh on the UI thread - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - if (fViewer.getControl().isDisposed()) { - return; - } - if (reset) { - fViewer.setTimeRange(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); - fViewer.setTimeBounds(); - } - fViewer.getControl().redraw(); - fViewer.getControl().update(); - synchronized (fSyncObj) { - fRedrawBusy = false; - if (fRedrawPending) { - fRedrawPending = false; - redrawViewer(reset); - } - } - } - }); - } - - private void itemize(long startTime, long stopTime) { - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - Thread thread = new ItemizeThread(fTimeAnalysisEntries.get(i), startTime, stopTime); - thread.start(); - } - } - - private class ItemizeThread extends Thread { - - private final TimeChartAnalysisEntry fTimeAnalysisEntry; - private final long fStartTime; - private final long fStopTime; - private final long fMaxDuration; - - private ItemizeThread(TimeChartAnalysisEntry timeAnalysisEntry, long startTime, long stopTime) { - super("Itemize Thread:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ - fTimeAnalysisEntry = timeAnalysisEntry; - fStartTime = startTime; - fStopTime = stopTime; - fMaxDuration = 3 * (fStopTime - fStartTime) / fDisplayWidth; - } - - @Override - public void run() { - itemizeTraceEntry(fTimeAnalysisEntry); - } - - public void itemizeTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry) { - Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(); - TimeChartEvent event = null; - boolean hasNext = true; - while (hasNext) { - synchronized (timeAnalysisEntry) { - while (hasNext = iterator.hasNext()) { - event = (TimeChartEvent) iterator.next(); - if (event.getTime() + event.getDuration() > fStartTime && event.getTime() < fStopTime && event.getDuration() > fMaxDuration - && event.getNbEvents() > 1) { - break; - } - } - } - if (hasNext) { - if (event.getItemizedEntry() == null) { - itemizeEvent(event); - } else { - itemizeTraceEntry(event.getItemizedEntry()); - } - } - } - } - - public void itemizeEvent(TimeChartEvent event) { - synchronized (event) { - if (event.isItemizing()) { - return; - } - event.setItemizing(true); - } - TimeChartAnalysisEntry timeAnalysisEntry = new TimeChartAnalysisEntry(fTimeAnalysisEntry.getTrace(), (int) Math.min( - event.getNbEvents() + 1, fDisplayWidth * 2)); - synchronized (event.getRankRangeList()) { - for (RankRange range : event.getRankRangeList()) { - timeAnalysisEntry.setLastRank(range.getFirstRank()); - updateTraceEntry(timeAnalysisEntry, range.getLastRank() + 1, event.getTime(), event.getTime() + event.getDuration()); - } - } - event.setItemizedEntry(timeAnalysisEntry); - redrawViewer(false); - itemizeTraceEntry(timeAnalysisEntry); - synchronized (event) { - event.setItemizing(false); - } - } - } - - private void redecorate() { - synchronized (fDecorateThreads) { - for (DecorateThread thread : fDecorateThreads) { - thread.cancel(); - } - fDecorateThreads.clear(); - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - DecorateThread thread = new DecorateThread(fTimeAnalysisEntries.get(i)); - thread.start(); - fDecorateThreads.add(thread); - } - } - } - - private class DecorateThread extends Thread { - private volatile boolean interrupted = false; - private final TimeChartAnalysisEntry fTimeAnalysisEntry; - private final TimeChartDecorationProvider fDecorationProvider; - private ITmfContext fContext; - private int fCount = 0; - - private DecorateThread(TimeChartAnalysisEntry timeAnalysisEntry) { - super("Decorate Thread:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ - fTimeAnalysisEntry = timeAnalysisEntry; - fDecorationProvider = fDecorationProviders.get(timeAnalysisEntry.getTrace()); - } - - @Override - public void run() { - resetTraceEntry(fTimeAnalysisEntry); - redrawViewer(false); - decorateTraceEntry(fTimeAnalysisEntry, null); - redrawViewer(false); - synchronized (fDecorateThreads) { - fDecorateThreads.remove(this); - } - if (fContext != null) { - fContext.dispose(); - } - } - - public void resetTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry) { - Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(); - TimeChartEvent event = null; - boolean hasNext = true; - while (!interrupted && hasNext) { - synchronized (timeAnalysisEntry) { - while (hasNext = iterator.hasNext()) { - event = (TimeChartEvent) iterator.next(); - break; - } - } - if (hasNext) { - // TODO possible concurrency problem here with ItemizeJob - event.setColorSettingPriority(ColorSettingsManager.PRIORITY_NONE); - if (event.getItemizedEntry() != null) { - resetTraceEntry(event.getItemizedEntry()); - } - } - } - } - - public void decorateTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry, TimeChartEvent parentEvent) { - // Set max duration high to ensure iterator does not consider - // itemized events - Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(0, Long.MAX_VALUE, Long.MAX_VALUE); - TimeChartEvent event = null; - int entryPriority = ColorSettingsManager.PRIORITY_NONE; - boolean entryIsBookmarked = false; - boolean entryIsVisible = false; - boolean entryIsSearchMatch = false; - boolean hasNext = true; - while (!interrupted && hasNext) { - synchronized (timeAnalysisEntry) { - while (hasNext = iterator.hasNext()) { - event = (TimeChartEvent) iterator.next(); - break; - } - } - if (hasNext) { - // TODO possible concurrency problem here with ItemizeJob - if (event.getItemizedEntry() == null) { - decorateEvent(event); - } else { - decorateTraceEntry(event.getItemizedEntry(), event); - } - entryPriority = Math.min(entryPriority, event.getColorSettingPriority()); - entryIsBookmarked |= event.isBookmarked(); - entryIsVisible |= event.isVisible(); - entryIsSearchMatch |= event.isSearchMatch(); - if (++fCount % timeAnalysisEntry.getTrace().getCacheSize() == 0) { - redrawViewer(false); - } - } - } - if (parentEvent != null) { - parentEvent.setColorSettingPriority(entryPriority); - parentEvent.setIsBookmarked(entryIsBookmarked); - parentEvent.setIsVisible(entryIsVisible); - parentEvent.setIsSearchMatch(entryIsSearchMatch); - } - } - - public void decorateEvent(TimeChartEvent timeChartEvent) { - // TODO possible concurrency problem here with ItemizeJob - TimeChartAnalysisEntry timeAnalysisEntry = (TimeChartAnalysisEntry) timeChartEvent.getEntry(); - ITmfTrace trace = timeAnalysisEntry.getTrace(); - int priority = ColorSettingsManager.PRIORITY_NONE; - boolean isBookmarked = false; - boolean isVisible = false; - boolean isSearchMatch = false; - synchronized (timeChartEvent.getRankRangeList()) { - for (RankRange range : timeChartEvent.getRankRangeList()) { - if (interrupted) { - return; - } - if (fContext == null || fContext.getRank() != range.getFirstRank()) { - if (fContext != null) { - fContext.dispose(); - } - fContext = trace.seekEvent(range.getFirstRank()); - fContext.setRank(range.getFirstRank()); - } - while (true) { - if (interrupted) { - return; - } - long rank = fContext.getRank(); - ITmfEvent event = trace.getNext(fContext); - if (event == null) { - break; - } - long eventTime = event.getTimestamp().normalize(0, -9).getValue(); - if (eventTime >= timeChartEvent.getTime() && eventTime <= timeChartEvent.getTime() + timeChartEvent.getDuration()) { - priority = Math.min(priority, ColorSettingsManager.getColorSettingPriority(event)); - } - isBookmarked |= fDecorationProvider.isBookmark(rank); - isVisible |= fDecorationProvider.isVisible(event); - isSearchMatch |= fDecorationProvider.isSearchMatch(event); - if (fContext.getRank() > range.getLastRank()) { - break; - } - } - } - } - timeChartEvent.setColorSettingPriority(priority); - timeChartEvent.setIsBookmarked(isBookmarked); - timeChartEvent.setIsVisible(isVisible); - timeChartEvent.setIsSearchMatch(isSearchMatch); - } - - public void cancel() { - interrupted = true; - } - } - - // ------------------------------------------------------------------------ - // Listeners - // ------------------------------------------------------------------------ - - @Override - public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { - fStartTime = event.getStartTime(); - fStopTime = event.getEndTime(); - itemize(fStartTime, fStopTime); - } - - @Override - public void selectionChanged(TimeGraphSelectionEvent event) { - ITimeGraphEntry timeAnalysisEntry = null; - if (event.getSelection() instanceof TimeChartAnalysisEntry) { - timeAnalysisEntry = event.getSelection(); - } else if (event.getSelection() instanceof TimeChartEvent) { - timeAnalysisEntry = ((TimeChartEvent) event.getSelection()).getEntry(); - } - if (timeAnalysisEntry instanceof TimeChartAnalysisEntry) { - broadcast(new TmfTraceSelectedSignal(this, ((TimeChartAnalysisEntry) timeAnalysisEntry).getTrace())); - } - } - - @Override - public void timeSelected(TimeGraphTimeEvent event) { - broadcast(new TmfTimeSynchSignal(this, new TmfTimestamp(event.getTime(), TIMESTAMP_SCALE))); - } - - @Override - public void colorSettingsChanged(ColorSetting[] colorSettings) { - // Set presentation provider again to trigger re-creation of new color settings which are stored - // in the TimeGraphControl class - fViewer.setTimeGraphProvider(fPresentationProvider); - redecorate(); - } - - @Override - public void resourceChanged(IResourceChangeEvent event) { - for (IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { - for (TimeChartDecorationProvider provider : fDecorationProviders.values()) { - if (delta.getResource().equals(provider.getBookmarksFile())) { - if (delta.getKind() == IResourceDelta.CHANGED && delta.getMarker().getAttribute(IMarker.LOCATION, -1) != -1) { - provider.refreshBookmarks(); - } else if (delta.getKind() == IResourceDelta.REMOVED) { - provider.refreshBookmarks(); - } - } - } - } - redecorate(); - } - - @Override - public void filterApplied(ITmfFilter filter, ITmfTrace trace) { - TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); - decorationProvider.filterApplied(filter); - redecorate(); - } - - @Override - public void searchApplied(ITmfFilter filter, ITmfTrace trace) { - TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); - decorationProvider.searchApplied(filter); - redecorate(); - } - - // ------------------------------------------------------------------------ - // Signal handlers - // ------------------------------------------------------------------------ - - /** - * Handler for the Trace Opened signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void traceOpened(TmfTraceOpenedSignal signal) { - if (fTimeAnalysisEntries == null) { - return; - } - final ITmfTrace trace = signal.getTrace(); - final IFile bookmarksFile = signal.getBookmarksFile(); - final ITmfEventsFilterProvider eventsFilterProvider = signal.getEventsFilterProvider(); - TimeChartAnalysisEntry timeAnalysisEntry = null; - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { - timeAnalysisEntry = fTimeAnalysisEntries.get(i); - break; - } - } - if (timeAnalysisEntry == null) { - timeAnalysisEntry = new TimeChartAnalysisEntry(trace, fDisplayWidth * 2); - fTimeAnalysisEntries.add(timeAnalysisEntry); - fDecorationProviders.put(trace, new TimeChartDecorationProvider(bookmarksFile)); - Thread thread = new ProcessTraceThread(timeAnalysisEntry); - thread.start(); - } - refreshViewer(); - if (eventsFilterProvider != null) { - eventsFilterProvider.addEventsFilterListener(this); - } - } - - /** - * Handler for the Trace Closed signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void traceClosed(TmfTraceClosedSignal signal) { - if (fTimeAnalysisEntries == null) { - return; - } - final ITmfTrace trace = signal.getTrace(); - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { - fTimeAnalysisEntries.remove(i); - fDecorationProviders.remove(trace); - refreshViewer(); - break; - } - } - } - - /** - * Handler for the Trace Selected signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void traceSelected(TmfTraceSelectedSignal signal) { - if (signal.getSource() != this && fTimeAnalysisEntries != null) { - ITmfTrace trace = signal.getTrace(); - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { - fViewer.setSelection(fTimeAnalysisEntries.get(i)); - break; - } - } - } - } - - /** - * Handler for the Trace Updated signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void traceUpdated(TmfTraceUpdatedSignal signal) { - if (fTimeAnalysisEntries == null) { - return; - } - final ITmfTrace trace = signal.getTrace(); - for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { - TimeChartAnalysisEntry timeAnalysisEntry = fTimeAnalysisEntries.get(i); - if (timeAnalysisEntry.getTrace().equals(trace)) { - updateTraceEntry(timeAnalysisEntry, Long.MAX_VALUE, 0, Long.MAX_VALUE); - break; - } - } - } - - /** - * Handler for the Time Synch signal - * - * @param signal - * The incoming signal - */ - @TmfSignalHandler - public void currentTimeUpdated(TmfTimeSynchSignal signal) { - final long time = signal.getCurrentTime().normalize(0, TIMESTAMP_SCALE).getValue(); - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - fViewer.setSelectedTime(time, true); - } - }); - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.views.timechart; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IMarkerDelta; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; +import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter; +import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler; +import org.eclipse.linuxtools.tmf.core.signal.TmfTimeSynchSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfTraceSelectedSignal; +import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal; +import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.linuxtools.tmf.ui.editors.ITmfTraceEditor; +import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceClosedSignal; +import org.eclipse.linuxtools.tmf.ui.signal.TmfTraceOpenedSignal; +import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterListener; +import org.eclipse.linuxtools.tmf.ui.viewers.events.ITmfEventsFilterProvider; +import org.eclipse.linuxtools.tmf.ui.views.TmfView; +import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSetting; +import org.eclipse.linuxtools.tmf.ui.views.colors.ColorSettingsManager; +import org.eclipse.linuxtools.tmf.ui.views.colors.IColorSettingsListener; +import org.eclipse.linuxtools.tmf.ui.views.timechart.TimeChartEvent.RankRange; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphRangeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphSelectionListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphTimeListener; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphRangeUpdateEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphSelectionEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphTimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.TimeGraphViewer; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; + +/** + * Generic Time Chart view, which is similar to a Gantt chart for trace analysis + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeChartView extends TmfView implements ITimeGraphRangeListener, + ITimeGraphSelectionListener, ITimeGraphTimeListener, + IColorSettingsListener, IResourceChangeListener, + ITmfEventsFilterListener { + + /** TimeChartView's ID */ + public static final String ID = "org.eclipse.linuxtools.tmf.ui.views.timechart"; //$NON-NLS-1$ + + private static final int TIMESTAMP_SCALE = -9; + + private final int fDisplayWidth; + private TimeGraphViewer fViewer; + private final ArrayList fTimeAnalysisEntries = new ArrayList(); + private final Map, TimeChartDecorationProvider> fDecorationProviders = new HashMap, TimeChartDecorationProvider>(); + private ArrayList fDecorateThreads; + private long fStartTime = 0; + private long fStopTime = Long.MAX_VALUE; + private boolean fRefreshBusy = false; + private boolean fRefreshPending = false; + private boolean fRedrawBusy = false; + private boolean fRedrawPending = false; + private final Object fSyncObj = new Object(); + private ITimeGraphPresentationProvider fPresentationProvider; + + /** + * Default constructor + */ + public TimeChartView() { + super("Time Chart"); //$NON-NLS-1$ + fDisplayWidth = Display.getDefault().getBounds().width; + } + + @Override + public void createPartControl(Composite parent) { + fViewer = new TimeGraphViewer(parent, SWT.NONE); + fPresentationProvider = new TimeChartAnalysisProvider(); + fViewer.setTimeGraphProvider(fPresentationProvider); + fViewer.setTimeCalendarFormat(true); + fViewer.addTimeListener(this); + fViewer.addRangeListener(this); + fViewer.addSelectionListener(this); + fViewer.setMinimumItemWidth(1); + + IEditorReference[] editorReferences = getSite().getPage().getEditorReferences(); + for (IEditorReference editorReference : editorReferences) { + IEditorPart editor = editorReference.getEditor(false); + if (editor instanceof ITmfTraceEditor) { + ITmfTrace trace = ((ITmfTraceEditor) editor).getTrace(); + if (trace != null) { + IFile bookmarksFile = ((ITmfTraceEditor) editor).getBookmarksFile(); + TimeChartAnalysisEntry timeAnalysisEntry = new TimeChartAnalysisEntry(trace, fDisplayWidth * 2); + fTimeAnalysisEntries.add(timeAnalysisEntry); + fDecorationProviders.put(trace, new TimeChartDecorationProvider(bookmarksFile)); + Thread thread = new ProcessTraceThread(timeAnalysisEntry); + thread.start(); + } + } + } + fViewer.setInput(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); + + fDecorateThreads = new ArrayList(); + ColorSettingsManager.addColorSettingsListener(this); + ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); + } + + @Override + public void dispose() { + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + for (DecorateThread thread : fDecorateThreads) { + thread.cancel(); + } + ColorSettingsManager.removeColorSettingsListener(this); + super.dispose(); + } + + @Override + public void setFocus() { + fViewer.setFocus(); + } + + private class ProcessTraceThread extends Thread { + + private final TimeChartAnalysisEntry fTimeAnalysisEntry; + + public ProcessTraceThread(TimeChartAnalysisEntry timeAnalysisEntry) { + super("ProcessTraceJob:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ + fTimeAnalysisEntry = timeAnalysisEntry; + } + + @Override + public void run() { + updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, 0, Long.MAX_VALUE); + } + } + + private void updateTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry, long stopRank, long startTime, long stopTime) { + ITmfTrace trace = timeAnalysisEntry.getTrace(); + TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); + if (decorationProvider == null) { + return; // the trace has been closed + } + ITmfContext context = null; + // TmfTimestamp lastTimestamp = null; + boolean done = false; + while (!done) { + synchronized (timeAnalysisEntry) { + if (timeAnalysisEntry.getLastRank() >= trace.getNbEvents()) { + done = true; + break; + } + if (context == null || context.getRank() != timeAnalysisEntry.getLastRank()) { + if (context != null) { + context.dispose(); + } + if (timeAnalysisEntry.getLastRank() != -1) { + context = trace.seekEvent(timeAnalysisEntry.getLastRank()); + } else { + // context = trace.seekLocation(null); + context = trace.seekEvent(0); + } + } + while (true) { + long rank = context.getRank(); + ITmfEvent event = trace.getNext(context); + if (event == null) { + done = true; + break; + } + // if (!event.getTimestamp().equals(lastTimestamp)) { + TimeChartEvent timeEvent = new TimeChartEvent(timeAnalysisEntry, event, rank, decorationProvider); + if (timeEvent.getTime() >= startTime && timeEvent.getTime() <= stopTime) { + timeAnalysisEntry.addTraceEvent(timeEvent); + } + // lastTimestamp = event.getTimestamp(); + // } *** commented out so that color setting priority gets + // set even if the event has same time + if (context.getRank() == trace.getNbEvents() || context.getRank() == stopRank) { + done = true; + break; + } + if (context.getRank() % trace.getCacheSize() == 1) { + // break for UI refresh + break; + } + } + // timeAnalysisEntry.setLastRank(Math.min(trace.getNbEvents(), + // stopRank)); + timeAnalysisEntry.setLastRank(context.getRank()); + } + redrawViewer(true); + } + if (context != null) { + context.dispose(); + } + } + + private void refreshViewer() { + synchronized (fSyncObj) { + if (fRefreshBusy) { + fRefreshPending = true; + return; + } + fRefreshBusy = true; + } + // Perform the refresh on the UI thread + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fViewer.getControl().isDisposed()) { + return; + } + fViewer.setInput(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); + fViewer.resetStartFinishTime(); + synchronized (fSyncObj) { + fRefreshBusy = false; + if (fRefreshPending) { + fRefreshPending = false; + refreshViewer(); + } + } + } + }); + } + + private void redrawViewer(boolean resetTimeIntervals) { + synchronized (fSyncObj) { + if (fRedrawBusy) { + fRedrawPending = true; + return; + } + fRedrawBusy = true; + } + final boolean reset = resetTimeIntervals; + // Perform the refresh on the UI thread + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (fViewer.getControl().isDisposed()) { + return; + } + if (reset) { + fViewer.setTimeRange(fTimeAnalysisEntries.toArray(new TimeChartAnalysisEntry[0])); + fViewer.setTimeBounds(); + } + fViewer.getControl().redraw(); + fViewer.getControl().update(); + synchronized (fSyncObj) { + fRedrawBusy = false; + if (fRedrawPending) { + fRedrawPending = false; + redrawViewer(reset); + } + } + } + }); + } + + private void itemize(long startTime, long stopTime) { + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + Thread thread = new ItemizeThread(fTimeAnalysisEntries.get(i), startTime, stopTime); + thread.start(); + } + } + + private class ItemizeThread extends Thread { + + private final TimeChartAnalysisEntry fTimeAnalysisEntry; + private final long fStartTime; + private final long fStopTime; + private final long fMaxDuration; + + private ItemizeThread(TimeChartAnalysisEntry timeAnalysisEntry, long startTime, long stopTime) { + super("Itemize Thread:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ + fTimeAnalysisEntry = timeAnalysisEntry; + fStartTime = startTime; + fStopTime = stopTime; + fMaxDuration = 3 * (fStopTime - fStartTime) / fDisplayWidth; + } + + @Override + public void run() { + itemizeTraceEntry(fTimeAnalysisEntry); + } + + public void itemizeTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry) { + Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(); + TimeChartEvent event = null; + boolean hasNext = true; + while (hasNext) { + synchronized (timeAnalysisEntry) { + while (hasNext = iterator.hasNext()) { + event = (TimeChartEvent) iterator.next(); + if (event.getTime() + event.getDuration() > fStartTime && event.getTime() < fStopTime && event.getDuration() > fMaxDuration + && event.getNbEvents() > 1) { + break; + } + } + } + if (hasNext) { + if (event.getItemizedEntry() == null) { + itemizeEvent(event); + } else { + itemizeTraceEntry(event.getItemizedEntry()); + } + } + } + } + + public void itemizeEvent(TimeChartEvent event) { + synchronized (event) { + if (event.isItemizing()) { + return; + } + event.setItemizing(true); + } + TimeChartAnalysisEntry timeAnalysisEntry = new TimeChartAnalysisEntry(fTimeAnalysisEntry.getTrace(), (int) Math.min( + event.getNbEvents() + 1, fDisplayWidth * 2)); + synchronized (event.getRankRangeList()) { + for (RankRange range : event.getRankRangeList()) { + timeAnalysisEntry.setLastRank(range.getFirstRank()); + updateTraceEntry(timeAnalysisEntry, range.getLastRank() + 1, event.getTime(), event.getTime() + event.getDuration()); + } + } + event.setItemizedEntry(timeAnalysisEntry); + redrawViewer(false); + itemizeTraceEntry(timeAnalysisEntry); + synchronized (event) { + event.setItemizing(false); + } + } + } + + private void redecorate() { + synchronized (fDecorateThreads) { + for (DecorateThread thread : fDecorateThreads) { + thread.cancel(); + } + fDecorateThreads.clear(); + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + DecorateThread thread = new DecorateThread(fTimeAnalysisEntries.get(i)); + thread.start(); + fDecorateThreads.add(thread); + } + } + } + + private class DecorateThread extends Thread { + private volatile boolean interrupted = false; + private final TimeChartAnalysisEntry fTimeAnalysisEntry; + private final TimeChartDecorationProvider fDecorationProvider; + private ITmfContext fContext; + private int fCount = 0; + + private DecorateThread(TimeChartAnalysisEntry timeAnalysisEntry) { + super("Decorate Thread:" + timeAnalysisEntry.getName()); //$NON-NLS-1$ + fTimeAnalysisEntry = timeAnalysisEntry; + fDecorationProvider = fDecorationProviders.get(timeAnalysisEntry.getTrace()); + } + + @Override + public void run() { + resetTraceEntry(fTimeAnalysisEntry); + redrawViewer(false); + decorateTraceEntry(fTimeAnalysisEntry, null); + redrawViewer(false); + synchronized (fDecorateThreads) { + fDecorateThreads.remove(this); + } + if (fContext != null) { + fContext.dispose(); + } + } + + public void resetTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry) { + Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(); + TimeChartEvent event = null; + boolean hasNext = true; + while (!interrupted && hasNext) { + synchronized (timeAnalysisEntry) { + while (hasNext = iterator.hasNext()) { + event = (TimeChartEvent) iterator.next(); + break; + } + } + if (hasNext) { + // TODO possible concurrency problem here with ItemizeJob + event.setColorSettingPriority(ColorSettingsManager.PRIORITY_NONE); + if (event.getItemizedEntry() != null) { + resetTraceEntry(event.getItemizedEntry()); + } + } + } + } + + public void decorateTraceEntry(TimeChartAnalysisEntry timeAnalysisEntry, TimeChartEvent parentEvent) { + // Set max duration high to ensure iterator does not consider + // itemized events + Iterator iterator = timeAnalysisEntry.getTimeEventsIterator(0, Long.MAX_VALUE, Long.MAX_VALUE); + TimeChartEvent event = null; + int entryPriority = ColorSettingsManager.PRIORITY_NONE; + boolean entryIsBookmarked = false; + boolean entryIsVisible = false; + boolean entryIsSearchMatch = false; + boolean hasNext = true; + while (!interrupted && hasNext) { + synchronized (timeAnalysisEntry) { + while (hasNext = iterator.hasNext()) { + event = (TimeChartEvent) iterator.next(); + break; + } + } + if (hasNext) { + // TODO possible concurrency problem here with ItemizeJob + if (event.getItemizedEntry() == null) { + decorateEvent(event); + } else { + decorateTraceEntry(event.getItemizedEntry(), event); + } + entryPriority = Math.min(entryPriority, event.getColorSettingPriority()); + entryIsBookmarked |= event.isBookmarked(); + entryIsVisible |= event.isVisible(); + entryIsSearchMatch |= event.isSearchMatch(); + if (++fCount % timeAnalysisEntry.getTrace().getCacheSize() == 0) { + redrawViewer(false); + } + } + } + if (parentEvent != null) { + parentEvent.setColorSettingPriority(entryPriority); + parentEvent.setIsBookmarked(entryIsBookmarked); + parentEvent.setIsVisible(entryIsVisible); + parentEvent.setIsSearchMatch(entryIsSearchMatch); + } + } + + public void decorateEvent(TimeChartEvent timeChartEvent) { + // TODO possible concurrency problem here with ItemizeJob + TimeChartAnalysisEntry timeAnalysisEntry = (TimeChartAnalysisEntry) timeChartEvent.getEntry(); + ITmfTrace trace = timeAnalysisEntry.getTrace(); + int priority = ColorSettingsManager.PRIORITY_NONE; + boolean isBookmarked = false; + boolean isVisible = false; + boolean isSearchMatch = false; + synchronized (timeChartEvent.getRankRangeList()) { + for (RankRange range : timeChartEvent.getRankRangeList()) { + if (interrupted) { + return; + } + if (fContext == null || fContext.getRank() != range.getFirstRank()) { + if (fContext != null) { + fContext.dispose(); + } + fContext = trace.seekEvent(range.getFirstRank()); + fContext.setRank(range.getFirstRank()); + } + while (true) { + if (interrupted) { + return; + } + long rank = fContext.getRank(); + ITmfEvent event = trace.getNext(fContext); + if (event == null) { + break; + } + long eventTime = event.getTimestamp().normalize(0, -9).getValue(); + if (eventTime >= timeChartEvent.getTime() && eventTime <= timeChartEvent.getTime() + timeChartEvent.getDuration()) { + priority = Math.min(priority, ColorSettingsManager.getColorSettingPriority(event)); + } + isBookmarked |= fDecorationProvider.isBookmark(rank); + isVisible |= fDecorationProvider.isVisible(event); + isSearchMatch |= fDecorationProvider.isSearchMatch(event); + if (fContext.getRank() > range.getLastRank()) { + break; + } + } + } + } + timeChartEvent.setColorSettingPriority(priority); + timeChartEvent.setIsBookmarked(isBookmarked); + timeChartEvent.setIsVisible(isVisible); + timeChartEvent.setIsSearchMatch(isSearchMatch); + } + + public void cancel() { + interrupted = true; + } + } + + // ------------------------------------------------------------------------ + // Listeners + // ------------------------------------------------------------------------ + + @Override + public void timeRangeUpdated(TimeGraphRangeUpdateEvent event) { + fStartTime = event.getStartTime(); + fStopTime = event.getEndTime(); + itemize(fStartTime, fStopTime); + } + + @Override + public void selectionChanged(TimeGraphSelectionEvent event) { + ITimeGraphEntry timeAnalysisEntry = null; + if (event.getSelection() instanceof TimeChartAnalysisEntry) { + timeAnalysisEntry = event.getSelection(); + } else if (event.getSelection() instanceof TimeChartEvent) { + timeAnalysisEntry = ((TimeChartEvent) event.getSelection()).getEntry(); + } + if (timeAnalysisEntry instanceof TimeChartAnalysisEntry) { + broadcast(new TmfTraceSelectedSignal(this, ((TimeChartAnalysisEntry) timeAnalysisEntry).getTrace())); + } + } + + @Override + public void timeSelected(TimeGraphTimeEvent event) { + broadcast(new TmfTimeSynchSignal(this, new TmfTimestamp(event.getTime(), TIMESTAMP_SCALE))); + } + + @Override + public void colorSettingsChanged(ColorSetting[] colorSettings) { + // Set presentation provider again to trigger re-creation of new color settings which are stored + // in the TimeGraphControl class + fViewer.setTimeGraphProvider(fPresentationProvider); + redecorate(); + } + + @Override + public void resourceChanged(IResourceChangeEvent event) { + for (IMarkerDelta delta : event.findMarkerDeltas(IMarker.BOOKMARK, false)) { + for (TimeChartDecorationProvider provider : fDecorationProviders.values()) { + if (delta.getResource().equals(provider.getBookmarksFile())) { + if (delta.getKind() == IResourceDelta.CHANGED && delta.getMarker().getAttribute(IMarker.LOCATION, -1) != -1) { + provider.refreshBookmarks(); + } else if (delta.getKind() == IResourceDelta.REMOVED) { + provider.refreshBookmarks(); + } + } + } + } + redecorate(); + } + + @Override + public void filterApplied(ITmfFilter filter, ITmfTrace trace) { + TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); + decorationProvider.filterApplied(filter); + redecorate(); + } + + @Override + public void searchApplied(ITmfFilter filter, ITmfTrace trace) { + TimeChartDecorationProvider decorationProvider = fDecorationProviders.get(trace); + decorationProvider.searchApplied(filter); + redecorate(); + } + + // ------------------------------------------------------------------------ + // Signal handlers + // ------------------------------------------------------------------------ + + /** + * Handler for the Trace Opened signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void traceOpened(TmfTraceOpenedSignal signal) { + if (fTimeAnalysisEntries == null) { + return; + } + final ITmfTrace trace = signal.getTrace(); + final IFile bookmarksFile = signal.getBookmarksFile(); + final ITmfEventsFilterProvider eventsFilterProvider = signal.getEventsFilterProvider(); + TimeChartAnalysisEntry timeAnalysisEntry = null; + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { + timeAnalysisEntry = fTimeAnalysisEntries.get(i); + break; + } + } + if (timeAnalysisEntry == null) { + timeAnalysisEntry = new TimeChartAnalysisEntry(trace, fDisplayWidth * 2); + fTimeAnalysisEntries.add(timeAnalysisEntry); + fDecorationProviders.put(trace, new TimeChartDecorationProvider(bookmarksFile)); + Thread thread = new ProcessTraceThread(timeAnalysisEntry); + thread.start(); + } + refreshViewer(); + if (eventsFilterProvider != null) { + eventsFilterProvider.addEventsFilterListener(this); + } + } + + /** + * Handler for the Trace Closed signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void traceClosed(TmfTraceClosedSignal signal) { + if (fTimeAnalysisEntries == null) { + return; + } + final ITmfTrace trace = signal.getTrace(); + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { + fTimeAnalysisEntries.remove(i); + fDecorationProviders.remove(trace); + refreshViewer(); + break; + } + } + } + + /** + * Handler for the Trace Selected signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void traceSelected(TmfTraceSelectedSignal signal) { + if (signal.getSource() != this && fTimeAnalysisEntries != null) { + ITmfTrace trace = signal.getTrace(); + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + if (fTimeAnalysisEntries.get(i).getTrace().equals(trace)) { + fViewer.setSelection(fTimeAnalysisEntries.get(i)); + break; + } + } + } + } + + /** + * Handler for the Trace Updated signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void traceUpdated(TmfTraceUpdatedSignal signal) { + if (fTimeAnalysisEntries == null) { + return; + } + final ITmfTrace trace = signal.getTrace(); + for (int i = 0; i < fTimeAnalysisEntries.size(); i++) { + TimeChartAnalysisEntry timeAnalysisEntry = fTimeAnalysisEntries.get(i); + if (timeAnalysisEntry.getTrace().equals(trace)) { + updateTraceEntry(timeAnalysisEntry, Long.MAX_VALUE, 0, Long.MAX_VALUE); + break; + } + } + } + + /** + * Handler for the Time Synch signal + * + * @param signal + * The incoming signal + */ + @TmfSignalHandler + public void currentTimeUpdated(TmfTimeSynchSignal signal) { + final long time = signal.getCurrentTime().normalize(0, TIMESTAMP_SCALE).getValue(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + fViewer.setSelectedTime(time, true); + } + }); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java index 2ee72aee17..d8c6815de2 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java @@ -1,1034 +1,1034 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - ******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.rawviewer; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; -import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; -import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; -import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.CaretEvent; -import org.eclipse.swt.custom.CaretListener; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.ControlListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseAdapter; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.MouseTrackListener; -import org.eclipse.swt.events.MouseWheelListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.FontData; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Slider; - -/** - * TmfRawEventViewer allows for the display of the raw data for an arbitrarily - * large number of TMF events. - * - * It is essentially a Composite of a StyledText area and a Slider, where the number - * of visible lines in the StyledText control is set to fill the viewer display area. - * An underlying data model is used to store a cache of event raw text line data. - * The slider is ratio-based. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TmfRawEventViewer extends Composite implements ControlListener, SelectionListener, - KeyListener, CaretListener, MouseMoveListener, MouseTrackListener, MouseWheelListener { - - private static final Color COLOR_BACKGROUND_ODD = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); - private static final Color COLOR_BACKGROUND_EVEN = new Color(Display.getDefault(), 242, 242, 242); - private static final Color COLOR_BACKGROUND_SELECTED = new Color(Display.getDefault(), 231, 246, 254); - private static final Color COLOR_BACKGROUND_HIGHLIGHTED = new Color(Display.getDefault(), 246, 252, 255); - private static final int MAX_LINE_DATA_SIZE = 1000; - private static final int SLIDER_MAX = 1000000; - - private ITmfTrace fTrace; - private ITmfContext fBottomContext; - - private ScrolledComposite fScrolledComposite; - private Composite fTextArea; - private StyledText fStyledText; - private Font fFixedFont; - private Slider fSlider; - - private List fLines = new ArrayList(); - private boolean fActualRanks = false; - private int fTopLineIndex; - private int fLastTopLineIndex; - private CaretPosition[] fStoredCaretPosition = new CaretPosition[] - { new CaretPosition(0, 0), new CaretPosition(0,0)}; - private int fNumVisibleLines; - private ITmfLocation fSelectedLocation = null; - private long fHighlightedRank = Long.MIN_VALUE; - private int fCursorYCoordinate = -1; - private int fHoldSelection = 0; - - private static class LineData { - long rank; - ITmfLocation location; - String string; - public LineData(long rank, ITmfLocation location, String string) { - this.rank = rank; - this.location = location; - if (string.length() == 0) { - this.string = " "; // workaround for setLineBackground has no effect on empty line //$NON-NLS-1$ - } else { - this.string = string; - } - } - @Override - public String toString() { - return rank + " [" + location + "]: " + string; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - private static class CaretPosition { - int time; - int caretOffset; - public CaretPosition(int time, int caretOffset) { - this.time = time; - this.caretOffset = caretOffset; - } - } - - // ------------------------------------------------------------------------ - // Constructor - // ------------------------------------------------------------------------ - - /** - * Constructor - * @param parent The parent composite - * @param style The style bits - */ - public TmfRawEventViewer(Composite parent, int style) { - super(parent, style & (~SWT.H_SCROLL) & (~SWT.V_SCROLL)); - - // Set the layout - GridLayout gridLayout = new GridLayout(); - gridLayout.numColumns = 2; - gridLayout.horizontalSpacing = 0; - gridLayout.verticalSpacing = 0; - gridLayout.marginWidth = 0; - gridLayout.marginHeight = 0; - setLayout(gridLayout); - - // Create the controls - createTextArea(style & SWT.H_SCROLL); - createSlider(style & SWT.V_SCROLL); - - // Prevent the slider from being traversed - setTabList(new Control[] { fScrolledComposite }); - } - - @Override - public void dispose() { - if (fFixedFont != null) { - fFixedFont.dispose(); - fFixedFont = null; - } - super.dispose(); - } - - // ------------------------------------------------------------------------ - // Text area handling - // ------------------------------------------------------------------------ - - /** - * Create the text area and add listeners - */ - private void createTextArea(int style) { - fScrolledComposite = new ScrolledComposite(this, style); - fScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - fTextArea = new Composite(fScrolledComposite, SWT.NONE); - fTextArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - fScrolledComposite.setContent(fTextArea); - fScrolledComposite.setExpandHorizontal(true); - fScrolledComposite.setExpandVertical(true); - fScrolledComposite.setAlwaysShowScrollBars(true); - fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - fScrolledComposite.addControlListener(this); - - GridLayout textAreaGridLayout = new GridLayout(); - textAreaGridLayout.marginHeight = 0; - textAreaGridLayout.marginWidth = 0; - fTextArea.setLayout(textAreaGridLayout); - - if (fFixedFont == null) { - if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ - fFixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ - } else { - fFixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ - } - } - - fStyledText = new StyledText(fTextArea, SWT.READ_ONLY); - fStyledText.setFont(fFixedFont); - fStyledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - - fStyledText.addCaretListener(this); - fStyledText.addMouseMoveListener(this); - fStyledText.addMouseTrackListener(this); - fStyledText.addMouseWheelListener(this); - fStyledText.addListener(SWT.MouseWheel, new Listener() { // disable mouse scroll of horizontal scroll bar - @Override - public void handleEvent(Event event) { event.doit = false; }}); - fStyledText.addKeyListener(this); - - fTextArea.setBackground(fStyledText.getBackground()); - fTextArea.addMouseListener(new MouseAdapter() { - @Override - public void mouseDown(MouseEvent e) { - fTextArea.setFocus(); - }}); - } - - // ------------------------------------------------------------------------ - // Slider handling - // ------------------------------------------------------------------------ - - private void createSlider(int style) { - fSlider = new Slider(this, SWT.VERTICAL); - fSlider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true)); - fSlider.setValues(0, 0, SLIDER_MAX, SLIDER_MAX, 1, 1); - fSlider.addSelectionListener(this); - if ((style & SWT.V_SCROLL) == 0) { - fSlider.setVisible(false); - } - } - - // ------------------------------------------------------------------------ - // Controls interactions - // ------------------------------------------------------------------------ - - @Override - public boolean setFocus() { - boolean isVisible = isVisible(); - if (isVisible) { - fTextArea.setFocus(); - } - return isVisible; - } - - @Override - public void setMenu(Menu menu) { - fStyledText.setMenu(menu); - } - - /** - * Sets the trace and updates the content - * @param trace The trace to set - */ - public void setTrace(ITmfTrace trace) { - fTrace = trace; - fTopLineIndex = 0; - fLines.clear(); - refreshEventCount(); - } - - /** - * Refreshes the event count, updates the slider thumb and loads display - */ - public void refreshEventCount() { - if (fTrace != null) { - if (fTrace.getNbEvents() > 0) { - fSlider.setThumb((int) Math.max(SLIDER_MAX / fTrace.getNbEvents(), 1)); - } else { - fSlider.setThumb(SLIDER_MAX); - } - - if (!isVisible()) return; - - if (fLines.size() == 0) { - setTopRank(0); - } else if (fLines.size() < fNumVisibleLines) { - fBottomContext = null; - loadLineData(); - fillTextArea(); - //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); - fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); - } - } - } - - /** - * Selects the event of given rank and makes it visible. - * @param rank The rank of event - */ - public void selectAndReveal(long rank) { - if (fTrace == null || !isVisible()) { - return; - } - if (fActualRanks && fTopLineIndex < fLines.size() && rank >= fLines.get(fTopLineIndex).rank) { - int lastVisibleIndex = Math.min(fTopLineIndex + fNumVisibleLines, fLines.size()) - 1; - if (rank <= fLines.get(lastVisibleIndex).rank) { - for (int i = fTopLineIndex; i < fLines.size(); i++) { - if (fLines.get(i).rank == rank) { - fSelectedLocation = fLines.get(i).location; - break; - } - } - refreshLineBackgrounds(); - return; - } - } - setTopRank(rank); - if (fLines.size() > 0 && fHoldSelection == 0) { - fSelectedLocation = fLines.get(0).location; - refreshLineBackgrounds(); - } - } - /** - * Add a selection listener - * @param listener A listener to add - */ - public void addSelectionListener(Listener listener) { - checkWidget(); - if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - addListener (SWT.Selection, listener); - } - - /** - * Remove selection listener - * @param listener A listener to remove - */ - public void removeSelectionListener(Listener listener) { - checkWidget(); - if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - removeListener(SWT.Selection, listener); - } - - private void sendSelectionEvent(LineData lineData) { - Event event = new Event(); - if (fActualRanks) { - event.data = Long.valueOf(lineData.rank); - } else { - event.data = lineData.location; - } - notifyListeners(SWT.Selection, event); - } - - private void setTopRank(long rank) { - fBottomContext = fTrace.seekEvent(rank); - if (fBottomContext == null) { - return; - } - fLines.clear(); - fActualRanks = true; - fTopLineIndex = 0; - loadLineData(); - refreshTextArea(); - if (fLines.size() == 0) { - fSlider.setSelection(0); - } else { - //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); - fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); - } - } - - private void setTopPosition(double ratio) { - fBottomContext = fTrace.seekEvent(ratio); - if (fBottomContext == null) { - return; - } - fBottomContext.setRank(0); - fLines.clear(); - fActualRanks = false; - fTopLineIndex = 0; - loadLineData(); - refreshTextArea(); - } - - private void loadLineData() { - if (fTopLineIndex < 0) { - //if (fLines.size() > 0 && fLines.get(0).rank > 0) { - //long endRank = fLines.get(0).rank; - //long startRank = Math.max(0, endRank - fNumVisibleLines); - //TmfContext context = fTrace.seekEvent(startRank); - //int index = 0; - //while (context.getRank() < endRank) { - //long rank = context.getRank(); - //ITmfLocation location = context.getLocation(); - //TmfEvent event = fTrace.getNextEvent(context); - //String[] lines = event.getRawText().split("\r?\n"); - //for (int i = 0; i < lines.length; i++) { - //String line = lines[i]; - //LineData lineData = new LineData(rank, location, line); - //fLines.add(index++, lineData); - //fTopLineIndex++; - //fLastTopLineIndex++; - //} - //} - //} - if (fLines.size() > 0 && fTrace.getLocationRatio(fLines.get(0).location) > 0) { - double lastRatio = fTrace.getLocationRatio(fLines.get(fLines.size() - 1).location); - double firstRatio = fTrace.getLocationRatio(fLines.get(0).location); - double delta; - boolean singleEvent = false; - if (firstRatio != lastRatio) { - // approximate ratio of at least 20 items - delta = Math.max(20, fNumVisibleLines) * (lastRatio - firstRatio) / (fLines.size() - 1); - } else { - delta = Math.pow(10, -15); - singleEvent = true; - } - while (fTopLineIndex < 0) { - ITmfLocation endLocation = fLines.get(0).location; - firstRatio = Math.max(0, firstRatio - delta); - ITmfContext context = fTrace.seekEvent(firstRatio); - ITmfLocation location; - int index = 0; - long rank = 0; - while (!context.getLocation().equals(endLocation)) { - location = context.getLocation().clone(); - ITmfEvent event = fTrace.getNext(context); - if (event == null) { - break; - } - if (event.getContent() != null && event.getContent().getValue() != null) { - String[] lines = event.getContent().getValue().toString().split("\r?\n"); //$NON-NLS-1$ - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - LineData lineData = new LineData(rank, location, line); - fLines.add(index++, lineData); - fTopLineIndex++; - fLastTopLineIndex++; - } - } else { - LineData lineData = new LineData(rank, location, ""); //$NON-NLS-1$ - fLines.add(index++, lineData); - fTopLineIndex++; - fLastTopLineIndex++; - } - rank++; - } - long rankOffset = fLines.get(index).rank - rank; - for (int i = 0; i < index; i++) { - fLines.get(i).rank += rankOffset; - } - if (firstRatio == 0) { - break; - } - if (singleEvent) { - delta = Math.min(delta * 10, 0.1); - } - } - } - if (fTopLineIndex < 0) { - fTopLineIndex = 0; - } - } - - while (fLines.size() - fTopLineIndex < fNumVisibleLines) { - if (fBottomContext == null) { - if (fLines.size() == 0) { - fBottomContext = fTrace.seekEvent(0); - } else { - //fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).rank + 1); - fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).location); - fTrace.getNext(fBottomContext); - } - if (fBottomContext == null) { - break; - } - } - long rank = fBottomContext.getRank(); - ITmfLocation location = fBottomContext.getLocation() != null ? fBottomContext.getLocation().clone() : null; - ITmfEvent event = fTrace.getNext(fBottomContext); - if (event == null) { - break; - } - if (event.getContent() != null && event.getContent().getValue() != null) { - for (String line : event.getContent().getValue().toString().split("\r?\n")) { //$NON-NLS-1$ - int crPos; - if ((crPos = line.indexOf('\r')) != -1) { - line = line.substring(0, crPos); - } - LineData lineData = new LineData(rank, location, line); - fLines.add(lineData); - } - } else { - LineData lineData = new LineData(rank, location, ""); //$NON-NLS-1$ - fLines.add(lineData); - } - } - fTopLineIndex = Math.max(0, Math.min(fTopLineIndex, fLines.size() - 1)); - - if (fLines.size() > MAX_LINE_DATA_SIZE) { - if (fTopLineIndex < MAX_LINE_DATA_SIZE / 2) { - long rank = fLines.get(MAX_LINE_DATA_SIZE - 1).rank; - for (int i = MAX_LINE_DATA_SIZE; i < fLines.size(); i++) { - if (fLines.get(i).rank > rank) { - fLines.subList(i, fLines.size()).clear(); - fBottomContext = null; - break; - } - } - } else { - long rank = fLines.get(fLines.size() - MAX_LINE_DATA_SIZE).rank; - for (int i = fLines.size() - MAX_LINE_DATA_SIZE - 1; i >= 0; i--) { - if (fLines.get(i).rank < rank) { - fLines.subList(0, i + 1).clear(); - fTopLineIndex -= (i + 1); - fLastTopLineIndex -= (i + 1); - break; - } - } - } - } - } - - private void refreshTextArea() { - fStyledText.setText(""); //$NON-NLS-1$ - for (int i = 0; i < fLines.size() - fTopLineIndex && i < fNumVisibleLines; i++) { - if (i > 0) fStyledText.append("\n"); //$NON-NLS-1$ - LineData lineData = fLines.get(fTopLineIndex + i); - fStyledText.append(lineData.string); - setLineBackground(i, lineData); - } - fTextArea.layout(); - fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - fLastTopLineIndex = fTopLineIndex; - } - - private void fillTextArea() { - int nextLine = fStyledText.getCharCount() == 0 ? 0 : fStyledText.getLineCount(); - for (int i = nextLine; i < fLines.size() - fTopLineIndex && i < fNumVisibleLines; i++) { - if (i > 0) fStyledText.append("\n"); //$NON-NLS-1$ - LineData lineData = fLines.get(fTopLineIndex + i); - fStyledText.append(lineData.string); - setLineBackground(i, lineData); - } - int endLine = Math.min(fNumVisibleLines, fLines.size()); - if (endLine < fStyledText.getLineCount()) { - int endOffset = fStyledText.getOffsetAtLine(endLine) - 1; - if (endOffset > fStyledText.getCharCount()) { - fHoldSelection++; - fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$ - fHoldSelection--; - } - } - fTextArea.layout(); - fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - } - - private void updateTextArea() { - if (fTopLineIndex < fLastTopLineIndex) { - StringBuffer insertedText = new StringBuffer(); - for (int i = fTopLineIndex; i < fLastTopLineIndex; i++) { - insertedText.append(fLines.get(i).string + "\n"); //$NON-NLS-1$ - } - fStyledText.replaceTextRange(0, 0, insertedText.toString()); - for (int i = 0; i < fLastTopLineIndex - fTopLineIndex; i++) { - LineData lineData = fLines.get(fTopLineIndex + i); - setLineBackground(i, lineData); - } - fLastTopLineIndex = fTopLineIndex; - } else if (fTopLineIndex > fLastTopLineIndex) { - int length = 0; - for (int i = 0; i < fTopLineIndex - fLastTopLineIndex && i < fNumVisibleLines; i++) { - length += fLines.get(i + fLastTopLineIndex).string.length(); - if (i < fStyledText.getLineCount()) length += 1; - } - fStyledText.replaceTextRange(0, length, ""); //$NON-NLS-1$ - fLastTopLineIndex = fTopLineIndex; - fillTextArea(); - } - int endLine = Math.min(fNumVisibleLines, fLines.size()); - if (endLine < fStyledText.getLineCount()) { - int endOffset = fStyledText.getOffsetAtLine(endLine) - 1; - if (endOffset > fStyledText.getCharCount()) { - fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$ - } - } - fTextArea.layout(); - fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - } - - private void refreshLineBackgrounds() { - for (int i = 0; (i < fStyledText.getLineCount()) && (i < fNumVisibleLines) && (i < fLines.size() - fTopLineIndex); i++) { - LineData lineData = fLines.get(fTopLineIndex + i); - setLineBackground(i, lineData); - } - } - - private void setLineBackground(int index, LineData lineData) { - if (lineData.location.equals(fSelectedLocation)) { - fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_SELECTED); - } else if (lineData.rank == fHighlightedRank) { - fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_HIGHLIGHTED); - } else if (lineData.rank % 2 == 0) { - fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_EVEN); - } else { - fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_ODD); - } - } - - private void storeCaretPosition(int time, int caretOffset) { - if (fStoredCaretPosition[0].time == time) { - fStoredCaretPosition[0].caretOffset = caretOffset; - } else { - fStoredCaretPosition[1] = fStoredCaretPosition[0]; - fStoredCaretPosition[0] = new CaretPosition(time, caretOffset); - } - } - - private int getPreviousCaretOffset(int time) { - if (fStoredCaretPosition[0].time == time) { - return fStoredCaretPosition[1].caretOffset; - } - return fStoredCaretPosition[0].caretOffset; - } - - private void updateHighlightedRank() { - if (fCursorYCoordinate < 0 || fCursorYCoordinate > fStyledText.getSize().y) { - if (fHighlightedRank != Long.MIN_VALUE) { - fHighlightedRank = Long.MIN_VALUE; - refreshLineBackgrounds(); - } - return; - } - int offset = fStyledText.getOffsetAtLocation(new Point(0, fCursorYCoordinate)); - int line = fStyledText.getLineAtOffset(offset); - if (line < fLines.size() - fTopLineIndex) { - LineData lineData = fLines.get(fTopLineIndex + line); - if (fHighlightedRank != lineData.rank) { - fHighlightedRank = lineData.rank; - refreshLineBackgrounds(); - } - } else { - if (fHighlightedRank != Long.MIN_VALUE) { - fHighlightedRank = Long.MIN_VALUE; - refreshLineBackgrounds(); - } - } - } - - // ------------------------------------------------------------------------ - // ControlListener (ScrolledComposite) - // ------------------------------------------------------------------------ - - @Override - public void controlResized(ControlEvent event) { - int areaHeight = fScrolledComposite.getSize().y; - if (fScrolledComposite.getHorizontalBar() != null) { - areaHeight -= fScrolledComposite.getHorizontalBar().getSize().y; - } - int lineHeight = fStyledText.getLineHeight(); - fNumVisibleLines = Math.max((areaHeight + lineHeight - 1) / lineHeight, 1); - - if (fBottomContext != null) { - loadLineData(); - fillTextArea(); - } - } - - @Override - public void controlMoved(ControlEvent e) { - } - - // ------------------------------------------------------------------------ - // SelectionListener (Slider) - // ------------------------------------------------------------------------ - - @Override - public void widgetSelected(SelectionEvent e) { - fTextArea.setFocus(); - if (fLines.size() == 0) { - return; - } - if (e.detail == SWT.DRAG) { - return; - } - fHoldSelection++; - switch (e.detail) { - case SWT.NONE: { - //long rank = (long) (fTrace.getNbEvents() * ((double) fSlider.getSelection() / SLIDER_MAX)); - //setTopRank(rank); - if (fSlider.getSelection() == 0 || fSlider.getThumb() == SLIDER_MAX) { - fLines.clear(); - setTopPosition(0.0); - break; - } - double ratio = (double) fSlider.getSelection() / (SLIDER_MAX - fSlider.getThumb()); - double delta = Math.pow(10, -15); - fLines.clear(); - while (fLines.size() == 0) { - setTopPosition(ratio); - if (ratio == 0.0) break; - delta = Math.min(delta * 10, 0.1); - ratio = Math.max(ratio - delta, 0.0); - } - break; - } - case SWT.ARROW_DOWN: { - if (fTopLineIndex >= fLines.size()) { - break; - } - fTopLineIndex++; - loadLineData(); - updateTextArea(); - break; - } - case SWT.PAGE_DOWN: { - fTopLineIndex += Math.max(fNumVisibleLines - 1, 1); - loadLineData(); - updateTextArea(); - break; - } - case SWT.ARROW_UP: { - //if (fLines.size() == 0 || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { - if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { - break; - } - fTopLineIndex--; - loadLineData(); - updateTextArea(); - break; - } - case SWT.PAGE_UP: { - fTopLineIndex -= Math.max(fNumVisibleLines - 1, 1); - loadLineData(); - updateTextArea(); - break; - } - case SWT.HOME: { - //selectAndReveal(0); - setTopPosition(0.0); - break; - } - case SWT.END: { - //if (fTrace.getNbEvents() > 0) { - //selectAndReveal(fTrace.getNbEvents() - 1); - //} - double ratio = 1.0; - double delta = Math.pow(10, -15); - fLines.clear(); - while (fLines.size() == 0) { - setTopPosition(ratio); - if (ratio == 0.0) break; - delta = Math.min(delta * 10, 0.1); - ratio = Math.max(ratio - delta, 0.0); - } - break; - } - default: - break; - } - //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); - if (e.detail != SWT.NONE) { - fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); - } - - fHoldSelection = 0; - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - } - - // ------------------------------------------------------------------------ - // KeyListener (StyledText) - // ------------------------------------------------------------------------ - - @Override - public void keyPressed(KeyEvent e) { - if (fLines.size() == 0) { - return; - } - int caretOffset = fStyledText.getCaretOffset(); - int previousCaretOffset = getPreviousCaretOffset(e.time); - int previousLineAtCaretPosition = fStyledText.getLineAtOffset(previousCaretOffset); - int previousColumnAtCaretPosition = getPreviousCaretOffset(e.time) - fStyledText.getOffsetAtLine(previousLineAtCaretPosition); - switch (e.keyCode) { - case SWT.ARROW_DOWN: { - if (previousLineAtCaretPosition < (fNumVisibleLines - 2)) { - break; - } - fHoldSelection++; - fTopLineIndex++; - loadLineData(); - updateTextArea(); - fHoldSelection--; - LineData lineData = fLines.get(fTopLineIndex + fStyledText.getLineAtOffset(fStyledText.getCaretOffset())); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - break; - } - case SWT.PAGE_DOWN: { - if (previousLineAtCaretPosition >= (fNumVisibleLines - 1)) { - fHoldSelection++; - if (fLines.get(fTopLineIndex + previousLineAtCaretPosition).rank % 2 == 0) { - fStyledText.setLineBackground(previousLineAtCaretPosition, 1, COLOR_BACKGROUND_EVEN); - } else { - fStyledText.setLineBackground(previousLineAtCaretPosition, 1, COLOR_BACKGROUND_ODD); - } - fSelectedLocation = null; - fTopLineIndex += Math.max(fNumVisibleLines - 1, 1); - loadLineData(); - updateTextArea(); - fHoldSelection--; - } - int line = Math.min(fNumVisibleLines - 1, fStyledText.getLineCount() - 1); - int offset = fStyledText.getOffsetAtLine(line); - fStyledText.setSelection(offset + Math.min(previousColumnAtCaretPosition, fLines.get(fTopLineIndex + line).string.length())); - break; - } - case SWT.ARROW_RIGHT: { - if (previousCaretOffset < fStyledText.getCharCount() || previousLineAtCaretPosition < (fNumVisibleLines - 2)) { - break; - } - fHoldSelection++; - fTopLineIndex++; - loadLineData(); - updateTextArea(); - fHoldSelection--; - fStyledText.setSelection(fStyledText.getCaretOffset() + 1); - break; - } - case SWT.ARROW_UP: { - if (previousLineAtCaretPosition > 0) { - break; - } - if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { - break; - } - fHoldSelection++; - fTopLineIndex--; - loadLineData(); - updateTextArea(); - fHoldSelection--; - LineData lineData = fLines.get(fTopLineIndex); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - fStyledText.setSelection(caretOffset); - break; - } - case SWT.PAGE_UP: { - if (previousLineAtCaretPosition > 0) { - break; - } - fHoldSelection++; - fTopLineIndex -= Math.max(fNumVisibleLines - 1, 1); - loadLineData(); - updateTextArea(); - fHoldSelection--; - LineData lineData = fLines.get(fTopLineIndex); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - fStyledText.setSelection(caretOffset); - break; - } - case SWT.ARROW_LEFT: { - if (previousCaretOffset > 0) { - break; - } - if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { - break; - } - long topRank = fLines.get(fTopLineIndex).rank; - fHoldSelection++; - fTopLineIndex--; - loadLineData(); - updateTextArea(); - fHoldSelection--; - LineData lineData = fLines.get(fTopLineIndex); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - if (topRank != fLines.get(fTopLineIndex).rank) { - fStyledText.setSelection(fLines.get(fTopLineIndex).string.length()); - } - break; - } - case SWT.HOME: { - if ((e.stateMask & SWT.CTRL) == 0) { - break; - } - //selectAndReveal(0); - setTopPosition(0.0); - LineData lineData = fLines.get(fTopLineIndex); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - break; - } - case SWT.END: { - if ((e.stateMask & SWT.CTRL) == 0) { - break; - } - //if (fTrace.getNbEvents() > 0) { - //selectAndReveal(fTrace.getNbEvents() - 1); - //} - double ratio = 1.0; - double delta = Math.pow(10, -15); - fLines.clear(); - while (fLines.size() == 0) { - setTopPosition(ratio); - if (ratio == 0.0) break; - delta = Math.min(delta * 10, 0.1); - ratio = Math.max(ratio - delta, 0.0); - } - LineData lineData = fLines.get(fTopLineIndex); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - break; - } - default: - break; - } - //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); - updateHighlightedRank(); - fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); - } - - @Override - public void keyReleased(KeyEvent e) { - } - - // ------------------------------------------------------------------------ - // CaretListener (StyledText) - // ------------------------------------------------------------------------ - - @Override - public void caretMoved(CaretEvent event) { - if (fHoldSelection == 0) { - int line = fStyledText.getLineAtOffset(event.caretOffset); - if (fTopLineIndex + line < fLines.size()) { - LineData lineData = fLines.get(fTopLineIndex + line); - if (!lineData.location.equals(fSelectedLocation)) { - fSelectedLocation = lineData.location; - refreshLineBackgrounds(); - sendSelectionEvent(lineData); - } - } - } - storeCaretPosition(event.time, event.caretOffset); - if (fHoldSelection == 0) { - Point caret = fStyledText.getLocationAtOffset(fStyledText.getCaretOffset()); - Point origin = fScrolledComposite.getOrigin(); - if (origin.x > caret.x) { - origin.x = caret.x; - } else if (caret.x - origin.x > fScrolledComposite.getSize().x) { - origin.x = caret.x - fScrolledComposite.getSize().x + 1; - } - fScrolledComposite.setOrigin(origin); - } - } - - // ------------------------------------------------------------------------ - // MouseMoveListener (StyledText) - // ------------------------------------------------------------------------ - - @Override - public void mouseMove(MouseEvent e) { - fCursorYCoordinate = e.y; - if (e.y < 0 || e.y > fStyledText.getSize().y) { - if (fHighlightedRank != Long.MIN_VALUE) { - fHighlightedRank = Long.MIN_VALUE; - refreshLineBackgrounds(); - } - return; - } - int offset = fStyledText.getOffsetAtLocation(new Point(0, e.y)); - int line = fStyledText.getLineAtOffset(offset); - if (line < fLines.size() - fTopLineIndex) { - LineData lineData = fLines.get(fTopLineIndex + line); - if (fHighlightedRank != lineData.rank) { - fHighlightedRank = lineData.rank; - refreshLineBackgrounds(); - } - } else { - if (fHighlightedRank != Long.MIN_VALUE) { - fHighlightedRank = Long.MIN_VALUE; - refreshLineBackgrounds(); - } - } - } - - // ------------------------------------------------------------------------ - // MouseTrackListener (StyledText) - // ------------------------------------------------------------------------ - - @Override - public void mouseExit(MouseEvent e) { - fCursorYCoordinate = -1; - if (fHighlightedRank != Long.MIN_VALUE) { - fHighlightedRank = Long.MIN_VALUE; - refreshLineBackgrounds(); - } - } - - @Override - public void mouseEnter(MouseEvent e) { - fCursorYCoordinate = e.y; - } - - @Override - public void mouseHover(MouseEvent e) { - } - - // ------------------------------------------------------------------------ - // MouseWheelListener (StyledText) - // ------------------------------------------------------------------------ - - @Override - public void mouseScrolled(MouseEvent e) { - if (fLines.size() == 0) { - return; - } - fHoldSelection++; - fTopLineIndex -= e.count; - loadLineData(); - updateTextArea(); - fHoldSelection = 0; - //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); - updateHighlightedRank(); - fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); - } - -} +/******************************************************************************* + * Copyright (c) 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + ******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.rawviewer; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; +import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; +import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CaretEvent; +import org.eclipse.swt.custom.CaretListener; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.ControlListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.events.MouseTrackListener; +import org.eclipse.swt.events.MouseWheelListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Slider; + +/** + * TmfRawEventViewer allows for the display of the raw data for an arbitrarily + * large number of TMF events. + * + * It is essentially a Composite of a StyledText area and a Slider, where the number + * of visible lines in the StyledText control is set to fill the viewer display area. + * An underlying data model is used to store a cache of event raw text line data. + * The slider is ratio-based. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TmfRawEventViewer extends Composite implements ControlListener, SelectionListener, + KeyListener, CaretListener, MouseMoveListener, MouseTrackListener, MouseWheelListener { + + private static final Color COLOR_BACKGROUND_ODD = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + private static final Color COLOR_BACKGROUND_EVEN = new Color(Display.getDefault(), 242, 242, 242); + private static final Color COLOR_BACKGROUND_SELECTED = new Color(Display.getDefault(), 231, 246, 254); + private static final Color COLOR_BACKGROUND_HIGHLIGHTED = new Color(Display.getDefault(), 246, 252, 255); + private static final int MAX_LINE_DATA_SIZE = 1000; + private static final int SLIDER_MAX = 1000000; + + private ITmfTrace fTrace; + private ITmfContext fBottomContext; + + private ScrolledComposite fScrolledComposite; + private Composite fTextArea; + private StyledText fStyledText; + private Font fFixedFont; + private Slider fSlider; + + private List fLines = new ArrayList(); + private boolean fActualRanks = false; + private int fTopLineIndex; + private int fLastTopLineIndex; + private CaretPosition[] fStoredCaretPosition = new CaretPosition[] + { new CaretPosition(0, 0), new CaretPosition(0,0)}; + private int fNumVisibleLines; + private ITmfLocation fSelectedLocation = null; + private long fHighlightedRank = Long.MIN_VALUE; + private int fCursorYCoordinate = -1; + private int fHoldSelection = 0; + + private static class LineData { + long rank; + ITmfLocation location; + String string; + public LineData(long rank, ITmfLocation location, String string) { + this.rank = rank; + this.location = location; + if (string.length() == 0) { + this.string = " "; // workaround for setLineBackground has no effect on empty line //$NON-NLS-1$ + } else { + this.string = string; + } + } + @Override + public String toString() { + return rank + " [" + location + "]: " + string; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private static class CaretPosition { + int time; + int caretOffset; + public CaretPosition(int time, int caretOffset) { + this.time = time; + this.caretOffset = caretOffset; + } + } + + // ------------------------------------------------------------------------ + // Constructor + // ------------------------------------------------------------------------ + + /** + * Constructor + * @param parent The parent composite + * @param style The style bits + */ + public TmfRawEventViewer(Composite parent, int style) { + super(parent, style & (~SWT.H_SCROLL) & (~SWT.V_SCROLL)); + + // Set the layout + GridLayout gridLayout = new GridLayout(); + gridLayout.numColumns = 2; + gridLayout.horizontalSpacing = 0; + gridLayout.verticalSpacing = 0; + gridLayout.marginWidth = 0; + gridLayout.marginHeight = 0; + setLayout(gridLayout); + + // Create the controls + createTextArea(style & SWT.H_SCROLL); + createSlider(style & SWT.V_SCROLL); + + // Prevent the slider from being traversed + setTabList(new Control[] { fScrolledComposite }); + } + + @Override + public void dispose() { + if (fFixedFont != null) { + fFixedFont.dispose(); + fFixedFont = null; + } + super.dispose(); + } + + // ------------------------------------------------------------------------ + // Text area handling + // ------------------------------------------------------------------------ + + /** + * Create the text area and add listeners + */ + private void createTextArea(int style) { + fScrolledComposite = new ScrolledComposite(this, style); + fScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + fTextArea = new Composite(fScrolledComposite, SWT.NONE); + fTextArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + fScrolledComposite.setContent(fTextArea); + fScrolledComposite.setExpandHorizontal(true); + fScrolledComposite.setExpandVertical(true); + fScrolledComposite.setAlwaysShowScrollBars(true); + fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + fScrolledComposite.addControlListener(this); + + GridLayout textAreaGridLayout = new GridLayout(); + textAreaGridLayout.marginHeight = 0; + textAreaGridLayout.marginWidth = 0; + fTextArea.setLayout(textAreaGridLayout); + + if (fFixedFont == null) { + if (System.getProperty("os.name").contains("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ + fFixedFont = new Font(Display.getCurrent(), new FontData("Courier New", 10, SWT.NORMAL)); //$NON-NLS-1$ + } else { + fFixedFont = new Font(Display.getCurrent(), new FontData("Monospace", 10, SWT.NORMAL)); //$NON-NLS-1$ + } + } + + fStyledText = new StyledText(fTextArea, SWT.READ_ONLY); + fStyledText.setFont(fFixedFont); + fStyledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + fStyledText.addCaretListener(this); + fStyledText.addMouseMoveListener(this); + fStyledText.addMouseTrackListener(this); + fStyledText.addMouseWheelListener(this); + fStyledText.addListener(SWT.MouseWheel, new Listener() { // disable mouse scroll of horizontal scroll bar + @Override + public void handleEvent(Event event) { event.doit = false; }}); + fStyledText.addKeyListener(this); + + fTextArea.setBackground(fStyledText.getBackground()); + fTextArea.addMouseListener(new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + fTextArea.setFocus(); + }}); + } + + // ------------------------------------------------------------------------ + // Slider handling + // ------------------------------------------------------------------------ + + private void createSlider(int style) { + fSlider = new Slider(this, SWT.VERTICAL); + fSlider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true)); + fSlider.setValues(0, 0, SLIDER_MAX, SLIDER_MAX, 1, 1); + fSlider.addSelectionListener(this); + if ((style & SWT.V_SCROLL) == 0) { + fSlider.setVisible(false); + } + } + + // ------------------------------------------------------------------------ + // Controls interactions + // ------------------------------------------------------------------------ + + @Override + public boolean setFocus() { + boolean isVisible = isVisible(); + if (isVisible) { + fTextArea.setFocus(); + } + return isVisible; + } + + @Override + public void setMenu(Menu menu) { + fStyledText.setMenu(menu); + } + + /** + * Sets the trace and updates the content + * @param trace The trace to set + */ + public void setTrace(ITmfTrace trace) { + fTrace = trace; + fTopLineIndex = 0; + fLines.clear(); + refreshEventCount(); + } + + /** + * Refreshes the event count, updates the slider thumb and loads display + */ + public void refreshEventCount() { + if (fTrace != null) { + if (fTrace.getNbEvents() > 0) { + fSlider.setThumb((int) Math.max(SLIDER_MAX / fTrace.getNbEvents(), 1)); + } else { + fSlider.setThumb(SLIDER_MAX); + } + + if (!isVisible()) return; + + if (fLines.size() == 0) { + setTopRank(0); + } else if (fLines.size() < fNumVisibleLines) { + fBottomContext = null; + loadLineData(); + fillTextArea(); + //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); + fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); + } + } + } + + /** + * Selects the event of given rank and makes it visible. + * @param rank The rank of event + */ + public void selectAndReveal(long rank) { + if (fTrace == null || !isVisible()) { + return; + } + if (fActualRanks && fTopLineIndex < fLines.size() && rank >= fLines.get(fTopLineIndex).rank) { + int lastVisibleIndex = Math.min(fTopLineIndex + fNumVisibleLines, fLines.size()) - 1; + if (rank <= fLines.get(lastVisibleIndex).rank) { + for (int i = fTopLineIndex; i < fLines.size(); i++) { + if (fLines.get(i).rank == rank) { + fSelectedLocation = fLines.get(i).location; + break; + } + } + refreshLineBackgrounds(); + return; + } + } + setTopRank(rank); + if (fLines.size() > 0 && fHoldSelection == 0) { + fSelectedLocation = fLines.get(0).location; + refreshLineBackgrounds(); + } + } + /** + * Add a selection listener + * @param listener A listener to add + */ + public void addSelectionListener(Listener listener) { + checkWidget(); + if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + addListener (SWT.Selection, listener); + } + + /** + * Remove selection listener + * @param listener A listener to remove + */ + public void removeSelectionListener(Listener listener) { + checkWidget(); + if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + removeListener(SWT.Selection, listener); + } + + private void sendSelectionEvent(LineData lineData) { + Event event = new Event(); + if (fActualRanks) { + event.data = Long.valueOf(lineData.rank); + } else { + event.data = lineData.location; + } + notifyListeners(SWT.Selection, event); + } + + private void setTopRank(long rank) { + fBottomContext = fTrace.seekEvent(rank); + if (fBottomContext == null) { + return; + } + fLines.clear(); + fActualRanks = true; + fTopLineIndex = 0; + loadLineData(); + refreshTextArea(); + if (fLines.size() == 0) { + fSlider.setSelection(0); + } else { + //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); + fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); + } + } + + private void setTopPosition(double ratio) { + fBottomContext = fTrace.seekEvent(ratio); + if (fBottomContext == null) { + return; + } + fBottomContext.setRank(0); + fLines.clear(); + fActualRanks = false; + fTopLineIndex = 0; + loadLineData(); + refreshTextArea(); + } + + private void loadLineData() { + if (fTopLineIndex < 0) { + //if (fLines.size() > 0 && fLines.get(0).rank > 0) { + //long endRank = fLines.get(0).rank; + //long startRank = Math.max(0, endRank - fNumVisibleLines); + //TmfContext context = fTrace.seekEvent(startRank); + //int index = 0; + //while (context.getRank() < endRank) { + //long rank = context.getRank(); + //ITmfLocation location = context.getLocation(); + //TmfEvent event = fTrace.getNextEvent(context); + //String[] lines = event.getRawText().split("\r?\n"); + //for (int i = 0; i < lines.length; i++) { + //String line = lines[i]; + //LineData lineData = new LineData(rank, location, line); + //fLines.add(index++, lineData); + //fTopLineIndex++; + //fLastTopLineIndex++; + //} + //} + //} + if (fLines.size() > 0 && fTrace.getLocationRatio(fLines.get(0).location) > 0) { + double lastRatio = fTrace.getLocationRatio(fLines.get(fLines.size() - 1).location); + double firstRatio = fTrace.getLocationRatio(fLines.get(0).location); + double delta; + boolean singleEvent = false; + if (firstRatio != lastRatio) { + // approximate ratio of at least 20 items + delta = Math.max(20, fNumVisibleLines) * (lastRatio - firstRatio) / (fLines.size() - 1); + } else { + delta = Math.pow(10, -15); + singleEvent = true; + } + while (fTopLineIndex < 0) { + ITmfLocation endLocation = fLines.get(0).location; + firstRatio = Math.max(0, firstRatio - delta); + ITmfContext context = fTrace.seekEvent(firstRatio); + ITmfLocation location; + int index = 0; + long rank = 0; + while (!context.getLocation().equals(endLocation)) { + location = context.getLocation().clone(); + ITmfEvent event = fTrace.getNext(context); + if (event == null) { + break; + } + if (event.getContent() != null && event.getContent().getValue() != null) { + String[] lines = event.getContent().getValue().toString().split("\r?\n"); //$NON-NLS-1$ + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + LineData lineData = new LineData(rank, location, line); + fLines.add(index++, lineData); + fTopLineIndex++; + fLastTopLineIndex++; + } + } else { + LineData lineData = new LineData(rank, location, ""); //$NON-NLS-1$ + fLines.add(index++, lineData); + fTopLineIndex++; + fLastTopLineIndex++; + } + rank++; + } + long rankOffset = fLines.get(index).rank - rank; + for (int i = 0; i < index; i++) { + fLines.get(i).rank += rankOffset; + } + if (firstRatio == 0) { + break; + } + if (singleEvent) { + delta = Math.min(delta * 10, 0.1); + } + } + } + if (fTopLineIndex < 0) { + fTopLineIndex = 0; + } + } + + while (fLines.size() - fTopLineIndex < fNumVisibleLines) { + if (fBottomContext == null) { + if (fLines.size() == 0) { + fBottomContext = fTrace.seekEvent(0); + } else { + //fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).rank + 1); + fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).location); + fTrace.getNext(fBottomContext); + } + if (fBottomContext == null) { + break; + } + } + long rank = fBottomContext.getRank(); + ITmfLocation location = fBottomContext.getLocation() != null ? fBottomContext.getLocation().clone() : null; + ITmfEvent event = fTrace.getNext(fBottomContext); + if (event == null) { + break; + } + if (event.getContent() != null && event.getContent().getValue() != null) { + for (String line : event.getContent().getValue().toString().split("\r?\n")) { //$NON-NLS-1$ + int crPos; + if ((crPos = line.indexOf('\r')) != -1) { + line = line.substring(0, crPos); + } + LineData lineData = new LineData(rank, location, line); + fLines.add(lineData); + } + } else { + LineData lineData = new LineData(rank, location, ""); //$NON-NLS-1$ + fLines.add(lineData); + } + } + fTopLineIndex = Math.max(0, Math.min(fTopLineIndex, fLines.size() - 1)); + + if (fLines.size() > MAX_LINE_DATA_SIZE) { + if (fTopLineIndex < MAX_LINE_DATA_SIZE / 2) { + long rank = fLines.get(MAX_LINE_DATA_SIZE - 1).rank; + for (int i = MAX_LINE_DATA_SIZE; i < fLines.size(); i++) { + if (fLines.get(i).rank > rank) { + fLines.subList(i, fLines.size()).clear(); + fBottomContext = null; + break; + } + } + } else { + long rank = fLines.get(fLines.size() - MAX_LINE_DATA_SIZE).rank; + for (int i = fLines.size() - MAX_LINE_DATA_SIZE - 1; i >= 0; i--) { + if (fLines.get(i).rank < rank) { + fLines.subList(0, i + 1).clear(); + fTopLineIndex -= (i + 1); + fLastTopLineIndex -= (i + 1); + break; + } + } + } + } + } + + private void refreshTextArea() { + fStyledText.setText(""); //$NON-NLS-1$ + for (int i = 0; i < fLines.size() - fTopLineIndex && i < fNumVisibleLines; i++) { + if (i > 0) fStyledText.append("\n"); //$NON-NLS-1$ + LineData lineData = fLines.get(fTopLineIndex + i); + fStyledText.append(lineData.string); + setLineBackground(i, lineData); + } + fTextArea.layout(); + fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + fLastTopLineIndex = fTopLineIndex; + } + + private void fillTextArea() { + int nextLine = fStyledText.getCharCount() == 0 ? 0 : fStyledText.getLineCount(); + for (int i = nextLine; i < fLines.size() - fTopLineIndex && i < fNumVisibleLines; i++) { + if (i > 0) fStyledText.append("\n"); //$NON-NLS-1$ + LineData lineData = fLines.get(fTopLineIndex + i); + fStyledText.append(lineData.string); + setLineBackground(i, lineData); + } + int endLine = Math.min(fNumVisibleLines, fLines.size()); + if (endLine < fStyledText.getLineCount()) { + int endOffset = fStyledText.getOffsetAtLine(endLine) - 1; + if (endOffset > fStyledText.getCharCount()) { + fHoldSelection++; + fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$ + fHoldSelection--; + } + } + fTextArea.layout(); + fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + } + + private void updateTextArea() { + if (fTopLineIndex < fLastTopLineIndex) { + StringBuffer insertedText = new StringBuffer(); + for (int i = fTopLineIndex; i < fLastTopLineIndex; i++) { + insertedText.append(fLines.get(i).string + "\n"); //$NON-NLS-1$ + } + fStyledText.replaceTextRange(0, 0, insertedText.toString()); + for (int i = 0; i < fLastTopLineIndex - fTopLineIndex; i++) { + LineData lineData = fLines.get(fTopLineIndex + i); + setLineBackground(i, lineData); + } + fLastTopLineIndex = fTopLineIndex; + } else if (fTopLineIndex > fLastTopLineIndex) { + int length = 0; + for (int i = 0; i < fTopLineIndex - fLastTopLineIndex && i < fNumVisibleLines; i++) { + length += fLines.get(i + fLastTopLineIndex).string.length(); + if (i < fStyledText.getLineCount()) length += 1; + } + fStyledText.replaceTextRange(0, length, ""); //$NON-NLS-1$ + fLastTopLineIndex = fTopLineIndex; + fillTextArea(); + } + int endLine = Math.min(fNumVisibleLines, fLines.size()); + if (endLine < fStyledText.getLineCount()) { + int endOffset = fStyledText.getOffsetAtLine(endLine) - 1; + if (endOffset > fStyledText.getCharCount()) { + fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$ + } + } + fTextArea.layout(); + fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + } + + private void refreshLineBackgrounds() { + for (int i = 0; (i < fStyledText.getLineCount()) && (i < fNumVisibleLines) && (i < fLines.size() - fTopLineIndex); i++) { + LineData lineData = fLines.get(fTopLineIndex + i); + setLineBackground(i, lineData); + } + } + + private void setLineBackground(int index, LineData lineData) { + if (lineData.location.equals(fSelectedLocation)) { + fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_SELECTED); + } else if (lineData.rank == fHighlightedRank) { + fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_HIGHLIGHTED); + } else if (lineData.rank % 2 == 0) { + fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_EVEN); + } else { + fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_ODD); + } + } + + private void storeCaretPosition(int time, int caretOffset) { + if (fStoredCaretPosition[0].time == time) { + fStoredCaretPosition[0].caretOffset = caretOffset; + } else { + fStoredCaretPosition[1] = fStoredCaretPosition[0]; + fStoredCaretPosition[0] = new CaretPosition(time, caretOffset); + } + } + + private int getPreviousCaretOffset(int time) { + if (fStoredCaretPosition[0].time == time) { + return fStoredCaretPosition[1].caretOffset; + } + return fStoredCaretPosition[0].caretOffset; + } + + private void updateHighlightedRank() { + if (fCursorYCoordinate < 0 || fCursorYCoordinate > fStyledText.getSize().y) { + if (fHighlightedRank != Long.MIN_VALUE) { + fHighlightedRank = Long.MIN_VALUE; + refreshLineBackgrounds(); + } + return; + } + int offset = fStyledText.getOffsetAtLocation(new Point(0, fCursorYCoordinate)); + int line = fStyledText.getLineAtOffset(offset); + if (line < fLines.size() - fTopLineIndex) { + LineData lineData = fLines.get(fTopLineIndex + line); + if (fHighlightedRank != lineData.rank) { + fHighlightedRank = lineData.rank; + refreshLineBackgrounds(); + } + } else { + if (fHighlightedRank != Long.MIN_VALUE) { + fHighlightedRank = Long.MIN_VALUE; + refreshLineBackgrounds(); + } + } + } + + // ------------------------------------------------------------------------ + // ControlListener (ScrolledComposite) + // ------------------------------------------------------------------------ + + @Override + public void controlResized(ControlEvent event) { + int areaHeight = fScrolledComposite.getSize().y; + if (fScrolledComposite.getHorizontalBar() != null) { + areaHeight -= fScrolledComposite.getHorizontalBar().getSize().y; + } + int lineHeight = fStyledText.getLineHeight(); + fNumVisibleLines = Math.max((areaHeight + lineHeight - 1) / lineHeight, 1); + + if (fBottomContext != null) { + loadLineData(); + fillTextArea(); + } + } + + @Override + public void controlMoved(ControlEvent e) { + } + + // ------------------------------------------------------------------------ + // SelectionListener (Slider) + // ------------------------------------------------------------------------ + + @Override + public void widgetSelected(SelectionEvent e) { + fTextArea.setFocus(); + if (fLines.size() == 0) { + return; + } + if (e.detail == SWT.DRAG) { + return; + } + fHoldSelection++; + switch (e.detail) { + case SWT.NONE: { + //long rank = (long) (fTrace.getNbEvents() * ((double) fSlider.getSelection() / SLIDER_MAX)); + //setTopRank(rank); + if (fSlider.getSelection() == 0 || fSlider.getThumb() == SLIDER_MAX) { + fLines.clear(); + setTopPosition(0.0); + break; + } + double ratio = (double) fSlider.getSelection() / (SLIDER_MAX - fSlider.getThumb()); + double delta = Math.pow(10, -15); + fLines.clear(); + while (fLines.size() == 0) { + setTopPosition(ratio); + if (ratio == 0.0) break; + delta = Math.min(delta * 10, 0.1); + ratio = Math.max(ratio - delta, 0.0); + } + break; + } + case SWT.ARROW_DOWN: { + if (fTopLineIndex >= fLines.size()) { + break; + } + fTopLineIndex++; + loadLineData(); + updateTextArea(); + break; + } + case SWT.PAGE_DOWN: { + fTopLineIndex += Math.max(fNumVisibleLines - 1, 1); + loadLineData(); + updateTextArea(); + break; + } + case SWT.ARROW_UP: { + //if (fLines.size() == 0 || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { + if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { + break; + } + fTopLineIndex--; + loadLineData(); + updateTextArea(); + break; + } + case SWT.PAGE_UP: { + fTopLineIndex -= Math.max(fNumVisibleLines - 1, 1); + loadLineData(); + updateTextArea(); + break; + } + case SWT.HOME: { + //selectAndReveal(0); + setTopPosition(0.0); + break; + } + case SWT.END: { + //if (fTrace.getNbEvents() > 0) { + //selectAndReveal(fTrace.getNbEvents() - 1); + //} + double ratio = 1.0; + double delta = Math.pow(10, -15); + fLines.clear(); + while (fLines.size() == 0) { + setTopPosition(ratio); + if (ratio == 0.0) break; + delta = Math.min(delta * 10, 0.1); + ratio = Math.max(ratio - delta, 0.0); + } + break; + } + default: + break; + } + //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); + if (e.detail != SWT.NONE) { + fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); + } + + fHoldSelection = 0; + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + + // ------------------------------------------------------------------------ + // KeyListener (StyledText) + // ------------------------------------------------------------------------ + + @Override + public void keyPressed(KeyEvent e) { + if (fLines.size() == 0) { + return; + } + int caretOffset = fStyledText.getCaretOffset(); + int previousCaretOffset = getPreviousCaretOffset(e.time); + int previousLineAtCaretPosition = fStyledText.getLineAtOffset(previousCaretOffset); + int previousColumnAtCaretPosition = getPreviousCaretOffset(e.time) - fStyledText.getOffsetAtLine(previousLineAtCaretPosition); + switch (e.keyCode) { + case SWT.ARROW_DOWN: { + if (previousLineAtCaretPosition < (fNumVisibleLines - 2)) { + break; + } + fHoldSelection++; + fTopLineIndex++; + loadLineData(); + updateTextArea(); + fHoldSelection--; + LineData lineData = fLines.get(fTopLineIndex + fStyledText.getLineAtOffset(fStyledText.getCaretOffset())); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + break; + } + case SWT.PAGE_DOWN: { + if (previousLineAtCaretPosition >= (fNumVisibleLines - 1)) { + fHoldSelection++; + if (fLines.get(fTopLineIndex + previousLineAtCaretPosition).rank % 2 == 0) { + fStyledText.setLineBackground(previousLineAtCaretPosition, 1, COLOR_BACKGROUND_EVEN); + } else { + fStyledText.setLineBackground(previousLineAtCaretPosition, 1, COLOR_BACKGROUND_ODD); + } + fSelectedLocation = null; + fTopLineIndex += Math.max(fNumVisibleLines - 1, 1); + loadLineData(); + updateTextArea(); + fHoldSelection--; + } + int line = Math.min(fNumVisibleLines - 1, fStyledText.getLineCount() - 1); + int offset = fStyledText.getOffsetAtLine(line); + fStyledText.setSelection(offset + Math.min(previousColumnAtCaretPosition, fLines.get(fTopLineIndex + line).string.length())); + break; + } + case SWT.ARROW_RIGHT: { + if (previousCaretOffset < fStyledText.getCharCount() || previousLineAtCaretPosition < (fNumVisibleLines - 2)) { + break; + } + fHoldSelection++; + fTopLineIndex++; + loadLineData(); + updateTextArea(); + fHoldSelection--; + fStyledText.setSelection(fStyledText.getCaretOffset() + 1); + break; + } + case SWT.ARROW_UP: { + if (previousLineAtCaretPosition > 0) { + break; + } + if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { + break; + } + fHoldSelection++; + fTopLineIndex--; + loadLineData(); + updateTextArea(); + fHoldSelection--; + LineData lineData = fLines.get(fTopLineIndex); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + fStyledText.setSelection(caretOffset); + break; + } + case SWT.PAGE_UP: { + if (previousLineAtCaretPosition > 0) { + break; + } + fHoldSelection++; + fTopLineIndex -= Math.max(fNumVisibleLines - 1, 1); + loadLineData(); + updateTextArea(); + fHoldSelection--; + LineData lineData = fLines.get(fTopLineIndex); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + fStyledText.setSelection(caretOffset); + break; + } + case SWT.ARROW_LEFT: { + if (previousCaretOffset > 0) { + break; + } + if (fLines.size() == 0) {// || (fTopLineIndex == 0 && fLines.get(0).rank == 0)) { + break; + } + long topRank = fLines.get(fTopLineIndex).rank; + fHoldSelection++; + fTopLineIndex--; + loadLineData(); + updateTextArea(); + fHoldSelection--; + LineData lineData = fLines.get(fTopLineIndex); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + if (topRank != fLines.get(fTopLineIndex).rank) { + fStyledText.setSelection(fLines.get(fTopLineIndex).string.length()); + } + break; + } + case SWT.HOME: { + if ((e.stateMask & SWT.CTRL) == 0) { + break; + } + //selectAndReveal(0); + setTopPosition(0.0); + LineData lineData = fLines.get(fTopLineIndex); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + break; + } + case SWT.END: { + if ((e.stateMask & SWT.CTRL) == 0) { + break; + } + //if (fTrace.getNbEvents() > 0) { + //selectAndReveal(fTrace.getNbEvents() - 1); + //} + double ratio = 1.0; + double delta = Math.pow(10, -15); + fLines.clear(); + while (fLines.size() == 0) { + setTopPosition(ratio); + if (ratio == 0.0) break; + delta = Math.min(delta * 10, 0.1); + ratio = Math.max(ratio - delta, 0.0); + } + LineData lineData = fLines.get(fTopLineIndex); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + break; + } + default: + break; + } + //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); + updateHighlightedRank(); + fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); + } + + @Override + public void keyReleased(KeyEvent e) { + } + + // ------------------------------------------------------------------------ + // CaretListener (StyledText) + // ------------------------------------------------------------------------ + + @Override + public void caretMoved(CaretEvent event) { + if (fHoldSelection == 0) { + int line = fStyledText.getLineAtOffset(event.caretOffset); + if (fTopLineIndex + line < fLines.size()) { + LineData lineData = fLines.get(fTopLineIndex + line); + if (!lineData.location.equals(fSelectedLocation)) { + fSelectedLocation = lineData.location; + refreshLineBackgrounds(); + sendSelectionEvent(lineData); + } + } + } + storeCaretPosition(event.time, event.caretOffset); + if (fHoldSelection == 0) { + Point caret = fStyledText.getLocationAtOffset(fStyledText.getCaretOffset()); + Point origin = fScrolledComposite.getOrigin(); + if (origin.x > caret.x) { + origin.x = caret.x; + } else if (caret.x - origin.x > fScrolledComposite.getSize().x) { + origin.x = caret.x - fScrolledComposite.getSize().x + 1; + } + fScrolledComposite.setOrigin(origin); + } + } + + // ------------------------------------------------------------------------ + // MouseMoveListener (StyledText) + // ------------------------------------------------------------------------ + + @Override + public void mouseMove(MouseEvent e) { + fCursorYCoordinate = e.y; + if (e.y < 0 || e.y > fStyledText.getSize().y) { + if (fHighlightedRank != Long.MIN_VALUE) { + fHighlightedRank = Long.MIN_VALUE; + refreshLineBackgrounds(); + } + return; + } + int offset = fStyledText.getOffsetAtLocation(new Point(0, e.y)); + int line = fStyledText.getLineAtOffset(offset); + if (line < fLines.size() - fTopLineIndex) { + LineData lineData = fLines.get(fTopLineIndex + line); + if (fHighlightedRank != lineData.rank) { + fHighlightedRank = lineData.rank; + refreshLineBackgrounds(); + } + } else { + if (fHighlightedRank != Long.MIN_VALUE) { + fHighlightedRank = Long.MIN_VALUE; + refreshLineBackgrounds(); + } + } + } + + // ------------------------------------------------------------------------ + // MouseTrackListener (StyledText) + // ------------------------------------------------------------------------ + + @Override + public void mouseExit(MouseEvent e) { + fCursorYCoordinate = -1; + if (fHighlightedRank != Long.MIN_VALUE) { + fHighlightedRank = Long.MIN_VALUE; + refreshLineBackgrounds(); + } + } + + @Override + public void mouseEnter(MouseEvent e) { + fCursorYCoordinate = e.y; + } + + @Override + public void mouseHover(MouseEvent e) { + } + + // ------------------------------------------------------------------------ + // MouseWheelListener (StyledText) + // ------------------------------------------------------------------------ + + @Override + public void mouseScrolled(MouseEvent e) { + if (fLines.size() == 0) { + return; + } + fHoldSelection++; + fTopLineIndex -= e.count; + loadLineData(); + updateTextArea(); + fHoldSelection = 0; + //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents()))); + updateHighlightedRank(); + fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location))); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphPresentationProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphPresentationProvider.java index 648b5da6a9..700eb58a8a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphPresentationProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphPresentationProvider.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.Map; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Rectangle; - -/** - * Interface for the time graph widget provider - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITimeGraphPresentationProvider { - - /** - * Returns the name of state types. - * - * @return the name of state types - */ - public String getStateTypeName(); - - /** - * Returns table of states with state name to state color relationship. - * - * @return table of states with color and name - * - * @see #getStateTableIndex - */ - public StateItem[] getStateTable(); - - /** - * Returns the index in the state table corresponding to this time event. - * The index should correspond to a state in the state table, - * otherwise the color SWT.COLOR_BLACK will be used. - * If the index returned is negative, the event will not be drawn. - * - * @param event the time event - * @return the corresponding state table index - * - * @see #getStateTable - */ - public int getStateTableIndex(ITimeEvent event); - - /** - * Called after drawing the control - * - * @param bounds - * The drawing rectangle - * @param gc - * The graphics context - */ - public void postDrawControl(Rectangle bounds, GC gc); - - /** - * Called after drawing an entry - * - * @param entry - * the entry that was drawn - * @param bounds - * the drawing rectangle - * @param gc - * the graphics context - */ - public void postDrawEntry(ITimeGraphEntry entry, Rectangle bounds, GC gc); - - /** - * Called after drawing an event - * - * @param event - * the event that was drawn - * @param bounds - * the drawing rectangle - * @param gc - * the graphics context - */ - public void postDrawEvent(ITimeEvent event, Rectangle bounds, GC gc); - - /** - * Returns the height of this item. This value is ignored if the time graph has a fixed item height. - * - * @param entry the entry - * @return the item height - * - * @see TimeGraphViewer#setItemHeight - */ - public int getItemHeight(ITimeGraphEntry entry); - - /** - * Provides the image icon for a given entry. - * - * @param entry the entry - * @return the image icon - */ - public Image getItemImage(ITimeGraphEntry entry); - - /** - * Returns the name of this event. - * - * @param event - * The event - * @return The event name - */ - public String getEventName(ITimeEvent event); - - /** - * Returns a map of name and value providing additional information - * to display in the tool tip for this event. - * - * @param event the time event - * @return a map of tool tip information - */ - public Map getEventHoverToolTipInfo(ITimeEvent event); - +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.Map; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; + +/** + * Interface for the time graph widget provider + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITimeGraphPresentationProvider { + + /** + * Returns the name of state types. + * + * @return the name of state types + */ + public String getStateTypeName(); + + /** + * Returns table of states with state name to state color relationship. + * + * @return table of states with color and name + * + * @see #getStateTableIndex + */ + public StateItem[] getStateTable(); + + /** + * Returns the index in the state table corresponding to this time event. + * The index should correspond to a state in the state table, + * otherwise the color SWT.COLOR_BLACK will be used. + * If the index returned is negative, the event will not be drawn. + * + * @param event the time event + * @return the corresponding state table index + * + * @see #getStateTable + */ + public int getStateTableIndex(ITimeEvent event); + + /** + * Called after drawing the control + * + * @param bounds + * The drawing rectangle + * @param gc + * The graphics context + */ + public void postDrawControl(Rectangle bounds, GC gc); + + /** + * Called after drawing an entry + * + * @param entry + * the entry that was drawn + * @param bounds + * the drawing rectangle + * @param gc + * the graphics context + */ + public void postDrawEntry(ITimeGraphEntry entry, Rectangle bounds, GC gc); + + /** + * Called after drawing an event + * + * @param event + * the event that was drawn + * @param bounds + * the drawing rectangle + * @param gc + * the graphics context + */ + public void postDrawEvent(ITimeEvent event, Rectangle bounds, GC gc); + + /** + * Returns the height of this item. This value is ignored if the time graph has a fixed item height. + * + * @param entry the entry + * @return the item height + * + * @see TimeGraphViewer#setItemHeight + */ + public int getItemHeight(ITimeGraphEntry entry); + + /** + * Provides the image icon for a given entry. + * + * @param entry the entry + * @return the image icon + */ + public Image getItemImage(ITimeGraphEntry entry); + + /** + * Returns the name of this event. + * + * @param event + * The event + * @return The event name + */ + public String getEventName(ITimeEvent event); + + /** + * Returns a map of name and value providing additional information + * to display in the tool tip for this event. + * + * @param event the time event + * @return a map of tool tip information + */ + public Map getEventHoverToolTipInfo(ITimeEvent event); + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphRangeListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphRangeListener.java index a0824db24d..77aee8593f 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphRangeListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphRangeListener.java @@ -1,31 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventListener; - -/** - * A listener which is notified when a timegraph changes its visible time range. - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITimeGraphRangeListener extends EventListener { - - /** - * Notifies that the timegraph range has changed. - * - * @param event event object describing details - */ - public void timeRangeUpdated(TimeGraphRangeUpdateEvent event); -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventListener; + +/** + * A listener which is notified when a timegraph changes its visible time range. + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITimeGraphRangeListener extends EventListener { + + /** + * Notifies that the timegraph range has changed. + * + * @param event event object describing details + */ + public void timeRangeUpdated(TimeGraphRangeUpdateEvent event); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphSelectionListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphSelectionListener.java index 40b93cbedf..456026eafc 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphSelectionListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphSelectionListener.java @@ -1,31 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventListener; - -/** - * A listener which is notified when a timegraph changes its selected time. - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITimeGraphSelectionListener extends EventListener { - - /** - * Notifies that the timegraph selected entry has changed. - * - * @param event event object describing details - */ - public void selectionChanged(TimeGraphSelectionEvent event); -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventListener; + +/** + * A listener which is notified when a timegraph changes its selected time. + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITimeGraphSelectionListener extends EventListener { + + /** + * Notifies that the timegraph selected entry has changed. + * + * @param event event object describing details + */ + public void selectionChanged(TimeGraphSelectionEvent event); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTimeListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTimeListener.java index 6bdd2e5abe..d3cd24e677 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTimeListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTimeListener.java @@ -1,31 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventListener; - -/** - * A listener which is notified when a timegraph changes its selected time. - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITimeGraphTimeListener extends EventListener { - - /** - * Notifies that the timegraph selected time has changed. - * - * @param event event object describing details - */ - public void timeSelected(TimeGraphTimeEvent event); -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventListener; + +/** + * A listener which is notified when a timegraph changes its selected time. + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITimeGraphTimeListener extends EventListener { + + /** + * Notifies that the timegraph selected time has changed. + * + * @param event event object describing details + */ + public void timeSelected(TimeGraphTimeEvent event); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTreeListener.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTreeListener.java index 7eb942b982..2e14dec03b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTreeListener.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/ITimeGraphTreeListener.java @@ -1,36 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -/** - * A listener which is notified when a timegraph expands or collapses an entry. - * - * @version 1.0 - * @author Patrick Tasse - */ -public interface ITimeGraphTreeListener { - - /** - * Notifies that an entry in the timegraph has been collapsed. - * - * @param event event object describing details - */ - public void treeCollapsed(TimeGraphTreeExpansionEvent event); - - /** - * Notifies that an entry in the timegraph has been expanded. - * - * @param event event object describing details - */ - public void treeExpanded(TimeGraphTreeExpansionEvent event); -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +/** + * A listener which is notified when a timegraph expands or collapses an entry. + * + * @version 1.0 + * @author Patrick Tasse + */ +public interface ITimeGraphTreeListener { + + /** + * Notifies that an entry in the timegraph has been collapsed. + * + * @param event event object describing details + */ + public void treeCollapsed(TimeGraphTreeExpansionEvent event); + + /** + * Notifies that an entry in the timegraph has been expanded. + * + * @param event event object describing details + */ + public void treeExpanded(TimeGraphTreeExpansionEvent event); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java index f8039cd4c0..10dd07d492 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java @@ -1,724 +1,724 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.ITreeViewerListener; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeExpansionEvent; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseTrackAdapter; -import org.eclipse.swt.events.MouseWheelListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Slider; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeColumn; -import org.eclipse.swt.widgets.TreeItem; - -/** - * Time graph "combo" view (with the list/tree on the left and the gantt chart - * on the right) - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeGraphCombo extends Composite { - - // ------------------------------------------------------------------------ - // Constants - // ------------------------------------------------------------------------ - - private static final Object FILLER = new Object(); - - // ------------------------------------------------------------------------ - // Fields - // ------------------------------------------------------------------------ - - // The tree viewer - private TreeViewer fTreeViewer; - - // The time viewer - private TimeGraphViewer fTimeGraphViewer; - - // The selection listener map - private final HashMap fSelectionListenerMap = new HashMap(); - - // Flag to block the tree selection changed listener when triggered by the time graph combo - private boolean fInhibitTreeSelection = false; - - // Number of filler rows used by the tree content provider - private int fNumFillerRows; - - // Calculated item height for Linux workaround - private int fLinuxItemHeight = 0; - - // ------------------------------------------------------------------------ - // Classes - // ------------------------------------------------------------------------ - - /** - * The TreeContentProviderWrapper is used to insert filler items after - * the elements of the tree's real content provider. - */ - private class TreeContentProviderWrapper implements ITreeContentProvider { - private final ITreeContentProvider contentProvider; - - public TreeContentProviderWrapper(ITreeContentProvider contentProvider) { - this.contentProvider = contentProvider; - } - - @Override - public void dispose() { - contentProvider.dispose(); - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - contentProvider.inputChanged(viewer, oldInput, newInput); - } - - @Override - public Object[] getElements(Object inputElement) { - Object[] elements = contentProvider.getElements(inputElement); - // add filler elements to ensure alignment with time analysis viewer - Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows, new Object[0].getClass()); - for (int i = 0; i < fNumFillerRows; i++) { - oElements[elements.length + i] = FILLER; - } - return oElements; - } - - @Override - public Object[] getChildren(Object parentElement) { - if (parentElement instanceof ITimeGraphEntry) { - return contentProvider.getChildren(parentElement); - } - return new Object[0]; - } - - @Override - public Object getParent(Object element) { - if (element instanceof ITimeGraphEntry) { - return contentProvider.getParent(element); - } - return null; - } - - @Override - public boolean hasChildren(Object element) { - if (element instanceof ITimeGraphEntry) { - return contentProvider.hasChildren(element); - } - return false; - } - } - - /** - * The TreeLabelProviderWrapper is used to intercept the filler items - * from the calls to the tree's real label provider. - */ - private class TreeLabelProviderWrapper implements ITableLabelProvider { - private final ITableLabelProvider labelProvider; - - public TreeLabelProviderWrapper(ITableLabelProvider labelProvider) { - this.labelProvider = labelProvider; - } - - @Override - public void addListener(ILabelProviderListener listener) { - labelProvider.addListener(listener); - } - - @Override - public void dispose() { - labelProvider.dispose(); - } - - @Override - public boolean isLabelProperty(Object element, String property) { - if (element instanceof ITimeGraphEntry) { - return labelProvider.isLabelProperty(element, property); - } - return false; - } - - @Override - public void removeListener(ILabelProviderListener listener) { - labelProvider.removeListener(listener); - } - - @Override - public Image getColumnImage(Object element, int columnIndex) { - if (element instanceof ITimeGraphEntry) { - return labelProvider.getColumnImage(element, columnIndex); - } - return null; - } - - @Override - public String getColumnText(Object element, int columnIndex) { - if (element instanceof ITimeGraphEntry) { - return labelProvider.getColumnText(element, columnIndex); - } - return null; - } - - } - - /** - * The SelectionListenerWrapper is used to intercept the filler items from - * the time graph combo's real selection listener, and to prevent double - * notifications from being sent when selection changes in both tree and - * time graph at the same time. - */ - private class SelectionListenerWrapper implements ISelectionChangedListener, ITimeGraphSelectionListener { - private final ITimeGraphSelectionListener listener; - private ITimeGraphEntry selection = null; - - public SelectionListenerWrapper(ITimeGraphSelectionListener listener) { - this.listener = listener; - } - - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (fInhibitTreeSelection) { - return; - } - Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); - if (element instanceof ITimeGraphEntry) { - ITimeGraphEntry entry = (ITimeGraphEntry) element; - if (entry != selection) { - selection = entry; - listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); - } - } - } - - @Override - public void selectionChanged(TimeGraphSelectionEvent event) { - ITimeGraphEntry entry = event.getSelection(); - if (entry != selection) { - selection = entry; - listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); - } - } - } - - // ------------------------------------------------------------------------ - // Constructors - // ------------------------------------------------------------------------ - - /** - * Constructs a new instance of this class given its parent - * and a style value describing its behavior and appearance. - * - * @param parent a widget which will be the parent of the new instance (cannot be null) - * @param style the style of widget to construct - */ - public TimeGraphCombo(Composite parent, int style) { - super(parent, style); - setLayout(new FillLayout()); - - final SashForm sash = new SashForm(this, SWT.NONE); - - fTreeViewer = new TreeViewer(sash, SWT.FULL_SELECTION | SWT.H_SCROLL); - final Tree tree = fTreeViewer.getTree(); - tree.setHeaderVisible(true); - tree.setLinesVisible(true); - - fTimeGraphViewer = new TimeGraphViewer(sash, SWT.NONE); - fTimeGraphViewer.setItemHeight(getItemHeight(tree)); - fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); - fTimeGraphViewer.setBorderWidth(tree.getBorderWidth()); - fTimeGraphViewer.setNameWidthPref(0); - - // Feature in Windows. The tree vertical bar reappears when - // the control is resized so we need to hide it again. - // Bug in Linux. The tree header height is 0 in constructor, - // so we need to reset it later when the control is resized. - tree.addControlListener(new ControlAdapter() { - int depth = 0; - @Override - public void controlResized(ControlEvent e) { - if (depth == 0) { - depth++; - tree.getVerticalBar().setEnabled(false); - // this can trigger controlResized recursively - tree.getVerticalBar().setVisible(false); - depth--; - } - fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); - } - }); - - // ensure synchronization of expanded items between tree and time graph - fTreeViewer.addTreeListener(new ITreeViewerListener() { - @Override - public void treeCollapsed(TreeExpansionEvent event) { - fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), false); - } - - @Override - public void treeExpanded(TreeExpansionEvent event) { - fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), true); - } - }); - - // ensure synchronization of expanded items between tree and time graph - fTimeGraphViewer.addTreeListener(new ITimeGraphTreeListener() { - @Override - public void treeCollapsed(TimeGraphTreeExpansionEvent event) { - fTreeViewer.setExpandedState(event.getEntry(), false); - } - - @Override - public void treeExpanded(TimeGraphTreeExpansionEvent event) { - fTreeViewer.setExpandedState(event.getEntry(), true); - } - }); - - // prevent mouse button from selecting a filler tree item - tree.addListener(SWT.MouseDown, new Listener() { - @Override - public void handleEvent(Event event) { - TreeItem treeItem = tree.getItem(new Point(event.x, event.y)); - if (treeItem == null || treeItem.getData() == FILLER) { - event.doit = false; - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - fTreeViewer.setSelection(new StructuredSelection()); - fTimeGraphViewer.setSelection(null); - return; - } - // this prevents from scrolling up when selecting - // the partially visible tree item at the bottom - tree.select(treeItems.get(treeItems.size() - 1)); - fTreeViewer.setSelection(new StructuredSelection()); - fTimeGraphViewer.setSelection(null); - } - } - }); - - // prevent mouse wheel from scrolling down into filler tree items - tree.addListener(SWT.MouseWheel, new Listener() { - @Override - public void handleEvent(Event event) { - event.doit = false; - Slider scrollBar = fTimeGraphViewer.getVerticalBar(); - fTimeGraphViewer.setTopIndex(scrollBar.getSelection() - event.count); - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - }); - - // prevent key stroke from selecting a filler tree item - tree.addListener(SWT.KeyDown, new Listener() { - @Override - public void handleEvent(Event event) { - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - fTreeViewer.setSelection(new StructuredSelection()); - event.doit = false; - return; - } - if (event.keyCode == SWT.ARROW_DOWN) { - int index = Math.min(fTimeGraphViewer.getSelectionIndex() + 1, treeItems.size() - 1); - fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); - event.doit = false; - } else if (event.keyCode == SWT.PAGE_DOWN) { - int height = tree.getSize().y - tree.getHeaderHeight() - tree.getHorizontalBar().getSize().y; - int countPerPage = height / getItemHeight(tree); - int index = Math.min(fTimeGraphViewer.getSelectionIndex() + countPerPage - 1, treeItems.size() - 1); - fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); - event.doit = false; - } else if (event.keyCode == SWT.END) { - fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(treeItems.size() - 1).getData()); - event.doit = false; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - if (fTimeGraphViewer.getSelectionIndex() >= 0) { - fTreeViewer.setSelection(new StructuredSelection(fTimeGraphViewer.getSelection())); - } else { - fTreeViewer.setSelection(new StructuredSelection()); - } - } - }); - - // ensure alignment of top item between tree and time graph - fTimeGraphViewer.getTimeGraphControl().addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent e) { - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - }); - - // ensure synchronization of selected item between tree and time graph - fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { - @Override - public void selectionChanged(SelectionChangedEvent event) { - if (fInhibitTreeSelection) { - return; - } - if (event.getSelection() instanceof IStructuredSelection) { - Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); - if (selection instanceof ITimeGraphEntry) { - fTimeGraphViewer.setSelection((ITimeGraphEntry) selection); - } - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - } - }); - - // ensure synchronization of selected item between tree and time graph - fTimeGraphViewer.addSelectionListener(new ITimeGraphSelectionListener() { - @Override - public void selectionChanged(TimeGraphSelectionEvent event) { - ITimeGraphEntry entry = fTimeGraphViewer.getSelection(); - fInhibitTreeSelection = true; // block the tree selection changed listener - if (entry != null) { - StructuredSelection selection = new StructuredSelection(entry); - fTreeViewer.setSelection(selection); - } else { - fTreeViewer.setSelection(new StructuredSelection()); - } - fInhibitTreeSelection = false; - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - }); - - // ensure alignment of top item between tree and time graph - fTimeGraphViewer.getVerticalBar().addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - }); - - // ensure alignment of top item between tree and time graph - fTimeGraphViewer.getTimeGraphControl().addMouseWheelListener(new MouseWheelListener() { - @Override - public void mouseScrolled(MouseEvent e) { - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - tree.setTopItem(treeItem); - } - }); - - // ensure the tree has focus control when mouse is over it if the time graph had control - fTreeViewer.getControl().addMouseTrackListener(new MouseTrackAdapter() { - @Override - public void mouseEnter(MouseEvent e) { - if (fTimeGraphViewer.getTimeGraphControl().isFocusControl()) { - fTreeViewer.getControl().setFocus(); - } - } - }); - - // ensure the time graph has focus control when mouse is over it if the tree had control - fTimeGraphViewer.getTimeGraphControl().addMouseTrackListener(new MouseTrackAdapter() { - @Override - public void mouseEnter(MouseEvent e) { - if (fTreeViewer.getControl().isFocusControl()) { - fTimeGraphViewer.getTimeGraphControl().setFocus(); - } - } - }); - fTimeGraphViewer.getTimeGraphScale().addMouseTrackListener(new MouseTrackAdapter() { - @Override - public void mouseEnter(MouseEvent e) { - if (fTreeViewer.getControl().isFocusControl()) { - fTimeGraphViewer.getTimeGraphControl().setFocus(); - } - } - }); - - // The filler rows are required to ensure alignment when the tree does not have a - // visible horizontal scroll bar. The tree does not allow its top item to be set - // to a value that would cause blank space to be drawn at the bottom of the tree. - fNumFillerRows = Display.getDefault().getBounds().height / getItemHeight(tree); - - sash.setWeights(new int[] { 1, 1 }); - } - - // ------------------------------------------------------------------------ - // Accessors - // ------------------------------------------------------------------------ - - /** - * Returns this time graph combo's tree viewer. - * - * @return the tree viewer - */ - public TreeViewer getTreeViewer() { - return fTreeViewer; - } - - /** - * Returns this time graph combo's time graph viewer. - * - * @return the time graph viewer - */ - public TimeGraphViewer getTimeGraphViewer() { - return fTimeGraphViewer; - } - - // ------------------------------------------------------------------------ - // Control - // ------------------------------------------------------------------------ - - /* (non-Javadoc) - * @see org.eclipse.swt.widgets.Control#redraw() - */ - @Override - public void redraw() { - fTimeGraphViewer.getControl().redraw(); - super.redraw(); - } - - // ------------------------------------------------------------------------ - // Operations - // ------------------------------------------------------------------------ - - /** - * Sets the tree content provider used by this time graph combo. - * - * @param contentProvider the tree content provider - */ - public void setTreeContentProvider(ITreeContentProvider contentProvider) { - fTreeViewer.setContentProvider(new TreeContentProviderWrapper(contentProvider)); - } - - /** - * Sets the tree label provider used by this time graph combo. - * - * @param labelProvider the tree label provider - */ - public void setTreeLabelProvider(ITableLabelProvider labelProvider) { - fTreeViewer.setLabelProvider(new TreeLabelProviderWrapper(labelProvider)); - } - - /** - * Sets the tree columns for this time graph combo. - * - * @param columnNames the tree column names - */ - public void setTreeColumns(String[] columnNames) { - final Tree tree = fTreeViewer.getTree(); - for (String columnName : columnNames) { - TreeColumn column = new TreeColumn(tree, SWT.LEFT); - column.setText(columnName); - column.pack(); - } - } - - - /** - * Sets the time graph provider used by this time graph combo. - * - * @param timeGraphProvider the time graph provider - */ - public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) { - fTimeGraphViewer.setTimeGraphProvider(timeGraphProvider); - } - - /** - * Sets or clears the input for this time graph combo. - * The input array should only contain top-level elements. - * - * @param input the input of this time graph combo, or null if none - */ - public void setInput(ITimeGraphEntry[] input) { - fInhibitTreeSelection = true; - fTreeViewer.setInput(input); - for (SelectionListenerWrapper listenerWrapper : fSelectionListenerMap.values()) { - listenerWrapper.selection = null; - } - fInhibitTreeSelection = false; - fTreeViewer.expandAll(); - fTreeViewer.getTree().getVerticalBar().setEnabled(false); - fTreeViewer.getTree().getVerticalBar().setVisible(false); - fTimeGraphViewer.setItemHeight(getItemHeight(fTreeViewer.getTree())); - fTimeGraphViewer.setInput(input); - } - - /** - * Refreshes this time graph completely with information freshly obtained from its model. - */ - public void refresh() { - fTreeViewer.refresh(); - fTimeGraphViewer.refresh(); - } - - /** - * Adds a listener for selection changes in this time graph combo. - * - * @param listener a selection listener - */ - public void addSelectionListener(ITimeGraphSelectionListener listener) { - SelectionListenerWrapper listenerWrapper = new SelectionListenerWrapper(listener); - fTreeViewer.addSelectionChangedListener(listenerWrapper); - fSelectionListenerMap.put(listener, listenerWrapper); - fTimeGraphViewer.addSelectionListener(listenerWrapper); - } - - /** - * Removes the given selection listener from this time graph combo. - * - * @param listener a selection changed listener - */ - public void removeSelectionListener(ITimeGraphSelectionListener listener) { - SelectionListenerWrapper listenerWrapper = fSelectionListenerMap.remove(listener); - fTreeViewer.removeSelectionChangedListener(listenerWrapper); - fTimeGraphViewer.removeSelectionListener(listenerWrapper); - } - - /** - * Sets the current selection for this time graph combo. - * - * @param selection the new selection - */ - public void setSelection(ITimeGraphEntry selection) { - fTimeGraphViewer.setSelection(selection); - fInhibitTreeSelection = true; // block the tree selection changed listener - if (selection != null) { - StructuredSelection structuredSelection = new StructuredSelection(selection); - fTreeViewer.setSelection(structuredSelection); - } else { - fTreeViewer.setSelection(new StructuredSelection()); - } - fInhibitTreeSelection = false; - ArrayList treeItems = getVisibleExpandedItems(fTreeViewer.getTree()); - if (treeItems.size() == 0) { - return; - } - TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); - fTreeViewer.getTree().setTopItem(treeItem); - } - - // ------------------------------------------------------------------------ - // Internal - // ------------------------------------------------------------------------ - - private ArrayList getVisibleExpandedItems(Tree tree) { - ArrayList items = new ArrayList(); - for (TreeItem item : tree.getItems()) { - if (item.getData() == FILLER) { - break; - } - items.add(item); - if (item.getExpanded()) { - items.addAll(getVisibleExpandedItems(item)); - } - } - return items; - } - - private ArrayList getVisibleExpandedItems(TreeItem treeItem) { - ArrayList items = new ArrayList(); - for (TreeItem item : treeItem.getItems()) { - items.add(item); - if (item.getExpanded()) { - items.addAll(getVisibleExpandedItems(item)); - } - } - return items; - } - - private int getItemHeight(final Tree tree) { - /* - * Bug in Linux. The method getItemHeight doesn't always return the correct value. - */ - if (fLinuxItemHeight >= 0 && System.getProperty("os.name").contains("Linux")) { //$NON-NLS-1$ //$NON-NLS-2$ - if (fLinuxItemHeight != 0) { - return fLinuxItemHeight; - } - ArrayList treeItems = getVisibleExpandedItems(tree); - if (treeItems.size() > 1) { - final TreeItem treeItem0 = treeItems.get(0); - final TreeItem treeItem1 = treeItems.get(1); - PaintListener paintListener = new PaintListener() { - @Override - public void paintControl(PaintEvent e) { - tree.removePaintListener(this); - int y0 = treeItem0.getBounds().y; - int y1 = treeItem1.getBounds().y; - int itemHeight = y1 - y0; - if (itemHeight > 0) { - fLinuxItemHeight = itemHeight; - fTimeGraphViewer.setItemHeight(itemHeight); - } - } - }; - tree.addPaintListener(paintListener); - } - } else { - fLinuxItemHeight = -1; // Not Linux, don't perform os.name check anymore - } - return tree.getItemHeight(); - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.ITreeViewerListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeExpansionEvent; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseTrackAdapter; +import org.eclipse.swt.events.MouseWheelListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Slider; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeColumn; +import org.eclipse.swt.widgets.TreeItem; + +/** + * Time graph "combo" view (with the list/tree on the left and the gantt chart + * on the right) + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeGraphCombo extends Composite { + + // ------------------------------------------------------------------------ + // Constants + // ------------------------------------------------------------------------ + + private static final Object FILLER = new Object(); + + // ------------------------------------------------------------------------ + // Fields + // ------------------------------------------------------------------------ + + // The tree viewer + private TreeViewer fTreeViewer; + + // The time viewer + private TimeGraphViewer fTimeGraphViewer; + + // The selection listener map + private final HashMap fSelectionListenerMap = new HashMap(); + + // Flag to block the tree selection changed listener when triggered by the time graph combo + private boolean fInhibitTreeSelection = false; + + // Number of filler rows used by the tree content provider + private int fNumFillerRows; + + // Calculated item height for Linux workaround + private int fLinuxItemHeight = 0; + + // ------------------------------------------------------------------------ + // Classes + // ------------------------------------------------------------------------ + + /** + * The TreeContentProviderWrapper is used to insert filler items after + * the elements of the tree's real content provider. + */ + private class TreeContentProviderWrapper implements ITreeContentProvider { + private final ITreeContentProvider contentProvider; + + public TreeContentProviderWrapper(ITreeContentProvider contentProvider) { + this.contentProvider = contentProvider; + } + + @Override + public void dispose() { + contentProvider.dispose(); + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + contentProvider.inputChanged(viewer, oldInput, newInput); + } + + @Override + public Object[] getElements(Object inputElement) { + Object[] elements = contentProvider.getElements(inputElement); + // add filler elements to ensure alignment with time analysis viewer + Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows, new Object[0].getClass()); + for (int i = 0; i < fNumFillerRows; i++) { + oElements[elements.length + i] = FILLER; + } + return oElements; + } + + @Override + public Object[] getChildren(Object parentElement) { + if (parentElement instanceof ITimeGraphEntry) { + return contentProvider.getChildren(parentElement); + } + return new Object[0]; + } + + @Override + public Object getParent(Object element) { + if (element instanceof ITimeGraphEntry) { + return contentProvider.getParent(element); + } + return null; + } + + @Override + public boolean hasChildren(Object element) { + if (element instanceof ITimeGraphEntry) { + return contentProvider.hasChildren(element); + } + return false; + } + } + + /** + * The TreeLabelProviderWrapper is used to intercept the filler items + * from the calls to the tree's real label provider. + */ + private class TreeLabelProviderWrapper implements ITableLabelProvider { + private final ITableLabelProvider labelProvider; + + public TreeLabelProviderWrapper(ITableLabelProvider labelProvider) { + this.labelProvider = labelProvider; + } + + @Override + public void addListener(ILabelProviderListener listener) { + labelProvider.addListener(listener); + } + + @Override + public void dispose() { + labelProvider.dispose(); + } + + @Override + public boolean isLabelProperty(Object element, String property) { + if (element instanceof ITimeGraphEntry) { + return labelProvider.isLabelProperty(element, property); + } + return false; + } + + @Override + public void removeListener(ILabelProviderListener listener) { + labelProvider.removeListener(listener); + } + + @Override + public Image getColumnImage(Object element, int columnIndex) { + if (element instanceof ITimeGraphEntry) { + return labelProvider.getColumnImage(element, columnIndex); + } + return null; + } + + @Override + public String getColumnText(Object element, int columnIndex) { + if (element instanceof ITimeGraphEntry) { + return labelProvider.getColumnText(element, columnIndex); + } + return null; + } + + } + + /** + * The SelectionListenerWrapper is used to intercept the filler items from + * the time graph combo's real selection listener, and to prevent double + * notifications from being sent when selection changes in both tree and + * time graph at the same time. + */ + private class SelectionListenerWrapper implements ISelectionChangedListener, ITimeGraphSelectionListener { + private final ITimeGraphSelectionListener listener; + private ITimeGraphEntry selection = null; + + public SelectionListenerWrapper(ITimeGraphSelectionListener listener) { + this.listener = listener; + } + + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (fInhibitTreeSelection) { + return; + } + Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); + if (element instanceof ITimeGraphEntry) { + ITimeGraphEntry entry = (ITimeGraphEntry) element; + if (entry != selection) { + selection = entry; + listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); + } + } + } + + @Override + public void selectionChanged(TimeGraphSelectionEvent event) { + ITimeGraphEntry entry = event.getSelection(); + if (entry != selection) { + selection = entry; + listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); + } + } + } + + // ------------------------------------------------------------------------ + // Constructors + // ------------------------------------------------------------------------ + + /** + * Constructs a new instance of this class given its parent + * and a style value describing its behavior and appearance. + * + * @param parent a widget which will be the parent of the new instance (cannot be null) + * @param style the style of widget to construct + */ + public TimeGraphCombo(Composite parent, int style) { + super(parent, style); + setLayout(new FillLayout()); + + final SashForm sash = new SashForm(this, SWT.NONE); + + fTreeViewer = new TreeViewer(sash, SWT.FULL_SELECTION | SWT.H_SCROLL); + final Tree tree = fTreeViewer.getTree(); + tree.setHeaderVisible(true); + tree.setLinesVisible(true); + + fTimeGraphViewer = new TimeGraphViewer(sash, SWT.NONE); + fTimeGraphViewer.setItemHeight(getItemHeight(tree)); + fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); + fTimeGraphViewer.setBorderWidth(tree.getBorderWidth()); + fTimeGraphViewer.setNameWidthPref(0); + + // Feature in Windows. The tree vertical bar reappears when + // the control is resized so we need to hide it again. + // Bug in Linux. The tree header height is 0 in constructor, + // so we need to reset it later when the control is resized. + tree.addControlListener(new ControlAdapter() { + int depth = 0; + @Override + public void controlResized(ControlEvent e) { + if (depth == 0) { + depth++; + tree.getVerticalBar().setEnabled(false); + // this can trigger controlResized recursively + tree.getVerticalBar().setVisible(false); + depth--; + } + fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); + } + }); + + // ensure synchronization of expanded items between tree and time graph + fTreeViewer.addTreeListener(new ITreeViewerListener() { + @Override + public void treeCollapsed(TreeExpansionEvent event) { + fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), false); + } + + @Override + public void treeExpanded(TreeExpansionEvent event) { + fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), true); + } + }); + + // ensure synchronization of expanded items between tree and time graph + fTimeGraphViewer.addTreeListener(new ITimeGraphTreeListener() { + @Override + public void treeCollapsed(TimeGraphTreeExpansionEvent event) { + fTreeViewer.setExpandedState(event.getEntry(), false); + } + + @Override + public void treeExpanded(TimeGraphTreeExpansionEvent event) { + fTreeViewer.setExpandedState(event.getEntry(), true); + } + }); + + // prevent mouse button from selecting a filler tree item + tree.addListener(SWT.MouseDown, new Listener() { + @Override + public void handleEvent(Event event) { + TreeItem treeItem = tree.getItem(new Point(event.x, event.y)); + if (treeItem == null || treeItem.getData() == FILLER) { + event.doit = false; + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + fTreeViewer.setSelection(new StructuredSelection()); + fTimeGraphViewer.setSelection(null); + return; + } + // this prevents from scrolling up when selecting + // the partially visible tree item at the bottom + tree.select(treeItems.get(treeItems.size() - 1)); + fTreeViewer.setSelection(new StructuredSelection()); + fTimeGraphViewer.setSelection(null); + } + } + }); + + // prevent mouse wheel from scrolling down into filler tree items + tree.addListener(SWT.MouseWheel, new Listener() { + @Override + public void handleEvent(Event event) { + event.doit = false; + Slider scrollBar = fTimeGraphViewer.getVerticalBar(); + fTimeGraphViewer.setTopIndex(scrollBar.getSelection() - event.count); + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + }); + + // prevent key stroke from selecting a filler tree item + tree.addListener(SWT.KeyDown, new Listener() { + @Override + public void handleEvent(Event event) { + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + fTreeViewer.setSelection(new StructuredSelection()); + event.doit = false; + return; + } + if (event.keyCode == SWT.ARROW_DOWN) { + int index = Math.min(fTimeGraphViewer.getSelectionIndex() + 1, treeItems.size() - 1); + fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); + event.doit = false; + } else if (event.keyCode == SWT.PAGE_DOWN) { + int height = tree.getSize().y - tree.getHeaderHeight() - tree.getHorizontalBar().getSize().y; + int countPerPage = height / getItemHeight(tree); + int index = Math.min(fTimeGraphViewer.getSelectionIndex() + countPerPage - 1, treeItems.size() - 1); + fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); + event.doit = false; + } else if (event.keyCode == SWT.END) { + fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(treeItems.size() - 1).getData()); + event.doit = false; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + if (fTimeGraphViewer.getSelectionIndex() >= 0) { + fTreeViewer.setSelection(new StructuredSelection(fTimeGraphViewer.getSelection())); + } else { + fTreeViewer.setSelection(new StructuredSelection()); + } + } + }); + + // ensure alignment of top item between tree and time graph + fTimeGraphViewer.getTimeGraphControl().addControlListener(new ControlAdapter() { + @Override + public void controlResized(ControlEvent e) { + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + }); + + // ensure synchronization of selected item between tree and time graph + fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent event) { + if (fInhibitTreeSelection) { + return; + } + if (event.getSelection() instanceof IStructuredSelection) { + Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); + if (selection instanceof ITimeGraphEntry) { + fTimeGraphViewer.setSelection((ITimeGraphEntry) selection); + } + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + } + }); + + // ensure synchronization of selected item between tree and time graph + fTimeGraphViewer.addSelectionListener(new ITimeGraphSelectionListener() { + @Override + public void selectionChanged(TimeGraphSelectionEvent event) { + ITimeGraphEntry entry = fTimeGraphViewer.getSelection(); + fInhibitTreeSelection = true; // block the tree selection changed listener + if (entry != null) { + StructuredSelection selection = new StructuredSelection(entry); + fTreeViewer.setSelection(selection); + } else { + fTreeViewer.setSelection(new StructuredSelection()); + } + fInhibitTreeSelection = false; + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + }); + + // ensure alignment of top item between tree and time graph + fTimeGraphViewer.getVerticalBar().addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + }); + + // ensure alignment of top item between tree and time graph + fTimeGraphViewer.getTimeGraphControl().addMouseWheelListener(new MouseWheelListener() { + @Override + public void mouseScrolled(MouseEvent e) { + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + tree.setTopItem(treeItem); + } + }); + + // ensure the tree has focus control when mouse is over it if the time graph had control + fTreeViewer.getControl().addMouseTrackListener(new MouseTrackAdapter() { + @Override + public void mouseEnter(MouseEvent e) { + if (fTimeGraphViewer.getTimeGraphControl().isFocusControl()) { + fTreeViewer.getControl().setFocus(); + } + } + }); + + // ensure the time graph has focus control when mouse is over it if the tree had control + fTimeGraphViewer.getTimeGraphControl().addMouseTrackListener(new MouseTrackAdapter() { + @Override + public void mouseEnter(MouseEvent e) { + if (fTreeViewer.getControl().isFocusControl()) { + fTimeGraphViewer.getTimeGraphControl().setFocus(); + } + } + }); + fTimeGraphViewer.getTimeGraphScale().addMouseTrackListener(new MouseTrackAdapter() { + @Override + public void mouseEnter(MouseEvent e) { + if (fTreeViewer.getControl().isFocusControl()) { + fTimeGraphViewer.getTimeGraphControl().setFocus(); + } + } + }); + + // The filler rows are required to ensure alignment when the tree does not have a + // visible horizontal scroll bar. The tree does not allow its top item to be set + // to a value that would cause blank space to be drawn at the bottom of the tree. + fNumFillerRows = Display.getDefault().getBounds().height / getItemHeight(tree); + + sash.setWeights(new int[] { 1, 1 }); + } + + // ------------------------------------------------------------------------ + // Accessors + // ------------------------------------------------------------------------ + + /** + * Returns this time graph combo's tree viewer. + * + * @return the tree viewer + */ + public TreeViewer getTreeViewer() { + return fTreeViewer; + } + + /** + * Returns this time graph combo's time graph viewer. + * + * @return the time graph viewer + */ + public TimeGraphViewer getTimeGraphViewer() { + return fTimeGraphViewer; + } + + // ------------------------------------------------------------------------ + // Control + // ------------------------------------------------------------------------ + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.Control#redraw() + */ + @Override + public void redraw() { + fTimeGraphViewer.getControl().redraw(); + super.redraw(); + } + + // ------------------------------------------------------------------------ + // Operations + // ------------------------------------------------------------------------ + + /** + * Sets the tree content provider used by this time graph combo. + * + * @param contentProvider the tree content provider + */ + public void setTreeContentProvider(ITreeContentProvider contentProvider) { + fTreeViewer.setContentProvider(new TreeContentProviderWrapper(contentProvider)); + } + + /** + * Sets the tree label provider used by this time graph combo. + * + * @param labelProvider the tree label provider + */ + public void setTreeLabelProvider(ITableLabelProvider labelProvider) { + fTreeViewer.setLabelProvider(new TreeLabelProviderWrapper(labelProvider)); + } + + /** + * Sets the tree columns for this time graph combo. + * + * @param columnNames the tree column names + */ + public void setTreeColumns(String[] columnNames) { + final Tree tree = fTreeViewer.getTree(); + for (String columnName : columnNames) { + TreeColumn column = new TreeColumn(tree, SWT.LEFT); + column.setText(columnName); + column.pack(); + } + } + + + /** + * Sets the time graph provider used by this time graph combo. + * + * @param timeGraphProvider the time graph provider + */ + public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) { + fTimeGraphViewer.setTimeGraphProvider(timeGraphProvider); + } + + /** + * Sets or clears the input for this time graph combo. + * The input array should only contain top-level elements. + * + * @param input the input of this time graph combo, or null if none + */ + public void setInput(ITimeGraphEntry[] input) { + fInhibitTreeSelection = true; + fTreeViewer.setInput(input); + for (SelectionListenerWrapper listenerWrapper : fSelectionListenerMap.values()) { + listenerWrapper.selection = null; + } + fInhibitTreeSelection = false; + fTreeViewer.expandAll(); + fTreeViewer.getTree().getVerticalBar().setEnabled(false); + fTreeViewer.getTree().getVerticalBar().setVisible(false); + fTimeGraphViewer.setItemHeight(getItemHeight(fTreeViewer.getTree())); + fTimeGraphViewer.setInput(input); + } + + /** + * Refreshes this time graph completely with information freshly obtained from its model. + */ + public void refresh() { + fTreeViewer.refresh(); + fTimeGraphViewer.refresh(); + } + + /** + * Adds a listener for selection changes in this time graph combo. + * + * @param listener a selection listener + */ + public void addSelectionListener(ITimeGraphSelectionListener listener) { + SelectionListenerWrapper listenerWrapper = new SelectionListenerWrapper(listener); + fTreeViewer.addSelectionChangedListener(listenerWrapper); + fSelectionListenerMap.put(listener, listenerWrapper); + fTimeGraphViewer.addSelectionListener(listenerWrapper); + } + + /** + * Removes the given selection listener from this time graph combo. + * + * @param listener a selection changed listener + */ + public void removeSelectionListener(ITimeGraphSelectionListener listener) { + SelectionListenerWrapper listenerWrapper = fSelectionListenerMap.remove(listener); + fTreeViewer.removeSelectionChangedListener(listenerWrapper); + fTimeGraphViewer.removeSelectionListener(listenerWrapper); + } + + /** + * Sets the current selection for this time graph combo. + * + * @param selection the new selection + */ + public void setSelection(ITimeGraphEntry selection) { + fTimeGraphViewer.setSelection(selection); + fInhibitTreeSelection = true; // block the tree selection changed listener + if (selection != null) { + StructuredSelection structuredSelection = new StructuredSelection(selection); + fTreeViewer.setSelection(structuredSelection); + } else { + fTreeViewer.setSelection(new StructuredSelection()); + } + fInhibitTreeSelection = false; + ArrayList treeItems = getVisibleExpandedItems(fTreeViewer.getTree()); + if (treeItems.size() == 0) { + return; + } + TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); + fTreeViewer.getTree().setTopItem(treeItem); + } + + // ------------------------------------------------------------------------ + // Internal + // ------------------------------------------------------------------------ + + private ArrayList getVisibleExpandedItems(Tree tree) { + ArrayList items = new ArrayList(); + for (TreeItem item : tree.getItems()) { + if (item.getData() == FILLER) { + break; + } + items.add(item); + if (item.getExpanded()) { + items.addAll(getVisibleExpandedItems(item)); + } + } + return items; + } + + private ArrayList getVisibleExpandedItems(TreeItem treeItem) { + ArrayList items = new ArrayList(); + for (TreeItem item : treeItem.getItems()) { + items.add(item); + if (item.getExpanded()) { + items.addAll(getVisibleExpandedItems(item)); + } + } + return items; + } + + private int getItemHeight(final Tree tree) { + /* + * Bug in Linux. The method getItemHeight doesn't always return the correct value. + */ + if (fLinuxItemHeight >= 0 && System.getProperty("os.name").contains("Linux")) { //$NON-NLS-1$ //$NON-NLS-2$ + if (fLinuxItemHeight != 0) { + return fLinuxItemHeight; + } + ArrayList treeItems = getVisibleExpandedItems(tree); + if (treeItems.size() > 1) { + final TreeItem treeItem0 = treeItems.get(0); + final TreeItem treeItem1 = treeItems.get(1); + PaintListener paintListener = new PaintListener() { + @Override + public void paintControl(PaintEvent e) { + tree.removePaintListener(this); + int y0 = treeItem0.getBounds().y; + int y1 = treeItem1.getBounds().y; + int itemHeight = y1 - y0; + if (itemHeight > 0) { + fLinuxItemHeight = itemHeight; + fTimeGraphViewer.setItemHeight(itemHeight); + } + } + }; + tree.addPaintListener(paintListener); + } + } else { + fLinuxItemHeight = -1; // Not Linux, don't perform os.name check anymore + } + return tree.getItemHeight(); + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphPresentationProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphPresentationProvider.java index de63a2f7cf..b30179cc9a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphPresentationProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphPresentationProvider.java @@ -1,133 +1,133 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon - Initial API and implementation - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.Map; - -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Rectangle; - -/** - * Provider class for the time graph provider - * - * @version 1.0 - * @author Patrick Tasse - * - */ -public class TimeGraphPresentationProvider implements ITimeGraphPresentationProvider { - - // ------------------------------------------------------------------------ - // Constants - // ------------------------------------------------------------------------ - private static final int DEFAULT_ITEM_HEIGHT = 19; - - // ------------------------------------------------------------------------ - // Operations - // ------------------------------------------------------------------------ - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getStateTypeName() - */ - @Override - public String getStateTypeName() { - return Messages.TmfTimeLegend_TRACE_STATES; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getStateTable() - */ - @Override - public StateItem[] getStateTable() { - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventTableIndex(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) - */ - @Override - public int getStateTableIndex(ITimeEvent event) { - return 0; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawControl(org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) - */ - @Override - public void postDrawControl(Rectangle bounds, GC gc) { - // Override to add own drawing code - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawEntry(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry, org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) - */ - @Override - public void postDrawEntry(ITimeGraphEntry entry, Rectangle bounds, GC gc) { - // Override to add own drawing code - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawEvent(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent, org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) - */ - @Override - public void postDrawEvent(ITimeEvent event, Rectangle bounds, GC gc) { - // Override to add own drawing code - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getItemHeight(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry) - */ - @Override - public int getItemHeight(ITimeGraphEntry entry) { - return DEFAULT_ITEM_HEIGHT; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getItemImage(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry) - */ - @Override - public Image getItemImage(ITimeGraphEntry entry) { - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventName(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) - */ - @Override - public String getEventName(ITimeEvent event) { - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventHoverToolTipInfo(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) - */ - @Override - public Map getEventHoverToolTipInfo(ITimeEvent event) { - return null; - } - +/******************************************************************************* + * Copyright (c) 2009, 2010, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon - Initial API and implementation + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.Map; + +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; + +/** + * Provider class for the time graph provider + * + * @version 1.0 + * @author Patrick Tasse + * + */ +public class TimeGraphPresentationProvider implements ITimeGraphPresentationProvider { + + // ------------------------------------------------------------------------ + // Constants + // ------------------------------------------------------------------------ + private static final int DEFAULT_ITEM_HEIGHT = 19; + + // ------------------------------------------------------------------------ + // Operations + // ------------------------------------------------------------------------ + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getStateTypeName() + */ + @Override + public String getStateTypeName() { + return Messages.TmfTimeLegend_TRACE_STATES; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getStateTable() + */ + @Override + public StateItem[] getStateTable() { + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventTableIndex(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) + */ + @Override + public int getStateTableIndex(ITimeEvent event) { + return 0; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawControl(org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) + */ + @Override + public void postDrawControl(Rectangle bounds, GC gc) { + // Override to add own drawing code + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawEntry(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry, org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) + */ + @Override + public void postDrawEntry(ITimeGraphEntry entry, Rectangle bounds, GC gc) { + // Override to add own drawing code + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#postDrawEvent(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent, org.eclipse.swt.graphics.Rectangle, org.eclipse.swt.graphics.GC) + */ + @Override + public void postDrawEvent(ITimeEvent event, Rectangle bounds, GC gc) { + // Override to add own drawing code + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getItemHeight(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry) + */ + @Override + public int getItemHeight(ITimeGraphEntry entry) { + return DEFAULT_ITEM_HEIGHT; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getItemImage(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry) + */ + @Override + public Image getItemImage(ITimeGraphEntry entry) { + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventName(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) + */ + @Override + public String getEventName(ITimeEvent event) { + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider#getEventHoverToolTipInfo(org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent) + */ + @Override + public Map getEventHoverToolTipInfo(ITimeEvent event) { + return null; + } + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphRangeUpdateEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphRangeUpdateEvent.java index 2013b1bceb..1d59f51e3a 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphRangeUpdateEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphRangeUpdateEvent.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventObject; - -/** - * Notifier for the time graph that the time range has been updated. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeGraphRangeUpdateEvent extends EventObject { - - /** - * Default serial version UID for this class. - * @since 1.0 - */ - private static final long serialVersionUID = 1L; - - /** - * The start time. - */ - private final long fStartTime; - - /** - * The end time. - */ - private final long fEndTime; - - /** - * Standard constructor - * - * @param source - * The source of this event - * @param startTime - * The start time - * @param endTime - * The end time - */ - public TimeGraphRangeUpdateEvent(Object source, long startTime, long endTime) { - super(source); - fStartTime = startTime; - fEndTime = endTime; - } - - /** - * @return the start time - */ - public long getStartTime() { - return fStartTime; - } - - /** - * @return the end time - */ - public long getEndTime() { - return fEndTime; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventObject; + +/** + * Notifier for the time graph that the time range has been updated. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeGraphRangeUpdateEvent extends EventObject { + + /** + * Default serial version UID for this class. + * @since 1.0 + */ + private static final long serialVersionUID = 1L; + + /** + * The start time. + */ + private final long fStartTime; + + /** + * The end time. + */ + private final long fEndTime; + + /** + * Standard constructor + * + * @param source + * The source of this event + * @param startTime + * The start time + * @param endTime + * The end time + */ + public TimeGraphRangeUpdateEvent(Object source, long startTime, long endTime) { + super(source); + fStartTime = startTime; + fEndTime = endTime; + } + + /** + * @return the start time + */ + public long getStartTime() { + return fStartTime; + } + + /** + * @return the end time + */ + public long getEndTime() { + return fEndTime; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphSelectionEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphSelectionEvent.java index 842d3164c5..eac0ded656 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphSelectionEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphSelectionEvent.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventObject; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * Notifier for the time graph that an object in the views has been selected. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeGraphSelectionEvent extends EventObject { - - /** - * Default serial version UID for this class. - * @since 1.0 - */ - private static final long serialVersionUID = 1L; - - /** - * The selected entry. - */ - private final ITimeGraphEntry fSelection; - - /** - * Standard constructor - * - * @param source - * The source of this event - * @param selection - * The entry that was selected - */ - public TimeGraphSelectionEvent(Object source, ITimeGraphEntry selection) { - super(source); - fSelection = selection; - } - - /** - * @return the selected entry or null if the selection is empty. - */ - public ITimeGraphEntry getSelection() { - return fSelection; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventObject; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * Notifier for the time graph that an object in the views has been selected. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeGraphSelectionEvent extends EventObject { + + /** + * Default serial version UID for this class. + * @since 1.0 + */ + private static final long serialVersionUID = 1L; + + /** + * The selected entry. + */ + private final ITimeGraphEntry fSelection; + + /** + * Standard constructor + * + * @param source + * The source of this event + * @param selection + * The entry that was selected + */ + public TimeGraphSelectionEvent(Object source, ITimeGraphEntry selection) { + super(source); + fSelection = selection; + } + + /** + * @return the selected entry or null if the selection is empty. + */ + public ITimeGraphEntry getSelection() { + return fSelection; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTimeEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTimeEvent.java index 963bec2d38..b6c476ce30 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTimeEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTimeEvent.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventObject; - -/** - * Event for the time graph view - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeGraphTimeEvent extends EventObject { - - /** - * Default serial version UID for this class. - * @since 1.0 - */ - private static final long serialVersionUID = 1L; - - /** - * The selected time. - */ - private final long fTime; - - /** - * Standard constructor - * - * @param source - * The source of this event - * @param time - * The time that was requested - */ - public TimeGraphTimeEvent(Object source, long time) { - super(source); - fTime = time; - } - - /** - * @return the selected time - */ - public long getTime() { - return fTime; - } - -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventObject; + +/** + * Event for the time graph view + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeGraphTimeEvent extends EventObject { + + /** + * Default serial version UID for this class. + * @since 1.0 + */ + private static final long serialVersionUID = 1L; + + /** + * The selected time. + */ + private final long fTime; + + /** + * Standard constructor + * + * @param source + * The source of this event + * @param time + * The time that was requested + */ + public TimeGraphTimeEvent(Object source, long time) { + super(source); + fTime = time; + } + + /** + * @return the selected time + */ + public long getTime() { + return fTime; + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTreeExpansionEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTreeExpansionEvent.java index 57683c6eb6..9cf37a8373 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTreeExpansionEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphTreeExpansionEvent.java @@ -1,57 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.EventObject; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * Notifier for the time graph view that a tree has been expanded. - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeGraphTreeExpansionEvent extends EventObject { - - /** - * Default serial version UID for this class. - * @since 1.0 - */ - private static final long serialVersionUID = 1L; - - /** - * The entry that was expanded or collapsed. - */ - private final ITimeGraphEntry fEntry; - - /** - * Creates a new event for the given source and entry. - * - * @param source the tree viewer - * @param entry the entry - */ - public TimeGraphTreeExpansionEvent(Object source, ITimeGraphEntry entry) { - super(source); - fEntry = entry; - } - - /** - * Returns the entry that got expanded or collapsed. - * - * @return the entry - */ - public ITimeGraphEntry getEntry() { - return fEntry; - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.EventObject; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * Notifier for the time graph view that a tree has been expanded. + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeGraphTreeExpansionEvent extends EventObject { + + /** + * Default serial version UID for this class. + * @since 1.0 + */ + private static final long serialVersionUID = 1L; + + /** + * The entry that was expanded or collapsed. + */ + private final ITimeGraphEntry fEntry; + + /** + * Creates a new event for the given source and entry. + * + * @param source the tree viewer + * @param entry the entry + */ + public TimeGraphTreeExpansionEvent(Object source, ITimeGraphEntry entry) { + super(source); + fEntry = entry; + } + + /** + * Returns the entry that got expanded or collapsed. + * + * @return the entry + */ + public ITimeGraphEntry getEntry() { + return fEntry; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphViewer.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphViewer.java index ca3c629a53..c1cf32663f 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphViewer.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphViewer.java @@ -1,1340 +1,1340 @@ -/***************************************************************************** - * Copyright (c) 2007, 2008 Intel Corporation, 2009, 2010, 2011, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alexander N. Alexeev, Intel - Add monitors statistics support - * Alvaro Sanchez-Leon - Adapted for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; - -import java.util.ArrayList; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.linuxtools.internal.tmf.ui.Activator; -import org.eclipse.linuxtools.internal.tmf.ui.ITmfImageConstants; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.dialogs.TimeGraphLegend; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.ITimeDataProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphColorScheme; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphControl; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphScale; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphTooltipHandler; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseWheelListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.ScrollBar; -import org.eclipse.swt.widgets.Slider; - -/** - * Generic time graph viewer implementation - * - * @version 1.0 - * @author Patrick Tasse, and others - */ -public class TimeGraphViewer implements ITimeDataProvider, SelectionListener { - - /** vars */ - private long _minTimeInterval; - private long _selectedTime; - private ITimeGraphEntry _selectedEntry; - private long _beginTime; - private long _endTime; - private long _time0; - private long _time1; - private long _time0_; - private long _time1_; - private long _time0_extSynch = 0; - private long _time1_extSynch = 0; - private boolean _timeRangeFixed; - private int _nameWidthPref = 200; - private int _minNameWidth = 6; - private int _nameWidth; - private Composite _dataViewer; - - private TimeGraphControl _stateCtrl; - private TimeGraphScale _timeScaleCtrl; - private Slider _verticalScrollBar; - private TimeGraphTooltipHandler _threadTip; - private TimeGraphColorScheme _colors; - private ITimeGraphPresentationProvider fTimeGraphProvider; - - ArrayList fSelectionListeners = new ArrayList(); - ArrayList fTimeListeners = new ArrayList(); - ArrayList fRangeListeners = new ArrayList(); - - // Calender Time format, using Epoch reference or Relative time - // format(default - private boolean calendarTimeFormat = false; - private int borderWidth = 0; - private int timeScaleHeight = 22; - - private Action resetScale; - private Action showLegendAction; - private Action nextEventAction; - private Action prevEventAction; - private Action nextItemAction; - private Action previousItemAction; - private Action zoomInAction; - private Action zoomOutAction; - - /** - * Standard constructor - * - * @param parent - * The parent UI composite object - * @param style - * The style to use - */ - public TimeGraphViewer(Composite parent, int style) { - createDataViewer(parent, style); - } - - /** - * Sets the timegraph provider used by this timegraph viewer. - * - * @param timeGraphProvider the timegraph provider - */ - public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) { - fTimeGraphProvider = timeGraphProvider; - _stateCtrl.setTimeGraphProvider(timeGraphProvider); - _threadTip = new TimeGraphTooltipHandler(_dataViewer.getShell(), fTimeGraphProvider, this); - _threadTip.activateHoverHelp(_stateCtrl); - } - - /** - * Sets or clears the input for this time graph viewer. - * The input array should only contain top-level elements. - * - * @param input the input of this time graph viewer, or null if none - */ - public void setInput(ITimeGraphEntry[] input) { - if (null != _stateCtrl) { - if (null == input) { - input = new ITimeGraphEntry[0]; - } - setTimeRange(input); - _verticalScrollBar.setEnabled(true); - setTopIndex(0); - _selectedTime = 0; - _selectedEntry = null; - refreshAllData(input); - } - } - - /** - * Refresh the view - */ - public void refresh() { - setInput(_stateCtrl.getTraces()); - } - - /** - * Callback for when the control is moved - * - * @param e - * The caller event - */ - public void controlMoved(ControlEvent e) { - } - - /** - * Callback for when the control is resized - * - * @param e - * The caller event - */ - public void controlResized(ControlEvent e) { - resizeControls(); - } - - /** - * Handler for when the model is updated. Called from the display order in - * the API - * - * @param traces - * The traces in the model - * @param start - * The start time - * @param end - * The end time - * @param updateTimeBounds - * Should we updated the time bounds too - */ - public void modelUpdate(ITimeGraphEntry[] traces, long start, - long end, boolean updateTimeBounds) { - if (null != _stateCtrl) { - //loadOptions(); - updateInternalData(traces, start, end); - if (updateTimeBounds) { - _timeRangeFixed = true; - // set window to match limits - setStartFinishTime(_time0_, _time1_); - } else { - _stateCtrl.redraw(); - _timeScaleCtrl.redraw(); - } - } - } - - protected String getViewTypeStr() { - return "viewoption.threads"; //$NON-NLS-1$ - } - - int getMarginWidth(int idx) { - return 0; - } - - int getMarginHeight(int idx) { - return 0; - } - - void loadOptions() { - _minTimeInterval = 1; - _selectedTime = -1; - _nameWidth = Utils.loadIntOption(getPreferenceString("namewidth"), //$NON-NLS-1$ - _nameWidthPref, _minNameWidth, 1000); - } - - void saveOptions() { - Utils.saveIntOption(getPreferenceString("namewidth"), _nameWidth); //$NON-NLS-1$ - } - - protected Control createDataViewer(Composite parent, int style) { - loadOptions(); - _colors = new TimeGraphColorScheme(); - _dataViewer = new Composite(parent, style) { - @Override - public void redraw() { - _timeScaleCtrl.redraw(); - _stateCtrl.redraw(); - super.redraw(); - } - }; - GridLayout gl = new GridLayout(2, false); - gl.marginHeight = borderWidth; - gl.marginWidth = 0; - gl.verticalSpacing = 0; - gl.horizontalSpacing = 0; - _dataViewer.setLayout(gl); - - _timeScaleCtrl = new TimeGraphScale(_dataViewer, _colors); - _timeScaleCtrl.setTimeProvider(this); - _timeScaleCtrl.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); - _timeScaleCtrl.setHeight(timeScaleHeight); - - _verticalScrollBar = new Slider(_dataViewer, SWT.VERTICAL | SWT.NO_FOCUS); - _verticalScrollBar.setLayoutData(new GridData(SWT.DEFAULT, SWT.FILL, false, true, 1, 2)); - _verticalScrollBar.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - setTopIndex(_verticalScrollBar.getSelection()); - } - }); - _verticalScrollBar.setEnabled(false); - - _stateCtrl = createTimeGraphControl(); - - _stateCtrl.setTimeProvider(this); - _stateCtrl.addSelectionListener(this); - _stateCtrl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2)); - _stateCtrl.addMouseWheelListener(new MouseWheelListener() { - @Override - public void mouseScrolled(MouseEvent e) { - adjustVerticalScrollBar(); - } - }); - _stateCtrl.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - adjustVerticalScrollBar(); - } - }); - - Composite filler = new Composite(_dataViewer, SWT.NONE); - GridData gd = new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false); - gd.heightHint = _stateCtrl.getHorizontalBar().getSize().y; - filler.setLayoutData(gd); - filler.setLayout(new FillLayout()); - - _stateCtrl.addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent event) { - resizeControls(); - } - }); - resizeControls(); - _dataViewer.update(); - adjustVerticalScrollBar(); - return _dataViewer; - } - - /** - * Dispose the view. - */ - public void dispose() { - saveOptions(); - _stateCtrl.dispose(); - _dataViewer.dispose(); - _colors.dispose(); - } - - protected TimeGraphControl createTimeGraphControl() { - return new TimeGraphControl(_dataViewer, _colors); - } - - /** - * Resize the controls - */ - public void resizeControls() { - Rectangle r = _dataViewer.getClientArea(); - if (r.isEmpty()) { - return; - } - - int width = r.width; - if (_nameWidth > width - _minNameWidth) { - _nameWidth = width - _minNameWidth; - } - if (_nameWidth < _minNameWidth) { - _nameWidth = _minNameWidth; - } - adjustVerticalScrollBar(); - } - - /** - * Try to set most convenient time range for display. - * - * @param traces - * The traces in the model - */ - public void setTimeRange(ITimeGraphEntry traces[]) { - _endTime = 0; - _beginTime = -1; - for (int i = 0; i < traces.length; i++) { - ITimeGraphEntry entry = traces[i]; - if (entry.getEndTime() >= entry.getStartTime() && entry.getEndTime() > 0) { - if (_beginTime < 0 || entry.getStartTime() < _beginTime) { - _beginTime = entry.getStartTime(); - } - if (entry.getEndTime() > _endTime) { - _endTime = entry.getEndTime(); - } - } - } - - if (_beginTime < 0) { - _beginTime = 0; - } - } - - /** - * Recalculate the time bounds - */ - public void setTimeBounds() { - //_time0_ = _beginTime - (long) ((_endTime - _beginTime) * 0.02); - _time0_ = _beginTime; - if (_time0_ < 0) { - _time0_ = 0; - } - // _time1_ = _time0_ + (_endTime - _time0_) * 1.05; - _time1_ = _endTime; - // _time0_ = Math.floor(_time0_); - // _time1_ = Math.ceil(_time1_); - if (!_timeRangeFixed) { - _time0 = _time0_; - _time1 = _time1_; - } - if (_time1 - _time0 < _minTimeInterval) { - _time1 = Math.min(_time1_, _time0 + _minTimeInterval); - } - } - - /** - * @param traces - * @param start - * @param end - */ - void updateInternalData(ITimeGraphEntry[] traces, long start, long end) { - if (null == traces) { - traces = new ITimeGraphEntry[0]; - } - if ((start == 0 && end == 0) || start < 0 || end < 0) { - // Start and end time are unspecified and need to be determined from - // individual processes - setTimeRange(traces); - } else { - _beginTime = start; - _endTime = end; - } - - refreshAllData(traces); - } - - /** - * @param traces - */ - private void refreshAllData(ITimeGraphEntry[] traces) { - setTimeBounds(); - if (_selectedTime < _beginTime) { - _selectedTime = _beginTime; - } else if (_selectedTime > _endTime) { - _selectedTime = _endTime; - } - _stateCtrl.refreshData(traces); - _timeScaleCtrl.redraw(); - adjustVerticalScrollBar(); - } - - /** - * Callback for when this view is focused - */ - public void setFocus() { - if (null != _stateCtrl) { - _stateCtrl.setFocus(); - } - } - - /** - * Get the current focus status of this view. - * - * @return If the view is currently focused, or not - */ - public boolean isInFocus() { - return _stateCtrl.isInFocus(); - } - - /** - * Get the view's current selection - * - * @return The entry that is selected - */ - public ITimeGraphEntry getSelection() { - return _stateCtrl.getSelectedTrace(); - } - - /** - * Get the index of the current selection - * - * @return The index - */ - public int getSelectionIndex() { - return _stateCtrl.getSelectedIndex(); - } - - @Override - public long getTime0() { - return _time0; - } - - @Override - public long getTime1() { - return _time1; - } - - @Override - public long getMinTimeInterval() { - return _minTimeInterval; - } - - @Override - public int getNameSpace() { - return _nameWidth; - } - - @Override - public void setNameSpace(int width) { - _nameWidth = width; - width = _stateCtrl.getClientArea().width; - if (_nameWidth > width - 6) { - _nameWidth = width - 6; - } - if (_nameWidth < 6) { - _nameWidth = 6; - } - _stateCtrl.adjustScrolls(); - _stateCtrl.redraw(); - _timeScaleCtrl.redraw(); - } - - @Override - public int getTimeSpace() { - int w = _stateCtrl.getClientArea().width; - return w - _nameWidth; - } - - @Override - public long getSelectedTime() { - return _selectedTime; - } - - @Override - public long getBeginTime() { - return _beginTime; - } - - @Override - public long getEndTime() { - return _endTime; - } - - @Override - public long getMaxTime() { - return _time1_; - } - - @Override - public long getMinTime() { - return _time0_; - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider - * #setStartFinishTimeNotify(long, long) - */ - @Override - public void setStartFinishTimeNotify(long time0, long time1) { - setStartFinishTime(time0, time1); - notifyRangeListeners(time0, time1); - } - - - /* (non-Javadoc) - * @see org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider#notifyStartFinishTime() - */ - @Override - public void notifyStartFinishTime() { - notifyRangeListeners(_time0, _time1); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider - * #setStartFinishTime(long, long) - */ - @Override - public void setStartFinishTime(long time0, long time1) { - _time0 = time0; - if (_time0 < _time0_) { - _time0 = _time0_; - } - if (_time0 > _time1_) { - _time0 = _time1_; - } - _time1 = time1; - if (_time1 < _time0_) { - _time1 = _time0_; - } - if (_time1 > _time1_) { - _time1 = _time1_; - } - if (_time1 - _time0 < _minTimeInterval) { - _time1 = Math.min(_time1_, _time0 + _minTimeInterval); - } - _timeRangeFixed = true; - _stateCtrl.adjustScrolls(); - _stateCtrl.redraw(); - _timeScaleCtrl.redraw(); - } - - /** - * Set the time bounds to the provided values - * - * @param beginTime - * The start time of the window - * @param endTime - * The end time - */ - public void setTimeBounds(long beginTime, long endTime) { - _beginTime = beginTime; - _endTime = endTime; - _time0_ = beginTime; - _time1_ = endTime; - _stateCtrl.adjustScrolls(); - } - - @Override - public void resetStartFinishTime() { - setStartFinishTimeNotify(_time0_, _time1_); - _timeRangeFixed = false; - } - - @Override - public void setSelectedTimeNotify(long time, boolean ensureVisible) { - setSelectedTimeInt(time, ensureVisible, true); - } - - @Override - public void setSelectedTime(long time, boolean ensureVisible) { - setSelectedTimeInt(time, ensureVisible, false); - } - - private void setSelectedTimeInt(long time, boolean ensureVisible, boolean doNotify) { - long time0 = _time0; - long time1 = _time1; - if (ensureVisible) { - long timeSpace = (long) ((_time1 - _time0) * .02); - long timeMid = (long) ((_time1 - _time0) * .5); - if (time < _time0 + timeSpace) { - long dt = _time0 - time + timeMid; - _time0 -= dt; - _time1 -= dt; - } else if (time > _time1 - timeSpace) { - long dt = time - _time1 + timeMid; - _time0 += dt; - _time1 += dt; - } - if (_time0 < _time0_) { - _time1 = Math.min(_time1_, _time1 + (_time0_ - _time0)); - _time0 = _time0_; - } else if (_time1 > _time1_) { - _time0 = Math.max(_time0_, _time0 - (_time1 - _time1_)); - _time1 = _time1_; - } - } - if (_time1 - _time0 < _minTimeInterval) { - _time1 = Math.min(_time1_, _time0 + _minTimeInterval); - } - _stateCtrl.adjustScrolls(); - _stateCtrl.redraw(); - _timeScaleCtrl.redraw(); - - - boolean notifySelectedTime = (time != _selectedTime); - _selectedTime = time; - - if (doNotify && ((time0 != _time0) || (time1 != _time1))) { - notifyRangeListeners(_time0, _time1); - } - - if (doNotify && notifySelectedTime) { - notifyTimeListeners(_selectedTime); - } - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - if (_selectedEntry != getSelection()) { - _selectedEntry = getSelection(); - notifySelectionListeners(_selectedEntry); - } - } - - @Override - public void widgetSelected(SelectionEvent e) { - if (_selectedEntry != getSelection()) { - _selectedEntry = getSelection(); - notifySelectionListeners(_selectedEntry); - } - } - - /** - * Callback for when the next event is selected - */ - public void selectNextEvent() { - _stateCtrl.selectNextEvent(); - adjustVerticalScrollBar(); - } - - /** - * Callback for when the previous event is selected - */ - public void selectPrevEvent() { - _stateCtrl.selectPrevEvent(); - adjustVerticalScrollBar(); - } - - /** - * Callback for when the next item is selected - */ - public void selectNextItem() { - _stateCtrl.selectNextTrace(); - adjustVerticalScrollBar(); - } - - /** - * Callback for when the previous item is selected - */ - public void selectPrevItem() { - _stateCtrl.selectPrevTrace(); - adjustVerticalScrollBar(); - } - - /** - * Callback for the show legend action - */ - public void showLegend() { - if (_dataViewer == null || _dataViewer.isDisposed()) { - return; - } - - TimeGraphLegend.open(_dataViewer.getShell(), fTimeGraphProvider); - } - - /** - * Callback for the Zoom In action - */ - public void zoomIn() { - _stateCtrl.zoomIn(); - } - - /** - * Callback for the Zoom Out action - */ - public void zoomOut() { - _stateCtrl.zoomOut(); - } - - private String getPreferenceString(String string) { - return getViewTypeStr() + "." + string; //$NON-NLS-1$ - } - - /** - * Add a selection listener - * - * @param listener - * The listener to add - */ - public void addSelectionListener(ITimeGraphSelectionListener listener) { - fSelectionListeners.add(listener); - } - - /** - * Remove a selection listener - * - * @param listener - * The listener to remove - */ - public void removeSelectionListener(ITimeGraphSelectionListener listener) { - fSelectionListeners.remove(listener); - } - - private void notifySelectionListeners(ITimeGraphEntry selection) { - TimeGraphSelectionEvent event = new TimeGraphSelectionEvent(this, selection); - - for (ITimeGraphSelectionListener listener : fSelectionListeners) { - listener.selectionChanged(event); - } - } - - /** - * Add a time listener - * - * @param listener - * The listener to add - */ - public void addTimeListener(ITimeGraphTimeListener listener) { - fTimeListeners.add(listener); - } - - /** - * Remove a time listener - * - * @param listener - * The listener to remove - */ - public void removeTimeListener(ITimeGraphTimeListener listener) { - fTimeListeners.remove(listener); - } - - private void notifyTimeListeners(long time) { - TimeGraphTimeEvent event = new TimeGraphTimeEvent(this, time); - - for (ITimeGraphTimeListener listener : fTimeListeners) { - listener.timeSelected(event); - } - } - - /** - * Add a range listener - * - * @param listener - * The listener to add - */ - public void addRangeListener(ITimeGraphRangeListener listener) { - fRangeListeners.add(listener); - } - - /** - * Remove a range listener - * - * @param listener - * The listener to remove - */ - public void removeRangeListener(ITimeGraphRangeListener listener) { - fRangeListeners.remove(listener); - } - - private void notifyRangeListeners(long startTime, long endTime) { - // Check if the time has actually changed from last notification - if (startTime != _time0_extSynch || endTime != _time1_extSynch) { - // Notify Time Scale Selection Listeners - TimeGraphRangeUpdateEvent event = new TimeGraphRangeUpdateEvent(this, startTime, endTime); - - for (ITimeGraphRangeListener listener : fRangeListeners) { - listener.timeRangeUpdated(event); - } - - // update external synch timers - updateExtSynchTimers(); - } - } - - /** - * Callback to set a selected event in the view - * - * @param event - * The event that was selected - * @param source - * The source of this selection event - */ - public void setSelectedEvent(ITimeEvent event, Object source) { - if (event == null || source == this) { - return; - } - _selectedEntry = event.getEntry(); - _stateCtrl.selectItem(_selectedEntry, false); - - setSelectedTimeInt(event.getTime(), true, true); - adjustVerticalScrollBar(); - } - - /** - * Set the seeked time of a trace - * - * @param trace - * The trace that was seeked - * @param time - * The target time - * @param source - * The source of this seek event - */ - public void setSelectedTraceTime(ITimeGraphEntry trace, long time, Object source) { - if (trace == null || source == this) { - return; - } - _selectedEntry = trace; - _stateCtrl.selectItem(trace, false); - - setSelectedTimeInt(time, true, true); - } - - /** - * Callback for a trace selection - * - * @param trace - * The trace that was selected - */ - public void setSelection(ITimeGraphEntry trace) { - _selectedEntry = trace; - _stateCtrl.selectItem(trace, false); - adjustVerticalScrollBar(); - } - - /** - * Callback for a time window selection - * - * @param time0 - * Start time of the range - * @param time1 - * End time of the range - * @param source - * Source of the event - */ - public void setSelectVisTimeWindow(long time0, long time1, Object source) { - if (source == this) { - return; - } - - setStartFinishTime(time0, time1); - - // update notification time values since we are now in synch with the - // external application - updateExtSynchTimers(); - } - - /** - * update the cache timers used to identify the need to send a time window - * update to external registered listeners - */ - private void updateExtSynchTimers() { - // last time notification cache - _time0_extSynch = _time0; - _time1_extSynch = _time1; - } - - /** - * Set the calendar format - * - * @param toAbsoluteCaltime - * True for absolute time, false for relative - */ - public void setTimeCalendarFormat(boolean toAbsoluteCaltime) { - calendarTimeFormat = toAbsoluteCaltime; - } - - @Override - public boolean isCalendarFormat() { - return calendarTimeFormat; - } - - /** - * Retrieve the border width - * - * @return The width - */ - public int getBorderWidth() { - return borderWidth; - } - - /** - * Set the border width - * - * @param borderWidth - * The width - */ - public void setBorderWidth(int borderWidth) { - if (borderWidth > -1) { - this.borderWidth = borderWidth; - GridLayout gl = (GridLayout)_dataViewer.getLayout(); - gl.marginHeight = borderWidth; - } - } - - /** - * Retrieve the height of the header - * - * @return The height - */ - public int getHeaderHeight() { - return timeScaleHeight; - } - - /** - * Set the height of the header - * - * @param headerHeight - * The height to set - */ - public void setHeaderHeight(int headerHeight) { - if (headerHeight > -1) { - this.timeScaleHeight = headerHeight; - _timeScaleCtrl.setHeight(headerHeight); - } - } - - /** - * Retrieve the height of an item row - * - * @return The height - */ - public int getItemHeight() { - if (_stateCtrl != null) { - return _stateCtrl.getItemHeight(); - } - return 0; - } - - /** - * Set the height of an item row - * - * @param rowHeight - * The height to set - */ - public void setItemHeight(int rowHeight) { - if (_stateCtrl != null) { - _stateCtrl.setItemHeight(rowHeight); - } - } - - /** - * Set the minimum item width - * - * @param width - * The min width - */ - public void setMinimumItemWidth(int width) { - if (_stateCtrl != null) { - _stateCtrl.setMinimumItemWidth(width); - } - } - - /** - * Set the width for the name column - * - * @param width The width - */ - public void setNameWidthPref(int width) { - _nameWidthPref = width; - if (width == 0) { - _minNameWidth = 0; - _nameWidth = 0; - } - } - - /** - * Retrieve the configure width for the name column - * - * @param width - * Unused? - * @return The width - */ - public int getNameWidthPref(int width) { - return _nameWidthPref; - } - - /** - * Returns the primary control associated with this viewer. - * - * @return the SWT control which displays this viewer's content - */ - public Control getControl() { - return _dataViewer; - } - - /** - * Returns the time graph control associated with this viewer. - * - * @return the time graph control - */ - TimeGraphControl getTimeGraphControl() { - return _stateCtrl; - } - - /** - * Returns the time graph scale associated with this viewer. - * - * @return the time graph scale - */ - TimeGraphScale getTimeGraphScale() { - return _timeScaleCtrl; - } - - /** - * Get the selection provider - * - * @return the selection provider - */ - public ISelectionProvider getSelectionProvider() { - return _stateCtrl; - } - - /** - * Wait for the cursor - * - * @param waitInd - * Wait indefinitely? - */ - public void waitCursor(boolean waitInd) { - _stateCtrl.waitCursor(waitInd); - } - - /** - * Get the horizontal scroll bar object - * - * @return The scroll bar - */ - public ScrollBar getHorizontalBar() { - return _stateCtrl.getHorizontalBar(); - } - - /** - * Get the vertical scroll bar object - * - * @return The scroll bar - */ - public Slider getVerticalBar() { - return _verticalScrollBar; - } - - /** - * Set the given index as the top one - * - * @param index - * The index that will go to the top - */ - public void setTopIndex(int index) { - _stateCtrl.setTopIndex(index); - adjustVerticalScrollBar(); - } - - /** - * Retrieve the current top index - * - * @return The top index - */ - public int getTopIndex() { - return _stateCtrl.getTopIndex(); - } - - /** - * Set the expanded state of an entry - * - * @param entry - * The entry to expand/collapse - * @param expanded - * True for expanded, false for collapsed - */ - public void setExpandedState(ITimeGraphEntry entry, boolean expanded) { - _stateCtrl.setExpandedState(entry, expanded); - adjustVerticalScrollBar(); - } - - /** - * Get the number of sub-elements when expanded - * - * @return The element count - */ - public int getExpandedElementCount() { - return _stateCtrl.getExpandedElementCount(); - } - - /** - * Get the sub-elements - * - * @return The array of entries that are below this one - */ - public ITimeGraphEntry[] getExpandedElements() { - return _stateCtrl.getExpandedElements(); - } - - /** - * Add a tree listener - * - * @param listener - * The listener to add - */ - public void addTreeListener(ITimeGraphTreeListener listener) { - _stateCtrl.addTreeListener(listener); - } - - /** - * Remove a tree listener - * - * @param listener - * The listener to remove - */ - public void removeTreeListener(ITimeGraphTreeListener listener) { - _stateCtrl.removeTreeListener(listener); - } - - /** - * Get the reset scale action. - * - * @return The Action object - */ - public Action getResetScaleAction() { - if (resetScale == null) { - // resetScale - resetScale = new Action() { - @Override - public void run() { - resetStartFinishTime(); - } - }; - resetScale.setText(Messages.TmfTimeGraphViewer_ResetScaleActionNameText); - resetScale.setToolTipText(Messages.TmfTimeGraphViewer_ResetScaleActionToolTipText); - resetScale.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_HOME_MENU)); - } - return resetScale; - } - - /** - * Get the show legend action. - * - * @return The Action object - */ - public Action getShowLegendAction() { - if (showLegendAction == null) { - // showLegend - showLegendAction = new Action() { - @Override - public void run() { - showLegend(); - } - }; - showLegendAction.setText(Messages.TmfTimeGraphViewer_LegendActionNameText); - showLegendAction.setToolTipText(Messages.TmfTimeGraphViewer_LegendActionToolTipText); - showLegendAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_SHOW_LEGEND)); - } - - return showLegendAction; - } - - /** - * Get the the next event action. - * - * @return The action object - */ - public Action getNextEventAction() { - if (nextEventAction == null) { - nextEventAction = new Action() { - @Override - public void run() { - selectNextEvent(); - } - }; - - nextEventAction.setText(Messages.TmfTimeGraphViewer_NextEventActionNameText); - nextEventAction.setToolTipText(Messages.TmfTimeGraphViewer_NextEventActionToolTipText); - nextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_EVENT)); - } - - return nextEventAction; - } - - /** - * Get the previous event action. - * - * @return The Action object - */ - public Action getPreviousEventAction() { - if (prevEventAction == null) { - prevEventAction = new Action() { - @Override - public void run() { - selectPrevEvent(); - } - }; - - prevEventAction.setText(Messages.TmfTimeGraphViewer_PreviousEventActionNameText); - prevEventAction.setToolTipText(Messages.TmfTimeGraphViewer_PreviousEventActionToolTipText); - prevEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_PREV_EVENT)); - } - - return prevEventAction; - } - - /** - * Get the next item action. - * - * @return The Action object - */ - public Action getNextItemAction() { - if (nextItemAction == null) { - - nextItemAction = new Action() { - @Override - public void run() { - selectNextItem(); - } - }; - nextItemAction.setText(Messages.TmfTimeGraphViewer_NextItemActionNameText); - nextItemAction.setToolTipText(Messages.TmfTimeGraphViewer_NextItemActionToolTipText); - nextItemAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_ITEM)); - } - return nextItemAction; - } - - /** - * Get the previous item action. - * - * @return The Action object - */ - public Action getPreviousItemAction() { - if (previousItemAction == null) { - - previousItemAction = new Action() { - @Override - public void run() { - selectPrevItem(); - } - }; - previousItemAction.setText(Messages.TmfTimeGraphViewer_PreviousItemActionNameText); - previousItemAction.setToolTipText(Messages.TmfTimeGraphViewer_PreviousItemActionToolTipText); - previousItemAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_PREV_ITEM)); - } - return previousItemAction; - } - - /** - * Get the zoom in action - * - * @return The Action object - */ - public Action getZoomInAction() { - if (zoomInAction == null) { - zoomInAction = new Action() { - @Override - public void run() { - zoomIn(); - } - }; - zoomInAction.setText(Messages.TmfTimeGraphViewer_ZoomInActionNameText); - zoomInAction.setToolTipText(Messages.TmfTimeGraphViewer_ZoomInActionToolTipText); - zoomInAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_ZOOM_IN_MENU)); - } - return zoomInAction; - } - - /** - * Get the zoom out action - * - * @return The Action object - */ - public Action getZoomOutAction() { - if (zoomOutAction == null) { - zoomOutAction = new Action() { - @Override - public void run() { - zoomOut(); - } - }; - zoomOutAction.setText(Messages.TmfTimeGraphViewer_ZoomOutActionNameText); - zoomOutAction.setToolTipText(Messages.TmfTimeGraphViewer_ZoomOutActionToolTipText); - zoomOutAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_ZOOM_OUT_MENU)); - } - return zoomOutAction; - } - - - private void adjustVerticalScrollBar() { - int topIndex = _stateCtrl.getTopIndex(); - int countPerPage = _stateCtrl.countPerPage(); - int expandedElementCount = _stateCtrl.getExpandedElementCount(); - if (topIndex + countPerPage > expandedElementCount) { - _stateCtrl.setTopIndex(Math.max(0, expandedElementCount - countPerPage)); - } - - int selection = _stateCtrl.getTopIndex(); - int min = 0; - int max = Math.max(1, expandedElementCount - 1); - int thumb = Math.min(max, Math.max(1, countPerPage - 1)); - int increment = 1; - int pageIncrement = Math.max(1, countPerPage); - _verticalScrollBar.setValues(selection, min, max, thumb, increment, pageIncrement); - } - - - -} +/***************************************************************************** + * Copyright (c) 2007, 2008 Intel Corporation, 2009, 2010, 2011, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alexander N. Alexeev, Intel - Add monitors statistics support + * Alvaro Sanchez-Leon - Adapted for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; + +import java.util.ArrayList; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.linuxtools.internal.tmf.ui.Activator; +import org.eclipse.linuxtools.internal.tmf.ui.ITmfImageConstants; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.dialogs.TimeGraphLegend; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.ITimeDataProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphColorScheme; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphControl; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphScale; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.TimeGraphTooltipHandler; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets.Utils; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseWheelListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.ScrollBar; +import org.eclipse.swt.widgets.Slider; + +/** + * Generic time graph viewer implementation + * + * @version 1.0 + * @author Patrick Tasse, and others + */ +public class TimeGraphViewer implements ITimeDataProvider, SelectionListener { + + /** vars */ + private long _minTimeInterval; + private long _selectedTime; + private ITimeGraphEntry _selectedEntry; + private long _beginTime; + private long _endTime; + private long _time0; + private long _time1; + private long _time0_; + private long _time1_; + private long _time0_extSynch = 0; + private long _time1_extSynch = 0; + private boolean _timeRangeFixed; + private int _nameWidthPref = 200; + private int _minNameWidth = 6; + private int _nameWidth; + private Composite _dataViewer; + + private TimeGraphControl _stateCtrl; + private TimeGraphScale _timeScaleCtrl; + private Slider _verticalScrollBar; + private TimeGraphTooltipHandler _threadTip; + private TimeGraphColorScheme _colors; + private ITimeGraphPresentationProvider fTimeGraphProvider; + + ArrayList fSelectionListeners = new ArrayList(); + ArrayList fTimeListeners = new ArrayList(); + ArrayList fRangeListeners = new ArrayList(); + + // Calender Time format, using Epoch reference or Relative time + // format(default + private boolean calendarTimeFormat = false; + private int borderWidth = 0; + private int timeScaleHeight = 22; + + private Action resetScale; + private Action showLegendAction; + private Action nextEventAction; + private Action prevEventAction; + private Action nextItemAction; + private Action previousItemAction; + private Action zoomInAction; + private Action zoomOutAction; + + /** + * Standard constructor + * + * @param parent + * The parent UI composite object + * @param style + * The style to use + */ + public TimeGraphViewer(Composite parent, int style) { + createDataViewer(parent, style); + } + + /** + * Sets the timegraph provider used by this timegraph viewer. + * + * @param timeGraphProvider the timegraph provider + */ + public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) { + fTimeGraphProvider = timeGraphProvider; + _stateCtrl.setTimeGraphProvider(timeGraphProvider); + _threadTip = new TimeGraphTooltipHandler(_dataViewer.getShell(), fTimeGraphProvider, this); + _threadTip.activateHoverHelp(_stateCtrl); + } + + /** + * Sets or clears the input for this time graph viewer. + * The input array should only contain top-level elements. + * + * @param input the input of this time graph viewer, or null if none + */ + public void setInput(ITimeGraphEntry[] input) { + if (null != _stateCtrl) { + if (null == input) { + input = new ITimeGraphEntry[0]; + } + setTimeRange(input); + _verticalScrollBar.setEnabled(true); + setTopIndex(0); + _selectedTime = 0; + _selectedEntry = null; + refreshAllData(input); + } + } + + /** + * Refresh the view + */ + public void refresh() { + setInput(_stateCtrl.getTraces()); + } + + /** + * Callback for when the control is moved + * + * @param e + * The caller event + */ + public void controlMoved(ControlEvent e) { + } + + /** + * Callback for when the control is resized + * + * @param e + * The caller event + */ + public void controlResized(ControlEvent e) { + resizeControls(); + } + + /** + * Handler for when the model is updated. Called from the display order in + * the API + * + * @param traces + * The traces in the model + * @param start + * The start time + * @param end + * The end time + * @param updateTimeBounds + * Should we updated the time bounds too + */ + public void modelUpdate(ITimeGraphEntry[] traces, long start, + long end, boolean updateTimeBounds) { + if (null != _stateCtrl) { + //loadOptions(); + updateInternalData(traces, start, end); + if (updateTimeBounds) { + _timeRangeFixed = true; + // set window to match limits + setStartFinishTime(_time0_, _time1_); + } else { + _stateCtrl.redraw(); + _timeScaleCtrl.redraw(); + } + } + } + + protected String getViewTypeStr() { + return "viewoption.threads"; //$NON-NLS-1$ + } + + int getMarginWidth(int idx) { + return 0; + } + + int getMarginHeight(int idx) { + return 0; + } + + void loadOptions() { + _minTimeInterval = 1; + _selectedTime = -1; + _nameWidth = Utils.loadIntOption(getPreferenceString("namewidth"), //$NON-NLS-1$ + _nameWidthPref, _minNameWidth, 1000); + } + + void saveOptions() { + Utils.saveIntOption(getPreferenceString("namewidth"), _nameWidth); //$NON-NLS-1$ + } + + protected Control createDataViewer(Composite parent, int style) { + loadOptions(); + _colors = new TimeGraphColorScheme(); + _dataViewer = new Composite(parent, style) { + @Override + public void redraw() { + _timeScaleCtrl.redraw(); + _stateCtrl.redraw(); + super.redraw(); + } + }; + GridLayout gl = new GridLayout(2, false); + gl.marginHeight = borderWidth; + gl.marginWidth = 0; + gl.verticalSpacing = 0; + gl.horizontalSpacing = 0; + _dataViewer.setLayout(gl); + + _timeScaleCtrl = new TimeGraphScale(_dataViewer, _colors); + _timeScaleCtrl.setTimeProvider(this); + _timeScaleCtrl.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); + _timeScaleCtrl.setHeight(timeScaleHeight); + + _verticalScrollBar = new Slider(_dataViewer, SWT.VERTICAL | SWT.NO_FOCUS); + _verticalScrollBar.setLayoutData(new GridData(SWT.DEFAULT, SWT.FILL, false, true, 1, 2)); + _verticalScrollBar.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + setTopIndex(_verticalScrollBar.getSelection()); + } + }); + _verticalScrollBar.setEnabled(false); + + _stateCtrl = createTimeGraphControl(); + + _stateCtrl.setTimeProvider(this); + _stateCtrl.addSelectionListener(this); + _stateCtrl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2)); + _stateCtrl.addMouseWheelListener(new MouseWheelListener() { + @Override + public void mouseScrolled(MouseEvent e) { + adjustVerticalScrollBar(); + } + }); + _stateCtrl.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + adjustVerticalScrollBar(); + } + }); + + Composite filler = new Composite(_dataViewer, SWT.NONE); + GridData gd = new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false); + gd.heightHint = _stateCtrl.getHorizontalBar().getSize().y; + filler.setLayoutData(gd); + filler.setLayout(new FillLayout()); + + _stateCtrl.addControlListener(new ControlAdapter() { + @Override + public void controlResized(ControlEvent event) { + resizeControls(); + } + }); + resizeControls(); + _dataViewer.update(); + adjustVerticalScrollBar(); + return _dataViewer; + } + + /** + * Dispose the view. + */ + public void dispose() { + saveOptions(); + _stateCtrl.dispose(); + _dataViewer.dispose(); + _colors.dispose(); + } + + protected TimeGraphControl createTimeGraphControl() { + return new TimeGraphControl(_dataViewer, _colors); + } + + /** + * Resize the controls + */ + public void resizeControls() { + Rectangle r = _dataViewer.getClientArea(); + if (r.isEmpty()) { + return; + } + + int width = r.width; + if (_nameWidth > width - _minNameWidth) { + _nameWidth = width - _minNameWidth; + } + if (_nameWidth < _minNameWidth) { + _nameWidth = _minNameWidth; + } + adjustVerticalScrollBar(); + } + + /** + * Try to set most convenient time range for display. + * + * @param traces + * The traces in the model + */ + public void setTimeRange(ITimeGraphEntry traces[]) { + _endTime = 0; + _beginTime = -1; + for (int i = 0; i < traces.length; i++) { + ITimeGraphEntry entry = traces[i]; + if (entry.getEndTime() >= entry.getStartTime() && entry.getEndTime() > 0) { + if (_beginTime < 0 || entry.getStartTime() < _beginTime) { + _beginTime = entry.getStartTime(); + } + if (entry.getEndTime() > _endTime) { + _endTime = entry.getEndTime(); + } + } + } + + if (_beginTime < 0) { + _beginTime = 0; + } + } + + /** + * Recalculate the time bounds + */ + public void setTimeBounds() { + //_time0_ = _beginTime - (long) ((_endTime - _beginTime) * 0.02); + _time0_ = _beginTime; + if (_time0_ < 0) { + _time0_ = 0; + } + // _time1_ = _time0_ + (_endTime - _time0_) * 1.05; + _time1_ = _endTime; + // _time0_ = Math.floor(_time0_); + // _time1_ = Math.ceil(_time1_); + if (!_timeRangeFixed) { + _time0 = _time0_; + _time1 = _time1_; + } + if (_time1 - _time0 < _minTimeInterval) { + _time1 = Math.min(_time1_, _time0 + _minTimeInterval); + } + } + + /** + * @param traces + * @param start + * @param end + */ + void updateInternalData(ITimeGraphEntry[] traces, long start, long end) { + if (null == traces) { + traces = new ITimeGraphEntry[0]; + } + if ((start == 0 && end == 0) || start < 0 || end < 0) { + // Start and end time are unspecified and need to be determined from + // individual processes + setTimeRange(traces); + } else { + _beginTime = start; + _endTime = end; + } + + refreshAllData(traces); + } + + /** + * @param traces + */ + private void refreshAllData(ITimeGraphEntry[] traces) { + setTimeBounds(); + if (_selectedTime < _beginTime) { + _selectedTime = _beginTime; + } else if (_selectedTime > _endTime) { + _selectedTime = _endTime; + } + _stateCtrl.refreshData(traces); + _timeScaleCtrl.redraw(); + adjustVerticalScrollBar(); + } + + /** + * Callback for when this view is focused + */ + public void setFocus() { + if (null != _stateCtrl) { + _stateCtrl.setFocus(); + } + } + + /** + * Get the current focus status of this view. + * + * @return If the view is currently focused, or not + */ + public boolean isInFocus() { + return _stateCtrl.isInFocus(); + } + + /** + * Get the view's current selection + * + * @return The entry that is selected + */ + public ITimeGraphEntry getSelection() { + return _stateCtrl.getSelectedTrace(); + } + + /** + * Get the index of the current selection + * + * @return The index + */ + public int getSelectionIndex() { + return _stateCtrl.getSelectedIndex(); + } + + @Override + public long getTime0() { + return _time0; + } + + @Override + public long getTime1() { + return _time1; + } + + @Override + public long getMinTimeInterval() { + return _minTimeInterval; + } + + @Override + public int getNameSpace() { + return _nameWidth; + } + + @Override + public void setNameSpace(int width) { + _nameWidth = width; + width = _stateCtrl.getClientArea().width; + if (_nameWidth > width - 6) { + _nameWidth = width - 6; + } + if (_nameWidth < 6) { + _nameWidth = 6; + } + _stateCtrl.adjustScrolls(); + _stateCtrl.redraw(); + _timeScaleCtrl.redraw(); + } + + @Override + public int getTimeSpace() { + int w = _stateCtrl.getClientArea().width; + return w - _nameWidth; + } + + @Override + public long getSelectedTime() { + return _selectedTime; + } + + @Override + public long getBeginTime() { + return _beginTime; + } + + @Override + public long getEndTime() { + return _endTime; + } + + @Override + public long getMaxTime() { + return _time1_; + } + + @Override + public long getMinTime() { + return _time0_; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider + * #setStartFinishTimeNotify(long, long) + */ + @Override + public void setStartFinishTimeNotify(long time0, long time1) { + setStartFinishTime(time0, time1); + notifyRangeListeners(time0, time1); + } + + + /* (non-Javadoc) + * @see org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider#notifyStartFinishTime() + */ + @Override + public void notifyStartFinishTime() { + notifyRangeListeners(_time0, _time1); + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.linuxtools.tmf.ui.viewers.timeAnalysis.widgets.ITimeDataProvider + * #setStartFinishTime(long, long) + */ + @Override + public void setStartFinishTime(long time0, long time1) { + _time0 = time0; + if (_time0 < _time0_) { + _time0 = _time0_; + } + if (_time0 > _time1_) { + _time0 = _time1_; + } + _time1 = time1; + if (_time1 < _time0_) { + _time1 = _time0_; + } + if (_time1 > _time1_) { + _time1 = _time1_; + } + if (_time1 - _time0 < _minTimeInterval) { + _time1 = Math.min(_time1_, _time0 + _minTimeInterval); + } + _timeRangeFixed = true; + _stateCtrl.adjustScrolls(); + _stateCtrl.redraw(); + _timeScaleCtrl.redraw(); + } + + /** + * Set the time bounds to the provided values + * + * @param beginTime + * The start time of the window + * @param endTime + * The end time + */ + public void setTimeBounds(long beginTime, long endTime) { + _beginTime = beginTime; + _endTime = endTime; + _time0_ = beginTime; + _time1_ = endTime; + _stateCtrl.adjustScrolls(); + } + + @Override + public void resetStartFinishTime() { + setStartFinishTimeNotify(_time0_, _time1_); + _timeRangeFixed = false; + } + + @Override + public void setSelectedTimeNotify(long time, boolean ensureVisible) { + setSelectedTimeInt(time, ensureVisible, true); + } + + @Override + public void setSelectedTime(long time, boolean ensureVisible) { + setSelectedTimeInt(time, ensureVisible, false); + } + + private void setSelectedTimeInt(long time, boolean ensureVisible, boolean doNotify) { + long time0 = _time0; + long time1 = _time1; + if (ensureVisible) { + long timeSpace = (long) ((_time1 - _time0) * .02); + long timeMid = (long) ((_time1 - _time0) * .5); + if (time < _time0 + timeSpace) { + long dt = _time0 - time + timeMid; + _time0 -= dt; + _time1 -= dt; + } else if (time > _time1 - timeSpace) { + long dt = time - _time1 + timeMid; + _time0 += dt; + _time1 += dt; + } + if (_time0 < _time0_) { + _time1 = Math.min(_time1_, _time1 + (_time0_ - _time0)); + _time0 = _time0_; + } else if (_time1 > _time1_) { + _time0 = Math.max(_time0_, _time0 - (_time1 - _time1_)); + _time1 = _time1_; + } + } + if (_time1 - _time0 < _minTimeInterval) { + _time1 = Math.min(_time1_, _time0 + _minTimeInterval); + } + _stateCtrl.adjustScrolls(); + _stateCtrl.redraw(); + _timeScaleCtrl.redraw(); + + + boolean notifySelectedTime = (time != _selectedTime); + _selectedTime = time; + + if (doNotify && ((time0 != _time0) || (time1 != _time1))) { + notifyRangeListeners(_time0, _time1); + } + + if (doNotify && notifySelectedTime) { + notifyTimeListeners(_selectedTime); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + if (_selectedEntry != getSelection()) { + _selectedEntry = getSelection(); + notifySelectionListeners(_selectedEntry); + } + } + + @Override + public void widgetSelected(SelectionEvent e) { + if (_selectedEntry != getSelection()) { + _selectedEntry = getSelection(); + notifySelectionListeners(_selectedEntry); + } + } + + /** + * Callback for when the next event is selected + */ + public void selectNextEvent() { + _stateCtrl.selectNextEvent(); + adjustVerticalScrollBar(); + } + + /** + * Callback for when the previous event is selected + */ + public void selectPrevEvent() { + _stateCtrl.selectPrevEvent(); + adjustVerticalScrollBar(); + } + + /** + * Callback for when the next item is selected + */ + public void selectNextItem() { + _stateCtrl.selectNextTrace(); + adjustVerticalScrollBar(); + } + + /** + * Callback for when the previous item is selected + */ + public void selectPrevItem() { + _stateCtrl.selectPrevTrace(); + adjustVerticalScrollBar(); + } + + /** + * Callback for the show legend action + */ + public void showLegend() { + if (_dataViewer == null || _dataViewer.isDisposed()) { + return; + } + + TimeGraphLegend.open(_dataViewer.getShell(), fTimeGraphProvider); + } + + /** + * Callback for the Zoom In action + */ + public void zoomIn() { + _stateCtrl.zoomIn(); + } + + /** + * Callback for the Zoom Out action + */ + public void zoomOut() { + _stateCtrl.zoomOut(); + } + + private String getPreferenceString(String string) { + return getViewTypeStr() + "." + string; //$NON-NLS-1$ + } + + /** + * Add a selection listener + * + * @param listener + * The listener to add + */ + public void addSelectionListener(ITimeGraphSelectionListener listener) { + fSelectionListeners.add(listener); + } + + /** + * Remove a selection listener + * + * @param listener + * The listener to remove + */ + public void removeSelectionListener(ITimeGraphSelectionListener listener) { + fSelectionListeners.remove(listener); + } + + private void notifySelectionListeners(ITimeGraphEntry selection) { + TimeGraphSelectionEvent event = new TimeGraphSelectionEvent(this, selection); + + for (ITimeGraphSelectionListener listener : fSelectionListeners) { + listener.selectionChanged(event); + } + } + + /** + * Add a time listener + * + * @param listener + * The listener to add + */ + public void addTimeListener(ITimeGraphTimeListener listener) { + fTimeListeners.add(listener); + } + + /** + * Remove a time listener + * + * @param listener + * The listener to remove + */ + public void removeTimeListener(ITimeGraphTimeListener listener) { + fTimeListeners.remove(listener); + } + + private void notifyTimeListeners(long time) { + TimeGraphTimeEvent event = new TimeGraphTimeEvent(this, time); + + for (ITimeGraphTimeListener listener : fTimeListeners) { + listener.timeSelected(event); + } + } + + /** + * Add a range listener + * + * @param listener + * The listener to add + */ + public void addRangeListener(ITimeGraphRangeListener listener) { + fRangeListeners.add(listener); + } + + /** + * Remove a range listener + * + * @param listener + * The listener to remove + */ + public void removeRangeListener(ITimeGraphRangeListener listener) { + fRangeListeners.remove(listener); + } + + private void notifyRangeListeners(long startTime, long endTime) { + // Check if the time has actually changed from last notification + if (startTime != _time0_extSynch || endTime != _time1_extSynch) { + // Notify Time Scale Selection Listeners + TimeGraphRangeUpdateEvent event = new TimeGraphRangeUpdateEvent(this, startTime, endTime); + + for (ITimeGraphRangeListener listener : fRangeListeners) { + listener.timeRangeUpdated(event); + } + + // update external synch timers + updateExtSynchTimers(); + } + } + + /** + * Callback to set a selected event in the view + * + * @param event + * The event that was selected + * @param source + * The source of this selection event + */ + public void setSelectedEvent(ITimeEvent event, Object source) { + if (event == null || source == this) { + return; + } + _selectedEntry = event.getEntry(); + _stateCtrl.selectItem(_selectedEntry, false); + + setSelectedTimeInt(event.getTime(), true, true); + adjustVerticalScrollBar(); + } + + /** + * Set the seeked time of a trace + * + * @param trace + * The trace that was seeked + * @param time + * The target time + * @param source + * The source of this seek event + */ + public void setSelectedTraceTime(ITimeGraphEntry trace, long time, Object source) { + if (trace == null || source == this) { + return; + } + _selectedEntry = trace; + _stateCtrl.selectItem(trace, false); + + setSelectedTimeInt(time, true, true); + } + + /** + * Callback for a trace selection + * + * @param trace + * The trace that was selected + */ + public void setSelection(ITimeGraphEntry trace) { + _selectedEntry = trace; + _stateCtrl.selectItem(trace, false); + adjustVerticalScrollBar(); + } + + /** + * Callback for a time window selection + * + * @param time0 + * Start time of the range + * @param time1 + * End time of the range + * @param source + * Source of the event + */ + public void setSelectVisTimeWindow(long time0, long time1, Object source) { + if (source == this) { + return; + } + + setStartFinishTime(time0, time1); + + // update notification time values since we are now in synch with the + // external application + updateExtSynchTimers(); + } + + /** + * update the cache timers used to identify the need to send a time window + * update to external registered listeners + */ + private void updateExtSynchTimers() { + // last time notification cache + _time0_extSynch = _time0; + _time1_extSynch = _time1; + } + + /** + * Set the calendar format + * + * @param toAbsoluteCaltime + * True for absolute time, false for relative + */ + public void setTimeCalendarFormat(boolean toAbsoluteCaltime) { + calendarTimeFormat = toAbsoluteCaltime; + } + + @Override + public boolean isCalendarFormat() { + return calendarTimeFormat; + } + + /** + * Retrieve the border width + * + * @return The width + */ + public int getBorderWidth() { + return borderWidth; + } + + /** + * Set the border width + * + * @param borderWidth + * The width + */ + public void setBorderWidth(int borderWidth) { + if (borderWidth > -1) { + this.borderWidth = borderWidth; + GridLayout gl = (GridLayout)_dataViewer.getLayout(); + gl.marginHeight = borderWidth; + } + } + + /** + * Retrieve the height of the header + * + * @return The height + */ + public int getHeaderHeight() { + return timeScaleHeight; + } + + /** + * Set the height of the header + * + * @param headerHeight + * The height to set + */ + public void setHeaderHeight(int headerHeight) { + if (headerHeight > -1) { + this.timeScaleHeight = headerHeight; + _timeScaleCtrl.setHeight(headerHeight); + } + } + + /** + * Retrieve the height of an item row + * + * @return The height + */ + public int getItemHeight() { + if (_stateCtrl != null) { + return _stateCtrl.getItemHeight(); + } + return 0; + } + + /** + * Set the height of an item row + * + * @param rowHeight + * The height to set + */ + public void setItemHeight(int rowHeight) { + if (_stateCtrl != null) { + _stateCtrl.setItemHeight(rowHeight); + } + } + + /** + * Set the minimum item width + * + * @param width + * The min width + */ + public void setMinimumItemWidth(int width) { + if (_stateCtrl != null) { + _stateCtrl.setMinimumItemWidth(width); + } + } + + /** + * Set the width for the name column + * + * @param width The width + */ + public void setNameWidthPref(int width) { + _nameWidthPref = width; + if (width == 0) { + _minNameWidth = 0; + _nameWidth = 0; + } + } + + /** + * Retrieve the configure width for the name column + * + * @param width + * Unused? + * @return The width + */ + public int getNameWidthPref(int width) { + return _nameWidthPref; + } + + /** + * Returns the primary control associated with this viewer. + * + * @return the SWT control which displays this viewer's content + */ + public Control getControl() { + return _dataViewer; + } + + /** + * Returns the time graph control associated with this viewer. + * + * @return the time graph control + */ + TimeGraphControl getTimeGraphControl() { + return _stateCtrl; + } + + /** + * Returns the time graph scale associated with this viewer. + * + * @return the time graph scale + */ + TimeGraphScale getTimeGraphScale() { + return _timeScaleCtrl; + } + + /** + * Get the selection provider + * + * @return the selection provider + */ + public ISelectionProvider getSelectionProvider() { + return _stateCtrl; + } + + /** + * Wait for the cursor + * + * @param waitInd + * Wait indefinitely? + */ + public void waitCursor(boolean waitInd) { + _stateCtrl.waitCursor(waitInd); + } + + /** + * Get the horizontal scroll bar object + * + * @return The scroll bar + */ + public ScrollBar getHorizontalBar() { + return _stateCtrl.getHorizontalBar(); + } + + /** + * Get the vertical scroll bar object + * + * @return The scroll bar + */ + public Slider getVerticalBar() { + return _verticalScrollBar; + } + + /** + * Set the given index as the top one + * + * @param index + * The index that will go to the top + */ + public void setTopIndex(int index) { + _stateCtrl.setTopIndex(index); + adjustVerticalScrollBar(); + } + + /** + * Retrieve the current top index + * + * @return The top index + */ + public int getTopIndex() { + return _stateCtrl.getTopIndex(); + } + + /** + * Set the expanded state of an entry + * + * @param entry + * The entry to expand/collapse + * @param expanded + * True for expanded, false for collapsed + */ + public void setExpandedState(ITimeGraphEntry entry, boolean expanded) { + _stateCtrl.setExpandedState(entry, expanded); + adjustVerticalScrollBar(); + } + + /** + * Get the number of sub-elements when expanded + * + * @return The element count + */ + public int getExpandedElementCount() { + return _stateCtrl.getExpandedElementCount(); + } + + /** + * Get the sub-elements + * + * @return The array of entries that are below this one + */ + public ITimeGraphEntry[] getExpandedElements() { + return _stateCtrl.getExpandedElements(); + } + + /** + * Add a tree listener + * + * @param listener + * The listener to add + */ + public void addTreeListener(ITimeGraphTreeListener listener) { + _stateCtrl.addTreeListener(listener); + } + + /** + * Remove a tree listener + * + * @param listener + * The listener to remove + */ + public void removeTreeListener(ITimeGraphTreeListener listener) { + _stateCtrl.removeTreeListener(listener); + } + + /** + * Get the reset scale action. + * + * @return The Action object + */ + public Action getResetScaleAction() { + if (resetScale == null) { + // resetScale + resetScale = new Action() { + @Override + public void run() { + resetStartFinishTime(); + } + }; + resetScale.setText(Messages.TmfTimeGraphViewer_ResetScaleActionNameText); + resetScale.setToolTipText(Messages.TmfTimeGraphViewer_ResetScaleActionToolTipText); + resetScale.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_HOME_MENU)); + } + return resetScale; + } + + /** + * Get the show legend action. + * + * @return The Action object + */ + public Action getShowLegendAction() { + if (showLegendAction == null) { + // showLegend + showLegendAction = new Action() { + @Override + public void run() { + showLegend(); + } + }; + showLegendAction.setText(Messages.TmfTimeGraphViewer_LegendActionNameText); + showLegendAction.setToolTipText(Messages.TmfTimeGraphViewer_LegendActionToolTipText); + showLegendAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_SHOW_LEGEND)); + } + + return showLegendAction; + } + + /** + * Get the the next event action. + * + * @return The action object + */ + public Action getNextEventAction() { + if (nextEventAction == null) { + nextEventAction = new Action() { + @Override + public void run() { + selectNextEvent(); + } + }; + + nextEventAction.setText(Messages.TmfTimeGraphViewer_NextEventActionNameText); + nextEventAction.setToolTipText(Messages.TmfTimeGraphViewer_NextEventActionToolTipText); + nextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_EVENT)); + } + + return nextEventAction; + } + + /** + * Get the previous event action. + * + * @return The Action object + */ + public Action getPreviousEventAction() { + if (prevEventAction == null) { + prevEventAction = new Action() { + @Override + public void run() { + selectPrevEvent(); + } + }; + + prevEventAction.setText(Messages.TmfTimeGraphViewer_PreviousEventActionNameText); + prevEventAction.setToolTipText(Messages.TmfTimeGraphViewer_PreviousEventActionToolTipText); + prevEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_PREV_EVENT)); + } + + return prevEventAction; + } + + /** + * Get the next item action. + * + * @return The Action object + */ + public Action getNextItemAction() { + if (nextItemAction == null) { + + nextItemAction = new Action() { + @Override + public void run() { + selectNextItem(); + } + }; + nextItemAction.setText(Messages.TmfTimeGraphViewer_NextItemActionNameText); + nextItemAction.setToolTipText(Messages.TmfTimeGraphViewer_NextItemActionToolTipText); + nextItemAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_ITEM)); + } + return nextItemAction; + } + + /** + * Get the previous item action. + * + * @return The Action object + */ + public Action getPreviousItemAction() { + if (previousItemAction == null) { + + previousItemAction = new Action() { + @Override + public void run() { + selectPrevItem(); + } + }; + previousItemAction.setText(Messages.TmfTimeGraphViewer_PreviousItemActionNameText); + previousItemAction.setToolTipText(Messages.TmfTimeGraphViewer_PreviousItemActionToolTipText); + previousItemAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_PREV_ITEM)); + } + return previousItemAction; + } + + /** + * Get the zoom in action + * + * @return The Action object + */ + public Action getZoomInAction() { + if (zoomInAction == null) { + zoomInAction = new Action() { + @Override + public void run() { + zoomIn(); + } + }; + zoomInAction.setText(Messages.TmfTimeGraphViewer_ZoomInActionNameText); + zoomInAction.setToolTipText(Messages.TmfTimeGraphViewer_ZoomInActionToolTipText); + zoomInAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_ZOOM_IN_MENU)); + } + return zoomInAction; + } + + /** + * Get the zoom out action + * + * @return The Action object + */ + public Action getZoomOutAction() { + if (zoomOutAction == null) { + zoomOutAction = new Action() { + @Override + public void run() { + zoomOut(); + } + }; + zoomOutAction.setText(Messages.TmfTimeGraphViewer_ZoomOutActionNameText); + zoomOutAction.setToolTipText(Messages.TmfTimeGraphViewer_ZoomOutActionToolTipText); + zoomOutAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_ZOOM_OUT_MENU)); + } + return zoomOutAction; + } + + + private void adjustVerticalScrollBar() { + int topIndex = _stateCtrl.getTopIndex(); + int countPerPage = _stateCtrl.countPerPage(); + int expandedElementCount = _stateCtrl.getExpandedElementCount(); + if (topIndex + countPerPage > expandedElementCount) { + _stateCtrl.setTopIndex(Math.max(0, expandedElementCount - countPerPage)); + } + + int selection = _stateCtrl.getTopIndex(); + int min = 0; + int max = Math.max(1, expandedElementCount - 1); + int thumb = Math.min(max, Math.max(1, countPerPage - 1)); + int increment = 1; + int pageIncrement = Math.max(1, countPerPage); + _verticalScrollBar.setValues(selection, min, max, thumb, increment, pageIncrement); + } + + + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/dialogs/TimeGraphLegend.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/dialogs/TimeGraphLegend.java index 55c9d02459..e5e625ab3d 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/dialogs/TimeGraphLegend.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/dialogs/TimeGraphLegend.java @@ -1,178 +1,178 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Ericsson. - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon - Initial API and implementation - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.dialogs; - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.resource.LocalResourceManager; -import org.eclipse.linuxtools.internal.tmf.ui.Messages; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Shell; - -/** - * Legend for the colors used in the time graph view - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public class TimeGraphLegend extends TitleAreaDialog { - - private final ITimeGraphPresentationProvider provider; - private final LocalResourceManager fResourceManager = new LocalResourceManager(JFaceResources.getResources()); - - /** - * Open the time graph legend window - * - * @param parent - * The parent shell - * @param provider - * The presentation provider - */ - public static void open(Shell parent, ITimeGraphPresentationProvider provider) { - (new TimeGraphLegend(parent, provider)).open(); - } - - /** - * Standard constructor - * - * @param parent - * The parent shell - * @param provider - * The presentation provider - */ - public TimeGraphLegend(Shell parent, ITimeGraphPresentationProvider provider) { - super(parent); - this.provider = provider; - this.setShellStyle(getShellStyle()); - } - - @Override - protected Control createDialogArea(Composite parent) { - Composite dlgArea = (Composite) super.createDialogArea(parent); - Composite composite = new Composite(dlgArea, SWT.NONE); - - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - composite.setLayoutData(gd); - - createStatesGroup(composite); - - setTitle(Messages.TmfTimeLegend_LEGEND); - setDialogHelpAvailable(false); - setHelpAvailable(false); - - return composite; - } - - private void createStatesGroup(Composite composite) { - Group gs = new Group(composite, SWT.NONE); - gs.setText(provider.getStateTypeName() + " " + Messages.TmfTimeLegend_StateTypeName); //$NON-NLS-1$ - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gs.setLayoutData(gd); - - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginWidth = 20; - layout.marginBottom = 10; - gs.setLayout(layout); - - // Go through all the defined pairs of state color and state name and display them. - StateItem[] stateItems = provider.getStateTable(); - for (int i = 0; i < stateItems.length; i++) { - //Get the color related to the index - RGB rgb = stateItems[i].getStateColor(); - - //Get the given name, provided by the interface to the application - String stateName = stateItems[i].getStateString(); - - // draw color with name - Bar bar = new Bar(gs, rgb); - gd = new GridData(); - gd.widthHint = 40; - gd.heightHint = 20; - gd.verticalIndent = 8; - bar.setLayoutData(gd); - Label name = new Label(gs, SWT.NONE); - name.setText(stateName); - gd = new GridData(); - gd.horizontalIndent = 10; - gd.verticalIndent = 8; - name.setLayoutData(gd); - } - } - - @Override - protected void configureShell(Shell shell) { - super.configureShell(shell); - shell.setText(Messages.TmfTimeLegend_TRACE_STATES_TITLE); - } - - @Override - protected void createButtonsForButtonBar(Composite parent) { - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, - true); - } - - class Bar extends Canvas { - private final Color color; - - public Bar(Composite parent, RGB rgb) { - super(parent, SWT.NONE); - - color = fResourceManager.createColor(rgb); - addListener(SWT.Paint, new Listener() { - @Override - public void handleEvent(Event event) { - draw(event.gc); - } - }); - } - - private void draw(GC gc) { - Rectangle r = getClientArea(); - gc.setBackground(color); - gc.fillRectangle(r); - gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); - gc.drawRectangle(0, 0, r.width - 1, r.height - 1); - } - - @Override - public void dispose() { - super.dispose(); - color.dispose(); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2009, 2012 Ericsson. + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon - Initial API and implementation + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.dialogs; + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.resource.LocalResourceManager; +import org.eclipse.linuxtools.internal.tmf.ui.Messages; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.ITimeGraphPresentationProvider; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.StateItem; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; + +/** + * Legend for the colors used in the time graph view + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public class TimeGraphLegend extends TitleAreaDialog { + + private final ITimeGraphPresentationProvider provider; + private final LocalResourceManager fResourceManager = new LocalResourceManager(JFaceResources.getResources()); + + /** + * Open the time graph legend window + * + * @param parent + * The parent shell + * @param provider + * The presentation provider + */ + public static void open(Shell parent, ITimeGraphPresentationProvider provider) { + (new TimeGraphLegend(parent, provider)).open(); + } + + /** + * Standard constructor + * + * @param parent + * The parent shell + * @param provider + * The presentation provider + */ + public TimeGraphLegend(Shell parent, ITimeGraphPresentationProvider provider) { + super(parent); + this.provider = provider; + this.setShellStyle(getShellStyle()); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite dlgArea = (Composite) super.createDialogArea(parent); + Composite composite = new Composite(dlgArea, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + composite.setLayout(layout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + composite.setLayoutData(gd); + + createStatesGroup(composite); + + setTitle(Messages.TmfTimeLegend_LEGEND); + setDialogHelpAvailable(false); + setHelpAvailable(false); + + return composite; + } + + private void createStatesGroup(Composite composite) { + Group gs = new Group(composite, SWT.NONE); + gs.setText(provider.getStateTypeName() + " " + Messages.TmfTimeLegend_StateTypeName); //$NON-NLS-1$ + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gs.setLayoutData(gd); + + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginWidth = 20; + layout.marginBottom = 10; + gs.setLayout(layout); + + // Go through all the defined pairs of state color and state name and display them. + StateItem[] stateItems = provider.getStateTable(); + for (int i = 0; i < stateItems.length; i++) { + //Get the color related to the index + RGB rgb = stateItems[i].getStateColor(); + + //Get the given name, provided by the interface to the application + String stateName = stateItems[i].getStateString(); + + // draw color with name + Bar bar = new Bar(gs, rgb); + gd = new GridData(); + gd.widthHint = 40; + gd.heightHint = 20; + gd.verticalIndent = 8; + bar.setLayoutData(gd); + Label name = new Label(gs, SWT.NONE); + name.setText(stateName); + gd = new GridData(); + gd.horizontalIndent = 10; + gd.verticalIndent = 8; + name.setLayoutData(gd); + } + } + + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(Messages.TmfTimeLegend_TRACE_STATES_TITLE); + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, + true); + } + + class Bar extends Canvas { + private final Color color; + + public Bar(Composite parent, RGB rgb) { + super(parent, SWT.NONE); + + color = fResourceManager.createColor(rgb); + addListener(SWT.Paint, new Listener() { + @Override + public void handleEvent(Event event) { + draw(event.gc); + } + }); + } + + private void draw(GC gc) { + Rectangle r = getClientArea(); + gc.setBackground(color); + gc.fillRectangle(r); + gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); + gc.drawRectangle(0, 0, r.width - 1, r.height - 1); + } + + @Override + public void dispose() { + super.dispose(); + color.dispose(); + } + + } + +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeEvent.java index 73a10e3bb6..9326eb84be 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeEvent.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon - Initial API and implementation - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; - -/** - * Interface for time events, for use in the timegraph view - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public interface ITimeEvent { - - /** - * Get the entry matching this time event. - * - * @return The time graph entry - */ - public ITimeGraphEntry getEntry(); - - /** - * Get the timestamp of this event. - * - * @return The event's time - */ - public long getTime(); - - /** - * @return - * - *
  • -1: Considers duration to be from current event till the next
  • - *
  • 0: Duration is not relevant e.g. a Burst / no state associated
  • - *
  • >0: Valid duration value specified
  • - *
    - *

    - */ - public long getDuration(); - +/******************************************************************************* + * Copyright (c) 2009, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon - Initial API and implementation + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; + +/** + * Interface for time events, for use in the timegraph view + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public interface ITimeEvent { + + /** + * Get the entry matching this time event. + * + * @return The time graph entry + */ + public ITimeGraphEntry getEntry(); + + /** + * Get the timestamp of this event. + * + * @return The event's time + */ + public long getTime(); + + /** + * @return + * + *

  • -1: Considers duration to be from current event till the next
  • + *
  • 0: Duration is not relevant e.g. a Burst / no state associated
  • + *
  • >0: Valid duration value specified
  • + * + *

    + */ + public long getDuration(); + } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeGraphEntry.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeGraphEntry.java index 16d50257aa..f31d7c2a7e 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeGraphEntry.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/ITimeGraphEntry.java @@ -1,100 +1,100 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alvaro Sanchez-Leon - Initial API and implementation - * Patrick Tasse - Refactoring - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; - -import java.util.Iterator; - -/** - * Interface for an entry (row) in the time graph view - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public interface ITimeGraphEntry { - - /** - * Returns the parent of this entry, or null if it has none. - * - * @return the parent element, or null if it has none - */ - public ITimeGraphEntry getParent(); - - /** - * Returns whether this entry has children. - * - * @return true if the given element has children, - * and false if it has no children - */ - public boolean hasChildren(); - - /** - * Returns the child elements of this entry. - * - * @return an array of child elements - */ - public ITimeGraphEntry[] getChildren(); - - /** - * Returns the name of this entry. - * - * @return the entry name - */ - public String getName(); - - /** - * Returns the start time of this entry in nanoseconds. - * - * @return the start time - */ - public long getStartTime(); - - /** - * Returns the end time of this entry in nanoseconds. - * - * @return the end time - */ - public long getEndTime(); - - /** - * Returns whether this entry has time events. - * If true, the time events iterator should not be null. - * - * @return true if the entry has time events - * - * @see #getTimeEventsIterator - * @see #getTimeEventsIterator(long, long, long) - */ - public boolean hasTimeEvents(); - - /** - * Get an iterator which returns all time events. - * - * @return the iterator - */ - public Iterator getTimeEventsIterator(); - - /** - * Get an iterator which only returns events that fall within the start time and the stop time. - * The visible duration is the event duration below which further detail is not discernible. - * If no such iterator is implemented, provide a basic iterator which returns all events. - * - * @param startTime start time in nanoseconds - * @param stopTime stop time in nanoseconds - * @param visibleDuration duration of one pixel in nanoseconds - * - * @return the iterator - */ - public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration); -} +/******************************************************************************* + * Copyright (c) 2009, 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alvaro Sanchez-Leon - Initial API and implementation + * Patrick Tasse - Refactoring + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; + +import java.util.Iterator; + +/** + * Interface for an entry (row) in the time graph view + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public interface ITimeGraphEntry { + + /** + * Returns the parent of this entry, or null if it has none. + * + * @return the parent element, or null if it has none + */ + public ITimeGraphEntry getParent(); + + /** + * Returns whether this entry has children. + * + * @return true if the given element has children, + * and false if it has no children + */ + public boolean hasChildren(); + + /** + * Returns the child elements of this entry. + * + * @return an array of child elements + */ + public ITimeGraphEntry[] getChildren(); + + /** + * Returns the name of this entry. + * + * @return the entry name + */ + public String getName(); + + /** + * Returns the start time of this entry in nanoseconds. + * + * @return the start time + */ + public long getStartTime(); + + /** + * Returns the end time of this entry in nanoseconds. + * + * @return the end time + */ + public long getEndTime(); + + /** + * Returns whether this entry has time events. + * If true, the time events iterator should not be null. + * + * @return true if the entry has time events + * + * @see #getTimeEventsIterator + * @see #getTimeEventsIterator(long, long, long) + */ + public boolean hasTimeEvents(); + + /** + * Get an iterator which returns all time events. + * + * @return the iterator + */ + public Iterator getTimeEventsIterator(); + + /** + * Get an iterator which only returns events that fall within the start time and the stop time. + * The visible duration is the event duration below which further detail is not discernible. + * If no such iterator is implemented, provide a basic iterator which returns all events. + * + * @param startTime start time in nanoseconds + * @param stopTime stop time in nanoseconds + * @param visibleDuration duration of one pixel in nanoseconds + * + * @return the iterator + */ + public Iterator getTimeEventsIterator(long startTime, long stopTime, long visibleDuration); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/TimeEvent.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/TimeEvent.java index aa82194f78..34988a6df5 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/TimeEvent.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/model/TimeEvent.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; - -/** - * Generic TimeEvent implementation - * - * @version 1.0 - * @author Patrick Tasse - */ -public class TimeEvent implements ITimeEvent { - protected ITimeGraphEntry fEntry; - protected long fTime; - protected long fDuration; - - /** - * Standard constructor - * - * @param entry - * The entry matching this event - * @param time - * The timestamp of this event - * @param duration - * The duration of the event - */ - public TimeEvent(ITimeGraphEntry entry, long time, long duration) { - fEntry = entry; - fTime = time; - fDuration = duration; - } - - @Override - public ITimeGraphEntry getEntry() { - return fEntry; - } - - @Override - public long getTime() { - return fTime; - } - - @Override - public long getDuration() { - return fDuration; - } -} +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model; + +/** + * Generic TimeEvent implementation + * + * @version 1.0 + * @author Patrick Tasse + */ +public class TimeEvent implements ITimeEvent { + protected ITimeGraphEntry fEntry; + protected long fTime; + protected long fDuration; + + /** + * Standard constructor + * + * @param entry + * The entry matching this event + * @param time + * The timestamp of this event + * @param duration + * The duration of the event + */ + public TimeEvent(ITimeGraphEntry entry, long time, long duration) { + fEntry = entry; + fTime = time; + fDuration = duration; + } + + @Override + public ITimeGraphEntry getEntry() { + return fEntry; + } + + @Override + public long getTime() { + return fTime; + } + + @Override + public long getDuration() { + return fDuration; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/ITimeDataProvider.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/ITimeDataProvider.java index 3b9fc98a8c..260eb1b4cf 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/ITimeDataProvider.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/ITimeDataProvider.java @@ -1,139 +1,139 @@ -/***************************************************************************** - * Copyright (c) 2007 Intel Corporation, 2010, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alvaro Sanchez-Leon - Updated for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -/** - * Time data provider interface, for use in the timegraph widget. - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public interface ITimeDataProvider { - - /** - * @return The selected time - */ - long getSelectedTime(); - - /** - * @return The beginning time - */ - long getBeginTime(); - - /** - * @return The end time - */ - long getEndTime(); - - /** - * @return The minimum time - */ - long getMinTime(); - - /** - * @return The maximum time - */ - long getMaxTime(); - - /** - * @return The start time of the current selection window - */ - long getTime0(); - - /** - * @return The end time of the current selection window - */ - long getTime1(); - - /** - * @return The minimal time interval - */ - long getMinTimeInterval(); - - /** - * Updates the time range and notify registered listeners - * - * @param time0 - * @param time1 - */ - void setStartFinishTimeNotify(long time0, long time1); - - /** - * Update the time range but do not trigger event notification - * - * @param time0 - * @param time1 - */ - void setStartFinishTime(long time0, long time1); - - /** - * Notify registered listeners without updating the time range - */ - void notifyStartFinishTime(); - - /** - * Updates the selected time, adjusts the time range if necessary and - * notifies any registered listeners about the new selected time and new - * range (if necessary) - * - * @param time - * A Time to set - * @param ensureVisible - * Ensure visibility of new time (will adjust time range if - * necessary) - */ - public void setSelectedTimeNotify(long time, boolean ensureVisible); - - /** - * Updates the selected time and adjusts the time range if necessary without - * notifying registered listeners. - * - * @param time - * A Time to set - * @param ensureVisible - * Ensure visibility of new time (will adjust time range if - * necessary) - */ - public void setSelectedTime(long time, boolean ensureVisible); - - /** - * Reset the start and end times - */ - void resetStartFinishTime(); - - /** - * @return The names' width - */ - int getNameSpace(); - - /** - * Set the names' width - * - * @param width - */ - void setNameSpace(int width); - - /** - * @return The width for timestamps - */ - int getTimeSpace(); - - /** - * @return If the calendar format is absolute (true) or relative (false) - */ - boolean isCalendarFormat(); -} +/***************************************************************************** + * Copyright (c) 2007 Intel Corporation, 2010, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alvaro Sanchez-Leon - Updated for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +/** + * Time data provider interface, for use in the timegraph widget. + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public interface ITimeDataProvider { + + /** + * @return The selected time + */ + long getSelectedTime(); + + /** + * @return The beginning time + */ + long getBeginTime(); + + /** + * @return The end time + */ + long getEndTime(); + + /** + * @return The minimum time + */ + long getMinTime(); + + /** + * @return The maximum time + */ + long getMaxTime(); + + /** + * @return The start time of the current selection window + */ + long getTime0(); + + /** + * @return The end time of the current selection window + */ + long getTime1(); + + /** + * @return The minimal time interval + */ + long getMinTimeInterval(); + + /** + * Updates the time range and notify registered listeners + * + * @param time0 + * @param time1 + */ + void setStartFinishTimeNotify(long time0, long time1); + + /** + * Update the time range but do not trigger event notification + * + * @param time0 + * @param time1 + */ + void setStartFinishTime(long time0, long time1); + + /** + * Notify registered listeners without updating the time range + */ + void notifyStartFinishTime(); + + /** + * Updates the selected time, adjusts the time range if necessary and + * notifies any registered listeners about the new selected time and new + * range (if necessary) + * + * @param time + * A Time to set + * @param ensureVisible + * Ensure visibility of new time (will adjust time range if + * necessary) + */ + public void setSelectedTimeNotify(long time, boolean ensureVisible); + + /** + * Updates the selected time and adjusts the time range if necessary without + * notifying registered listeners. + * + * @param time + * A Time to set + * @param ensureVisible + * Ensure visibility of new time (will adjust time range if + * necessary) + */ + public void setSelectedTime(long time, boolean ensureVisible); + + /** + * Reset the start and end times + */ + void resetStartFinishTime(); + + /** + * @return The names' width + */ + int getNameSpace(); + + /** + * Set the names' width + * + * @param width + */ + void setNameSpace(int width); + + /** + * @return The width for timestamps + */ + int getTimeSpace(); + + /** + * @return If the calendar format is absolute (true) or relative (false) + */ + boolean isCalendarFormat(); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphBaseControl.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphBaseControl.java index 96d8189116..3be2c0a5b6 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphBaseControl.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphBaseControl.java @@ -1,107 +1,107 @@ -/***************************************************************************** - * Copyright (c) 2007 Intel Corporation, 2009, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alvaro Sanchez-Leon - Updated for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.Composite; - -/** - * Base control abstract class for the time graph widget - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public abstract class TimeGraphBaseControl extends Canvas implements PaintListener { - - /** Default left margin size */ - static public final int MARGIN = 4; - - /** Default expanded size */ - static public final int EXPAND_SIZE = 9; // the [+] or [-] control size - - /** Default size of the right margin */ - static public final int RIGHT_MARGIN = 1; // 1 pixels less to make sure end time is visible - - /** Default size for small icons */ - static public final int SMALL_ICON_SIZE = 16; - - protected TimeGraphColorScheme _colors; - protected int _fontHeight = 0; - - /** - * Basic constructor. Uses a default style value - * - * @param parent - * The parent composite object - * @param colors - * The color scheme to use - */ - public TimeGraphBaseControl(Composite parent, TimeGraphColorScheme colors) { - this(parent, colors, SWT.NO_BACKGROUND | SWT.NO_FOCUS); - } - - /** - * Standard constructor - * - * @param parent - * The parent composite object - * @param colors - * The color scheme to use - * @param style - * The index of the style to use - */ - public TimeGraphBaseControl(Composite parent, TimeGraphColorScheme colors, int style) { - super(parent, style); - _colors = colors; - addPaintListener(this); - } - - @Override - public void dispose() { - super.dispose(); - } - - @Override - public void paintControl(PaintEvent e) { - if (e.widget != this) { - return; - } - _fontHeight = e.gc.getFontMetrics().getHeight(); - Rectangle bound = getClientArea(); - if (!bound.isEmpty()) { - Color colBackup = e.gc.getBackground(); - paint(bound, e); - e.gc.setBackground(colBackup); - } - } - - /** - * Retrieve the current font's height - * - * @return The height - */ - public int getFontHeight() { - return _fontHeight; - } - - abstract void paint(Rectangle bound, PaintEvent e); -} +/***************************************************************************** + * Copyright (c) 2007 Intel Corporation, 2009, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alvaro Sanchez-Leon - Updated for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; + +/** + * Base control abstract class for the time graph widget + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public abstract class TimeGraphBaseControl extends Canvas implements PaintListener { + + /** Default left margin size */ + static public final int MARGIN = 4; + + /** Default expanded size */ + static public final int EXPAND_SIZE = 9; // the [+] or [-] control size + + /** Default size of the right margin */ + static public final int RIGHT_MARGIN = 1; // 1 pixels less to make sure end time is visible + + /** Default size for small icons */ + static public final int SMALL_ICON_SIZE = 16; + + protected TimeGraphColorScheme _colors; + protected int _fontHeight = 0; + + /** + * Basic constructor. Uses a default style value + * + * @param parent + * The parent composite object + * @param colors + * The color scheme to use + */ + public TimeGraphBaseControl(Composite parent, TimeGraphColorScheme colors) { + this(parent, colors, SWT.NO_BACKGROUND | SWT.NO_FOCUS); + } + + /** + * Standard constructor + * + * @param parent + * The parent composite object + * @param colors + * The color scheme to use + * @param style + * The index of the style to use + */ + public TimeGraphBaseControl(Composite parent, TimeGraphColorScheme colors, int style) { + super(parent, style); + _colors = colors; + addPaintListener(this); + } + + @Override + public void dispose() { + super.dispose(); + } + + @Override + public void paintControl(PaintEvent e) { + if (e.widget != this) { + return; + } + _fontHeight = e.gc.getFontMetrics().getHeight(); + Rectangle bound = getClientArea(); + if (!bound.isEmpty()) { + Color colBackup = e.gc.getBackground(); + paint(bound, e); + e.gc.setBackground(colBackup); + } + } + + /** + * Retrieve the current font's height + * + * @return The height + */ + public int getFontHeight() { + return _fontHeight; + } + + abstract void paint(Rectangle bound, PaintEvent e); +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphColorScheme.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphColorScheme.java index d8061804b2..b398df4091 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphColorScheme.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphColorScheme.java @@ -1,430 +1,430 @@ -/***************************************************************************** - * Copyright (c) 2008 Intel Corporation, 2009, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alvaro Sanchez-Leon - Updated for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; - -/** - * Color theme used by the timegraph view - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TimeGraphColorScheme { - - // elements color indices - static public final int BLACK_STATE = 0; - static public final int GREEN_STATE = 1; - static public final int DARK_BLUE_STATE = 2; - static public final int ORANGE_STATE = 3; - static public final int GOLD_STATE = 4; - static public final int RED_STATE = 5; - static public final int GRAY_STATE = 6; - static public final int DARK_GREEN_STATE = 7; - static public final int DARK_YELLOW_STATE = 8; - static public final int MAGENTA3_STATE = 9; - static public final int PURPLE1_STATE = 10; - static public final int PINK1_STATE = 11; - static public final int AQUAMARINE_STATE = 12; - static public final int LIGHT_BLUE_STATE = 13; - static public final int CADET_BLUE_STATE = 14; - static public final int OLIVE_STATE = 15; - - static public final int STATES0 = 0; - static public final int STATES1 = 15; - - // selected state elements color indices - static public final int BLACK_STATE_SEL = 16; - static public final int GREEN_STATE_SEL = 17; - static public final int DARK_BLUE_STATE_SEL = 18; - static public final int ORANGE_STATE_SEL = 19; - static public final int GOLD_STATE_SEL = 20; - static public final int RED_STATE_SEL = 21; - static public final int GRAY_STATE_SEL = 22; - static public final int DARK_GREEN_STATE_SEL = 23; - static public final int DARK_YELLOW_STATE_SEL = 24; - static public final int MAGENTA3_STATE_SEL = 25; - static public final int PURPLE1_STATE_SEL = 26; - static public final int PINK1_STATE_SEL = 27; - static public final int AQUAMARINE_STATE_SEL = 28; - static public final int LIGHT_BLUE_STATE_SEL = 29; - static public final int CADET_BLUE_STATE_SEL = 30; - static public final int OLIVE_STATE_SEL = 31; - - static public final int STATES_SEL0 = 16; - static public final int STATES_SEL1 = 31; - - // colors indices for viewer controls - static public final int BACKGROUND = 32; - static public final int FOREGROUND = 33; - static public final int BACKGROUND_SEL = 34; - static public final int FOREGROUND_SEL = 35; - static public final int BACKGROUND_SEL_NOFOCUS = 36; - static public final int FOREGROUND_SEL_NOFOCUS = 37; - static public final int TOOL_BACKGROUND = 38; - static public final int TOOL_FOREGROUND = 39; - - // misc colors - static public final int FIX_COLOR = 40; - static public final int WHITE = 41; - static public final int GRAY = 42; - static public final int BLACK = 43; - static public final int DARK_GRAY = 44; - - // selected border color indices - static public final int BLACK_BORDER = 45; - static public final int GREEN_BORDER = 46; - static public final int DARK_BLUE_BORDER = 47; - static public final int ORANGE_BORDER = 48; - static public final int GOLD_BORDER = 49; - static public final int RED_BORDER = 50; - static public final int GRAY_BORDER = 51; - static public final int DARK_GREEN_BORDER1 = 52; - static public final int DARK_YELLOW_BORDER1 = 53; - static public final int MAGENTA3_BORDER1 = 54; - static public final int PURPLE1_BORDER1 = 55; - static public final int PINK1_BORDER1 = 56; - static public final int AQUAMARINE_BORDER1 = 57; - static public final int LIGHT_BLUE_BORDER1 = 58; - static public final int CADET_BLUE_STATE_BORDER = 59; - static public final int OLIVE_BORDER2 = 60; - - static public final int STATES_BORDER0 = 45; - static public final int STATES_BORDER1 = 60; - - static public final int MID_LINE = 61; - static public final int RED = 62; - static public final int GREEN = 63; - static public final int BLUE = 64; - static public final int YELLOW = 65; - static public final int CYAN = 66; - static public final int MAGENTA = 67; - - static public final int SELECTED_TIME = 68; - static public final int LEGEND_BACKGROUND = 69; - static public final int LEGEND_FOREGROUND = 70; - - // group items' colors - static public final int GR_BACKGROUND = 71; - static public final int GR_FOREGROUND = 72; - static public final int GR_BACKGROUND_SEL = 73; - static public final int GR_FOREGROUND_SEL = 74; - static public final int GR_BACKGROUND_SEL_NOFOCUS = 75; - static public final int GR_FOREGROUND_SEL_NOFOCUS = 76; - - static public final int LIGHT_LINE = 77; - static public final int BACKGROUND_NAME = 78; - static public final int BACKGROUND_NAME_SEL = 79; - static public final int BACKGROUND_NAME_SEL_NOFOCUS = 80; - - // Interraction's colors - static public final int TI_START_THREAD = BLACK; - static public final int TI_HANDOFF_LOCK = BLUE; - static public final int TI_NOTIFY_ALL = GREEN; - static public final int TI_NOTIFY = GREEN; - static public final int TI_NOTIFY_JOINED = DARK_GRAY; - static public final int TI_INTERRUPT = RED; - static public final int TI_WAIT_EXCEEDED = BLUE; - - static interface IColorProvider { - public Color get(); - } - - static class SysCol implements IColorProvider { - int syscol; - - SysCol(int syscol) { - this.syscol = syscol; - } - - @Override - public Color get() { - return Utils.getSysColor(syscol); - } - } - - static class RGB implements IColorProvider { - int r; - int g; - int b; - - RGB(int r, int g, int b) { - this.r = r; - this.g = g; - this.b = b; - } - - @Override - public Color get() { - return new Color(null, r, g, b); - } - } - - static class Mix implements IColorProvider { - IColorProvider cp1; - IColorProvider cp2; - int w1; - int w2; - - Mix(IColorProvider cp1, IColorProvider cp2, int w1, int w2) { - this.cp1 = cp1; - this.cp2 = cp2; - this.w1 = w1; - this.w2 = w2; - } - - Mix(IColorProvider cp1, IColorProvider cp2) { - this.cp1 = cp1; - this.cp2 = cp2; - this.w1 = 1; - this.w2 = 1; - } - - @Override - public Color get() { - Color col1 = cp1.get(); - Color col2 = cp2.get(); - Color col = Utils.mixColors(col1, col2, w1, w2); - return col; - } - } - - static private final IColorProvider _providersMap[] = { - // - new RGB(100, 100, 100), // UNKNOWN - new RGB(174, 200, 124), // RUNNING - new Mix(new SysCol(SWT.COLOR_BLUE), new SysCol(SWT.COLOR_GRAY), 1, 3), // SLEEPING - new RGB(210, 150, 60), // WAITING - new RGB(242, 225, 168), // BLOCKED - new Mix(new SysCol(SWT.COLOR_RED), new SysCol(SWT.COLOR_GRAY), 1, 3), // DEADLOCK - new RGB(200, 200, 200), // STOPPED - new RGB(35, 107, 42), // STEEL BLUE - new RGB(205,205,0), // DARK YELLOW - new RGB(205, 0, 205), // MAGENTA - new RGB(171, 130, 255), // PURPLE - new RGB(255, 181, 197), // PINK - new RGB(112, 219, 147), // AQUAMARINE - new RGB(198, 226, 255), // SLATEGRAY - new RGB(95, 158, 160), // CADET BLUE - new RGB(107, 142, 35), // OLIVE - - - //TODO: Does not seem to be used, check during clean-up - new SysCol(SWT.COLOR_WHITE), // UNKNOWN_SEL - new SysCol(SWT.COLOR_GREEN), // RUNNING_SEL - new SysCol(SWT.COLOR_BLUE), // SLEEPING_SEL - new SysCol(SWT.COLOR_CYAN), // WAITING_SEL - new SysCol(SWT.COLOR_YELLOW), // BLOCKED_SEL - new SysCol(SWT.COLOR_RED), // DEADLOCK_SEL - new SysCol(SWT.COLOR_DARK_GRAY), // STOPPED_SEL - new SysCol(SWT.COLOR_WHITE), - new SysCol(SWT.COLOR_GREEN), - new SysCol(SWT.COLOR_BLUE), - new SysCol(SWT.COLOR_CYAN), - new SysCol(SWT.COLOR_YELLOW), - new SysCol(SWT.COLOR_RED), - new SysCol(SWT.COLOR_DARK_GRAY), - new SysCol(SWT.COLOR_WHITE), - new SysCol(SWT.COLOR_GREEN), - - - new SysCol(SWT.COLOR_LIST_BACKGROUND), // BACKGROUND - new SysCol(SWT.COLOR_LIST_FOREGROUND), // FOREGROUND - new RGB(232, 242, 254), // BACKGROUND_SEL - new SysCol(SWT.COLOR_LIST_FOREGROUND), // FOREGROUND_SEL - new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // BACKGROUND_SEL_NOFOCUS - new SysCol(SWT.COLOR_WIDGET_FOREGROUND), // FOREGROUND_SEL_NOFOCUS - new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // TOOL_BACKGROUND - new SysCol(SWT.COLOR_WIDGET_DARK_SHADOW), // TOOL_FOREGROUND - - new SysCol(SWT.COLOR_GRAY), // FIX_COLOR - new SysCol(SWT.COLOR_WHITE), // WHITE - new SysCol(SWT.COLOR_GRAY), // GRAY - new SysCol(SWT.COLOR_BLACK), // BLACK - new SysCol(SWT.COLOR_DARK_GRAY), // DARK_GRAY - - new SysCol(SWT.COLOR_DARK_GRAY), // BLACK_BORDER - new RGB(75, 115, 120), // GREEN_BORDER - new SysCol(SWT.COLOR_DARK_BLUE), // DARK_BLUE_BORDER - new RGB(242, 225, 168), // ORANGE_BORDER - new RGB(210, 150, 60), // GOLD_BORDER - new SysCol(SWT.COLOR_DARK_RED), // RED_BORDER - new SysCol(SWT.COLOR_BLACK), // GRAY_BORDER - new SysCol(SWT.COLOR_DARK_GRAY), // DARK_GREEN_BORDER - new RGB(75, 115, 120), // DARK_YELLOW_BORDER - new SysCol(SWT.COLOR_DARK_BLUE), // MAGENTA3_BORDER - new RGB(242, 225, 168), // PURPLE1_BORDER - new RGB(210, 150, 60), // PINK1_BORDER - new SysCol(SWT.COLOR_DARK_RED), // AQUAMARINE_BORDER - new SysCol(SWT.COLOR_BLACK), // LIGHT_BLUE_BORDER - new SysCol(SWT.COLOR_DARK_GRAY), // BLUE_BORDER - new RGB(75, 115, 120), // OLIVE_BORDER - - - new SysCol(SWT.COLOR_GRAY), // MID_LINE - new SysCol(SWT.COLOR_RED), // RED - new SysCol(SWT.COLOR_GREEN), // GREEN - new SysCol(SWT.COLOR_BLUE), // BLUE - new SysCol(SWT.COLOR_YELLOW), // YELLOW - new SysCol(SWT.COLOR_CYAN), // CYAN - new SysCol(SWT.COLOR_MAGENTA), // MAGENTA - - new SysCol(SWT.COLOR_BLUE), // SELECTED_TIME - new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // LEGEND_BACKGROUND - new SysCol(SWT.COLOR_WIDGET_DARK_SHADOW), // LEGEND_FOREGROUND - - new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_LIST_BACKGROUND)), // GR_BACKGROUND - new RGB(0, 0, 50), // GR_FOREGROUND - new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_WHITE), 6, 1), // GR_BACKGROUND_SEL - new RGB(0, 0, 50), // GR_FOREGROUND_SEL - new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_WHITE), 6, 1), // GR_BACKGROUND_SEL_NOFOCUS - new RGB(0, 0, 50), // GR_FOREGROUND_SEL_NOFOCUS - - new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_LIST_BACKGROUND), 1, 3), // LIGHT_LINE - - new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_LIST_BACKGROUND), 1, 6), // BACKGROUND_NAME - new Mix(new SysCol(SWT.COLOR_GRAY), new RGB(232, 242, 254), 1, 6), // BACKGROUND_NAME_SEL - new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_WIDGET_BACKGROUND), 1, 6), // BACKGROUND_NAME_SEL_NOFOCUS - }; - - private final Color _colors[]; - - /** - * Default constructor - */ - public TimeGraphColorScheme() { - _colors = new Color[_providersMap.length]; - } - - /** - * Dispose this color scheme - */ - public void dispose() { - for (int i = 0; i < _colors.length; i++) { - Utils.dispose(_colors[i]); - _colors[i] = null; - } - } - - /** - * Get the color matching the given index - * - * @param idx - * The index - * @return The matching color - */ - public Color getColor(int idx) { - if (null == _colors[idx]) { - if (idx >= STATES_SEL0 && idx <= STATES_SEL1) { - Color col1 = getColor(idx - STATES_SEL0); - Color col2 = getColor(BACKGROUND_SEL); - _colors[idx] = Utils.mixColors(col1, col2, 3, 1); - } else { - _colors[idx] = _providersMap[idx].get(); - } - } - return _colors[idx]; - } - - /** - * Get an entry's background color based on its status. - * - * @param selected - * If the entry is selected - * @param focused - * If the entry is focused - * @param name - * Get the color of the name column (false for other columns) - * @return The matching color - */ - public Color getBkColor(boolean selected, boolean focused, boolean name) { - if (name) { - if (selected && focused) { - return getColor(BACKGROUND_NAME_SEL); - } - if (selected) { - return getColor(BACKGROUND_NAME_SEL_NOFOCUS); - } - return getColor(BACKGROUND_NAME); - } - if (selected && focused) { - return getColor(BACKGROUND_SEL); - } - if (selected) { - return getColor(BACKGROUND_SEL_NOFOCUS); - } - return getColor(BACKGROUND); - } - - /** - * Get the correct foreground color - * - * @param selected - * Is the entry selected - * @param focused - * Is the entry focused - * @return The matching color - */ - public Color getFgColor(boolean selected, boolean focused) { - if (selected && focused) { - return getColor(FOREGROUND_SEL); - } - if (selected) { - return getColor(FOREGROUND_SEL_NOFOCUS); - } - return getColor(FOREGROUND); - } - - /** - * Get the correct background color group - * - * @param selected - * Is the entry selected - * @param focused - * Is the entry focused - * @return The matching color - */ - public Color getBkColorGroup(boolean selected, boolean focused) { - if (selected && focused) { - return getColor(GR_BACKGROUND_SEL); - } - if (selected) { - return getColor(GR_BACKGROUND_SEL_NOFOCUS); - } - return getColor(GR_BACKGROUND); - } - - /** - * Get the correct foreground color group - * - * @param selected - * Is the entry selected - * @param focused - * Is the entry focused - * @return The matching color - */ - public Color getFgColorGroup(boolean selected, boolean focused) { - if (selected && focused) { - return getColor(GR_FOREGROUND_SEL); - } - if (selected) { - return getColor(GR_FOREGROUND_SEL_NOFOCUS); - } - return getColor(GR_FOREGROUND); - } -} +/***************************************************************************** + * Copyright (c) 2008 Intel Corporation, 2009, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alvaro Sanchez-Leon - Updated for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; + +/** + * Color theme used by the timegraph view + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TimeGraphColorScheme { + + // elements color indices + static public final int BLACK_STATE = 0; + static public final int GREEN_STATE = 1; + static public final int DARK_BLUE_STATE = 2; + static public final int ORANGE_STATE = 3; + static public final int GOLD_STATE = 4; + static public final int RED_STATE = 5; + static public final int GRAY_STATE = 6; + static public final int DARK_GREEN_STATE = 7; + static public final int DARK_YELLOW_STATE = 8; + static public final int MAGENTA3_STATE = 9; + static public final int PURPLE1_STATE = 10; + static public final int PINK1_STATE = 11; + static public final int AQUAMARINE_STATE = 12; + static public final int LIGHT_BLUE_STATE = 13; + static public final int CADET_BLUE_STATE = 14; + static public final int OLIVE_STATE = 15; + + static public final int STATES0 = 0; + static public final int STATES1 = 15; + + // selected state elements color indices + static public final int BLACK_STATE_SEL = 16; + static public final int GREEN_STATE_SEL = 17; + static public final int DARK_BLUE_STATE_SEL = 18; + static public final int ORANGE_STATE_SEL = 19; + static public final int GOLD_STATE_SEL = 20; + static public final int RED_STATE_SEL = 21; + static public final int GRAY_STATE_SEL = 22; + static public final int DARK_GREEN_STATE_SEL = 23; + static public final int DARK_YELLOW_STATE_SEL = 24; + static public final int MAGENTA3_STATE_SEL = 25; + static public final int PURPLE1_STATE_SEL = 26; + static public final int PINK1_STATE_SEL = 27; + static public final int AQUAMARINE_STATE_SEL = 28; + static public final int LIGHT_BLUE_STATE_SEL = 29; + static public final int CADET_BLUE_STATE_SEL = 30; + static public final int OLIVE_STATE_SEL = 31; + + static public final int STATES_SEL0 = 16; + static public final int STATES_SEL1 = 31; + + // colors indices for viewer controls + static public final int BACKGROUND = 32; + static public final int FOREGROUND = 33; + static public final int BACKGROUND_SEL = 34; + static public final int FOREGROUND_SEL = 35; + static public final int BACKGROUND_SEL_NOFOCUS = 36; + static public final int FOREGROUND_SEL_NOFOCUS = 37; + static public final int TOOL_BACKGROUND = 38; + static public final int TOOL_FOREGROUND = 39; + + // misc colors + static public final int FIX_COLOR = 40; + static public final int WHITE = 41; + static public final int GRAY = 42; + static public final int BLACK = 43; + static public final int DARK_GRAY = 44; + + // selected border color indices + static public final int BLACK_BORDER = 45; + static public final int GREEN_BORDER = 46; + static public final int DARK_BLUE_BORDER = 47; + static public final int ORANGE_BORDER = 48; + static public final int GOLD_BORDER = 49; + static public final int RED_BORDER = 50; + static public final int GRAY_BORDER = 51; + static public final int DARK_GREEN_BORDER1 = 52; + static public final int DARK_YELLOW_BORDER1 = 53; + static public final int MAGENTA3_BORDER1 = 54; + static public final int PURPLE1_BORDER1 = 55; + static public final int PINK1_BORDER1 = 56; + static public final int AQUAMARINE_BORDER1 = 57; + static public final int LIGHT_BLUE_BORDER1 = 58; + static public final int CADET_BLUE_STATE_BORDER = 59; + static public final int OLIVE_BORDER2 = 60; + + static public final int STATES_BORDER0 = 45; + static public final int STATES_BORDER1 = 60; + + static public final int MID_LINE = 61; + static public final int RED = 62; + static public final int GREEN = 63; + static public final int BLUE = 64; + static public final int YELLOW = 65; + static public final int CYAN = 66; + static public final int MAGENTA = 67; + + static public final int SELECTED_TIME = 68; + static public final int LEGEND_BACKGROUND = 69; + static public final int LEGEND_FOREGROUND = 70; + + // group items' colors + static public final int GR_BACKGROUND = 71; + static public final int GR_FOREGROUND = 72; + static public final int GR_BACKGROUND_SEL = 73; + static public final int GR_FOREGROUND_SEL = 74; + static public final int GR_BACKGROUND_SEL_NOFOCUS = 75; + static public final int GR_FOREGROUND_SEL_NOFOCUS = 76; + + static public final int LIGHT_LINE = 77; + static public final int BACKGROUND_NAME = 78; + static public final int BACKGROUND_NAME_SEL = 79; + static public final int BACKGROUND_NAME_SEL_NOFOCUS = 80; + + // Interraction's colors + static public final int TI_START_THREAD = BLACK; + static public final int TI_HANDOFF_LOCK = BLUE; + static public final int TI_NOTIFY_ALL = GREEN; + static public final int TI_NOTIFY = GREEN; + static public final int TI_NOTIFY_JOINED = DARK_GRAY; + static public final int TI_INTERRUPT = RED; + static public final int TI_WAIT_EXCEEDED = BLUE; + + static interface IColorProvider { + public Color get(); + } + + static class SysCol implements IColorProvider { + int syscol; + + SysCol(int syscol) { + this.syscol = syscol; + } + + @Override + public Color get() { + return Utils.getSysColor(syscol); + } + } + + static class RGB implements IColorProvider { + int r; + int g; + int b; + + RGB(int r, int g, int b) { + this.r = r; + this.g = g; + this.b = b; + } + + @Override + public Color get() { + return new Color(null, r, g, b); + } + } + + static class Mix implements IColorProvider { + IColorProvider cp1; + IColorProvider cp2; + int w1; + int w2; + + Mix(IColorProvider cp1, IColorProvider cp2, int w1, int w2) { + this.cp1 = cp1; + this.cp2 = cp2; + this.w1 = w1; + this.w2 = w2; + } + + Mix(IColorProvider cp1, IColorProvider cp2) { + this.cp1 = cp1; + this.cp2 = cp2; + this.w1 = 1; + this.w2 = 1; + } + + @Override + public Color get() { + Color col1 = cp1.get(); + Color col2 = cp2.get(); + Color col = Utils.mixColors(col1, col2, w1, w2); + return col; + } + } + + static private final IColorProvider _providersMap[] = { + // + new RGB(100, 100, 100), // UNKNOWN + new RGB(174, 200, 124), // RUNNING + new Mix(new SysCol(SWT.COLOR_BLUE), new SysCol(SWT.COLOR_GRAY), 1, 3), // SLEEPING + new RGB(210, 150, 60), // WAITING + new RGB(242, 225, 168), // BLOCKED + new Mix(new SysCol(SWT.COLOR_RED), new SysCol(SWT.COLOR_GRAY), 1, 3), // DEADLOCK + new RGB(200, 200, 200), // STOPPED + new RGB(35, 107, 42), // STEEL BLUE + new RGB(205,205,0), // DARK YELLOW + new RGB(205, 0, 205), // MAGENTA + new RGB(171, 130, 255), // PURPLE + new RGB(255, 181, 197), // PINK + new RGB(112, 219, 147), // AQUAMARINE + new RGB(198, 226, 255), // SLATEGRAY + new RGB(95, 158, 160), // CADET BLUE + new RGB(107, 142, 35), // OLIVE + + + //TODO: Does not seem to be used, check during clean-up + new SysCol(SWT.COLOR_WHITE), // UNKNOWN_SEL + new SysCol(SWT.COLOR_GREEN), // RUNNING_SEL + new SysCol(SWT.COLOR_BLUE), // SLEEPING_SEL + new SysCol(SWT.COLOR_CYAN), // WAITING_SEL + new SysCol(SWT.COLOR_YELLOW), // BLOCKED_SEL + new SysCol(SWT.COLOR_RED), // DEADLOCK_SEL + new SysCol(SWT.COLOR_DARK_GRAY), // STOPPED_SEL + new SysCol(SWT.COLOR_WHITE), + new SysCol(SWT.COLOR_GREEN), + new SysCol(SWT.COLOR_BLUE), + new SysCol(SWT.COLOR_CYAN), + new SysCol(SWT.COLOR_YELLOW), + new SysCol(SWT.COLOR_RED), + new SysCol(SWT.COLOR_DARK_GRAY), + new SysCol(SWT.COLOR_WHITE), + new SysCol(SWT.COLOR_GREEN), + + + new SysCol(SWT.COLOR_LIST_BACKGROUND), // BACKGROUND + new SysCol(SWT.COLOR_LIST_FOREGROUND), // FOREGROUND + new RGB(232, 242, 254), // BACKGROUND_SEL + new SysCol(SWT.COLOR_LIST_FOREGROUND), // FOREGROUND_SEL + new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // BACKGROUND_SEL_NOFOCUS + new SysCol(SWT.COLOR_WIDGET_FOREGROUND), // FOREGROUND_SEL_NOFOCUS + new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // TOOL_BACKGROUND + new SysCol(SWT.COLOR_WIDGET_DARK_SHADOW), // TOOL_FOREGROUND + + new SysCol(SWT.COLOR_GRAY), // FIX_COLOR + new SysCol(SWT.COLOR_WHITE), // WHITE + new SysCol(SWT.COLOR_GRAY), // GRAY + new SysCol(SWT.COLOR_BLACK), // BLACK + new SysCol(SWT.COLOR_DARK_GRAY), // DARK_GRAY + + new SysCol(SWT.COLOR_DARK_GRAY), // BLACK_BORDER + new RGB(75, 115, 120), // GREEN_BORDER + new SysCol(SWT.COLOR_DARK_BLUE), // DARK_BLUE_BORDER + new RGB(242, 225, 168), // ORANGE_BORDER + new RGB(210, 150, 60), // GOLD_BORDER + new SysCol(SWT.COLOR_DARK_RED), // RED_BORDER + new SysCol(SWT.COLOR_BLACK), // GRAY_BORDER + new SysCol(SWT.COLOR_DARK_GRAY), // DARK_GREEN_BORDER + new RGB(75, 115, 120), // DARK_YELLOW_BORDER + new SysCol(SWT.COLOR_DARK_BLUE), // MAGENTA3_BORDER + new RGB(242, 225, 168), // PURPLE1_BORDER + new RGB(210, 150, 60), // PINK1_BORDER + new SysCol(SWT.COLOR_DARK_RED), // AQUAMARINE_BORDER + new SysCol(SWT.COLOR_BLACK), // LIGHT_BLUE_BORDER + new SysCol(SWT.COLOR_DARK_GRAY), // BLUE_BORDER + new RGB(75, 115, 120), // OLIVE_BORDER + + + new SysCol(SWT.COLOR_GRAY), // MID_LINE + new SysCol(SWT.COLOR_RED), // RED + new SysCol(SWT.COLOR_GREEN), // GREEN + new SysCol(SWT.COLOR_BLUE), // BLUE + new SysCol(SWT.COLOR_YELLOW), // YELLOW + new SysCol(SWT.COLOR_CYAN), // CYAN + new SysCol(SWT.COLOR_MAGENTA), // MAGENTA + + new SysCol(SWT.COLOR_BLUE), // SELECTED_TIME + new SysCol(SWT.COLOR_WIDGET_BACKGROUND), // LEGEND_BACKGROUND + new SysCol(SWT.COLOR_WIDGET_DARK_SHADOW), // LEGEND_FOREGROUND + + new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_LIST_BACKGROUND)), // GR_BACKGROUND + new RGB(0, 0, 50), // GR_FOREGROUND + new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_WHITE), 6, 1), // GR_BACKGROUND_SEL + new RGB(0, 0, 50), // GR_FOREGROUND_SEL + new Mix(new RGB(150, 200, 240), new SysCol(SWT.COLOR_WHITE), 6, 1), // GR_BACKGROUND_SEL_NOFOCUS + new RGB(0, 0, 50), // GR_FOREGROUND_SEL_NOFOCUS + + new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_LIST_BACKGROUND), 1, 3), // LIGHT_LINE + + new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_LIST_BACKGROUND), 1, 6), // BACKGROUND_NAME + new Mix(new SysCol(SWT.COLOR_GRAY), new RGB(232, 242, 254), 1, 6), // BACKGROUND_NAME_SEL + new Mix(new SysCol(SWT.COLOR_GRAY), new SysCol(SWT.COLOR_WIDGET_BACKGROUND), 1, 6), // BACKGROUND_NAME_SEL_NOFOCUS + }; + + private final Color _colors[]; + + /** + * Default constructor + */ + public TimeGraphColorScheme() { + _colors = new Color[_providersMap.length]; + } + + /** + * Dispose this color scheme + */ + public void dispose() { + for (int i = 0; i < _colors.length; i++) { + Utils.dispose(_colors[i]); + _colors[i] = null; + } + } + + /** + * Get the color matching the given index + * + * @param idx + * The index + * @return The matching color + */ + public Color getColor(int idx) { + if (null == _colors[idx]) { + if (idx >= STATES_SEL0 && idx <= STATES_SEL1) { + Color col1 = getColor(idx - STATES_SEL0); + Color col2 = getColor(BACKGROUND_SEL); + _colors[idx] = Utils.mixColors(col1, col2, 3, 1); + } else { + _colors[idx] = _providersMap[idx].get(); + } + } + return _colors[idx]; + } + + /** + * Get an entry's background color based on its status. + * + * @param selected + * If the entry is selected + * @param focused + * If the entry is focused + * @param name + * Get the color of the name column (false for other columns) + * @return The matching color + */ + public Color getBkColor(boolean selected, boolean focused, boolean name) { + if (name) { + if (selected && focused) { + return getColor(BACKGROUND_NAME_SEL); + } + if (selected) { + return getColor(BACKGROUND_NAME_SEL_NOFOCUS); + } + return getColor(BACKGROUND_NAME); + } + if (selected && focused) { + return getColor(BACKGROUND_SEL); + } + if (selected) { + return getColor(BACKGROUND_SEL_NOFOCUS); + } + return getColor(BACKGROUND); + } + + /** + * Get the correct foreground color + * + * @param selected + * Is the entry selected + * @param focused + * Is the entry focused + * @return The matching color + */ + public Color getFgColor(boolean selected, boolean focused) { + if (selected && focused) { + return getColor(FOREGROUND_SEL); + } + if (selected) { + return getColor(FOREGROUND_SEL_NOFOCUS); + } + return getColor(FOREGROUND); + } + + /** + * Get the correct background color group + * + * @param selected + * Is the entry selected + * @param focused + * Is the entry focused + * @return The matching color + */ + public Color getBkColorGroup(boolean selected, boolean focused) { + if (selected && focused) { + return getColor(GR_BACKGROUND_SEL); + } + if (selected) { + return getColor(GR_BACKGROUND_SEL_NOFOCUS); + } + return getColor(GR_BACKGROUND); + } + + /** + * Get the correct foreground color group + * + * @param selected + * Is the entry selected + * @param focused + * Is the entry focused + * @return The matching color + */ + public Color getFgColorGroup(boolean selected, boolean focused) { + if (selected && focused) { + return getColor(GR_FOREGROUND_SEL); + } + if (selected) { + return getColor(GR_FOREGROUND_SEL_NOFOCUS); + } + return getColor(GR_FOREGROUND); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphItem.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphItem.java index 5d7bb318c3..f2a7eb515f 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphItem.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphItem.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2012 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Patrick Tasse - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; - -/** - * Item in the generic time graph view - * - * @version 1.0 - * @author Patrick Tasse - */ -@SuppressWarnings("javadoc") -public class TimeGraphItem { - public boolean _expanded; - public boolean _selected; - public boolean _hasChildren; - public int itemHeight; - public int level; - public List children; - public String _name; - public ITimeGraphEntry _trace; - - /** - * Standard constructor - * - * @param trace - * The entry matching to trace to which this item is associated - * @param name - * The name of the item - * @param level - * The tree level of this entry (0 = top level) - */ - public TimeGraphItem(ITimeGraphEntry trace, String name, int level) { - this._trace = trace; - this._name = name; - this.level = level; - this.children = new ArrayList(); - } - - @Override - public String toString() { - return _name; - } +/******************************************************************************* + * Copyright (c) 2012 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Patrick Tasse - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; + +/** + * Item in the generic time graph view + * + * @version 1.0 + * @author Patrick Tasse + */ +@SuppressWarnings("javadoc") +public class TimeGraphItem { + public boolean _expanded; + public boolean _selected; + public boolean _hasChildren; + public int itemHeight; + public int level; + public List children; + public String _name; + public ITimeGraphEntry _trace; + + /** + * Standard constructor + * + * @param trace + * The entry matching to trace to which this item is associated + * @param name + * The name of the item + * @param level + * The tree level of this entry (0 = top level) + */ + public TimeGraphItem(ITimeGraphEntry trace, String name, int level) { + this._trace = trace; + this._name = name; + this.level = level; + this.children = new ArrayList(); + } + + @Override + public String toString() { + return _name; + } } \ No newline at end of file diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphSelection.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphSelection.java index 101c33302f..072d11fbd7 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphSelection.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/TimeGraphSelection.java @@ -1,96 +1,96 @@ -/***************************************************************************** - * Copyright (c) 2007 Intel Corporation, 2009, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alvaro Sanchez-Leon - Updated for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.viewers.IStructuredSelection; - -/** - * Selection object for the time graph scale - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public class TimeGraphSelection implements IStructuredSelection { - - List list = new ArrayList(); - - /** - * Default constructor - */ - public TimeGraphSelection() { - } - - /** - * "Wrapper" constructor. Instantiate a new selection object with only one - * existing selection. - * - * @param sel - * The initial selection to add to this one - */ - public TimeGraphSelection(Object sel) { - add(sel); - } - - /** - * Add a selection to this one. - * - * @param sel - * The selection to add - */ - public void add(Object sel) { - if (null != sel && !list.contains(sel)) { - list.add(sel); - } - } - - @Override - public Object getFirstElement() { - if (!list.isEmpty()) { - return list.get(0); - } - return null; - } - - @Override - public Iterator iterator() { - return list.iterator(); - } - - @Override - public int size() { - return list.size(); - } - - @Override - public Object[] toArray() { - return list.toArray(); - } - - @Override - public List toList() { - return list; - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } -} +/***************************************************************************** + * Copyright (c) 2007 Intel Corporation, 2009, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alvaro Sanchez-Leon - Updated for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.viewers.IStructuredSelection; + +/** + * Selection object for the time graph scale + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public class TimeGraphSelection implements IStructuredSelection { + + List list = new ArrayList(); + + /** + * Default constructor + */ + public TimeGraphSelection() { + } + + /** + * "Wrapper" constructor. Instantiate a new selection object with only one + * existing selection. + * + * @param sel + * The initial selection to add to this one + */ + public TimeGraphSelection(Object sel) { + add(sel); + } + + /** + * Add a selection to this one. + * + * @param sel + * The selection to add + */ + public void add(Object sel) { + if (null != sel && !list.contains(sel)) { + list.add(sel); + } + } + + @Override + public Object getFirstElement() { + if (!list.isEmpty()) { + return list.get(0); + } + return null; + } + + @Override + public Iterator iterator() { + return list.iterator(); + } + + @Override + public int size() { + return list.size(); + } + + @Override + public Object[] toArray() { + return list.toArray(); + } + + @Override + public List toList() { + return list; + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/Utils.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/Utils.java index beb33a348b..0c81dbda21 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/Utils.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/widgets/Utils.java @@ -1,632 +1,632 @@ -/***************************************************************************** - * Copyright (c) 2007, 2008 Intel Corporation, 2009, 2012 Ericsson. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Intel Corporation - Initial API and implementation - * Ruslan A. Scherbakov, Intel - Initial API and implementation - * Alvaro Sanchez-Leon - Udpated for TMF - * Patrick Tasse - Refactoring - * - *****************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; - -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; -import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Device; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Display; - -/** - * General utilities and definitions used by the time graph widget - * - * @version 1.0 - * @author Alvaro Sanchez-Leon - * @author Patrick Tasse - */ -public class Utils { - - /** Time format for dates and timestamp */ - public enum TimeFormat { - /** Relative to the start of the trace */ - RELATIVE, - /** Absolute timestamp (ie, relative to the Unix epoch) */ - ABSOLUTE - } - - static public final int IMG_THREAD_RUNNING = 0; - static public final int IMG_THREAD_SUSPENDED = 1; - static public final int IMG_THREAD_STOPPED = 2; - static public final int IMG_METHOD_RUNNING = 3; - static public final int IMG_METHOD = 4; - static public final int IMG_NUM = 5; - - static public final Object[] _empty = new Object[0]; - - public static enum Resolution { - SECONDS, MILLISEC, MICROSEC, NANOSEC - } - - static private final SimpleDateFormat stimeformat = new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$ - static private final SimpleDateFormat sdateformat = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$ - - static Rectangle clone(Rectangle source) { - return new Rectangle(source.x, source.y, source.width, source.height); - } - - /** - * Initialize a Rectangle object to default values (all equal to 0) - * - * @param rect - * The Rectangle to initialize - */ - static public void init(Rectangle rect) { - rect.x = 0; - rect.y = 0; - rect.width = 0; - rect.height = 0; - } - - /** - * Initialize a Rectangle object with all the given values - * - * @param rect - * The Rectangle object to initialize - * @param x - * The X coordinate - * @param y - * The Y coordinate - * @param width - * The width of the rectangle - * @param height - * The height of the rectangle - */ - static public void init(Rectangle rect, int x, int y, int width, int height) { - rect.x = x; - rect.y = y; - rect.width = width; - rect.height = height; - } - - /** - * Initialize a Rectangle object to another existing Rectangle's values. - * - * @param rect - * The Rectangle to initialize - * @param source - * The reference Rectangle to copy - */ - static public void init(Rectangle rect, Rectangle source) { - rect.x = source.x; - rect.y = source.y; - rect.width = source.width; - rect.height = source.height; - } - - /** - * Reduce the size of a given rectangle by the given amounts. - * - * @param rect - * The rectangle to modify - * @param x - * The reduction in width - * @param y - * The reduction in height - */ - static public void deflate(Rectangle rect, int x, int y) { - rect.x += x; - rect.y += y; - rect.width -= x + x; - rect.height -= y + y; - } - - /** - * Increase the size of a given rectangle by the given amounts. - * - * @param rect - * The rectangle to modify - * @param x - * The augmentation in width - * @param y - * The augmentation in height - */ - static public void inflate(Rectangle rect, int x, int y) { - rect.x -= x; - rect.y -= y; - rect.width += x + x; - rect.height += y + y; - } - - static void dispose(Color col) { - if (null != col) { - col.dispose(); - } - } - - /** - * Get the resulting color from a mix of two existing ones for a given - * display. - * - * @param display - * The display device (which might affect the color conversion) - * @param c1 - * The first color - * @param c2 - * The second color - * @param w1 - * The gamma level for color 1 - * @param w2 - * The gamma level for color 2 - * @return The resulting color - */ - static public Color mixColors(Device display, Color c1, Color c2, int w1, - int w2) { - return new Color(display, (w1 * c1.getRed() + w2 * c2.getRed()) - / (w1 + w2), (w1 * c1.getGreen() + w2 * c2.getGreen()) - / (w1 + w2), (w1 * c1.getBlue() + w2 * c2.getBlue()) - / (w1 + w2)); - } - - /** - * Get the system color with the given ID. - * - * @param id - * The color ID - * @return The resulting color - */ - static public Color getSysColor(int id) { - Color col = Display.getCurrent().getSystemColor(id); - return new Color(col.getDevice(), col.getRGB()); - } - - /** - * Get the resulting color from a mix of two existing ones for the current - * display. - * - * @param col1 - * The first color - * @param col2 - * The second color - * @param w1 - * The gamma level for color 1 - * @param w2 - * The gamma level for color 2 - * @return The resulting color - */ - static public Color mixColors(Color col1, Color col2, int w1, int w2) { - return mixColors(Display.getCurrent(), col1, col2, w1, w2); - } - - /** - * Draw text in a rectangle. - * - * @param gc - * The SWT GC object - * @param text - * The text to draw - * @param rect - * The rectangle object which is being drawn - * @param transp - * Should we transpose the color - * @return The X coordinate where we have written - */ - static public int drawText(GC gc, String text, Rectangle rect, boolean transp) { - Point size = gc.stringExtent(text); - gc.drawText(text, rect.x, rect.y, transp); - return size.x; - } - - /** - * Draw text at a given location. - * - * @param gc - * The SWT GC object - * @param text - * The text to draw - * @param x - * The X coordinate of the starting point - * @param y - * the Y coordinate of the starting point - * @param transp - * Should we transpose the color - * @return The X coordinate where we have written - */ - static public int drawText(GC gc, String text, int x, int y, boolean transp) { - Point size = gc.stringExtent(text); - gc.drawText(text, x, y, transp); - return size.x; - } - - /** - * Formats time in format: MM:SS:NNN - * - * @param time time - * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn - * @param resolution the resolution - * @return the formatted time - */ - static public String formatTime(long time, TimeFormat format, Resolution resolution) { - // if format is absolute (Calendar) - if (format == TimeFormat.ABSOLUTE) { - return formatTimeAbs(time, resolution); - } - - StringBuffer str = new StringBuffer(); - boolean neg = time < 0; - if (neg) { - time = -time; - str.append('-'); - } - - long sec = (long) (time * 1E-9); - // TODO: Expand to make it possible to select the minute, second, nanosecond format - //printing minutes is suppressed just sec and ns - // if (sec / 60 < 10) - // str.append('0'); - // str.append(sec / 60); - // str.append(':'); - // sec %= 60; - // if (sec < 10) - // str.append('0'); - str.append(sec); - String ns = formatNs(time, resolution); - if (!ns.equals("")) { //$NON-NLS-1$ - str.append('.'); - str.append(ns); - } - - return str.toString(); - } - - /** - * From input time in nanoseconds, convert to Date format YYYY-MM-dd - * - * @param absTime - * The source time, in ns - * @return the formatted date - */ - public static String formatDate(long absTime) { - String sdate = sdateformat.format(new Date((long) (absTime * 1E-6))); - return sdate; - } - - /** - * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn - * - * @param time - * The source time, in ns - * @param res - * The resolution to use - * @return the formatted time - */ - static public String formatTimeAbs(long time, Resolution res) { - StringBuffer str = new StringBuffer(); - - // format time from nanoseconds to calendar time HH:MM:SS - String stime = stimeformat.format(new Date((long) (time * 1E-6))); - str.append(stime); - str.append('.'); - // append the Milliseconds, MicroSeconds and NanoSeconds as specified in - // the Resolution - str.append(formatNs(time, res)); - return str.toString(); - } - - /** - * Obtains the remainder fraction on unit Seconds of the entered value in - * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction - * seconds can be obtained by removing the last 9 digits: 1241207054 the - * fractional portion of seconds, expressed in ns is: 171080214 - * - * @param time - * The source time in ns - * @param res - * The Resolution to use - * @return the formatted nanosec - */ - public static String formatNs(long time, Resolution res) { - StringBuffer str = new StringBuffer(); - boolean neg = time < 0; - if (neg) { - time = -time; - } - - // The following approach could be used although performance - // decreases in half. - // String strVal = String.format("%09d", time); - // String tmp = strVal.substring(strVal.length() - 9); - - long ns = time; - ns %= 1000000000; - if (ns < 10) { - str.append("00000000"); //$NON-NLS-1$ - } else if (ns < 100) { - str.append("0000000"); //$NON-NLS-1$ - } else if (ns < 1000) { - str.append("000000"); //$NON-NLS-1$ - } else if (ns < 10000) { - str.append("00000"); //$NON-NLS-1$ - } else if (ns < 100000) { - str.append("0000"); //$NON-NLS-1$ - } else if (ns < 1000000) { - str.append("000"); //$NON-NLS-1$ - } else if (ns < 10000000) { - str.append("00"); //$NON-NLS-1$ - } else if (ns < 100000000) { - str.append("0"); //$NON-NLS-1$ - } - str.append(ns); - - if (res == Resolution.MILLISEC) { - return str.substring(0, 3); - } else if (res == Resolution.MICROSEC) { - return str.substring(0, 6); - } else if (res == Resolution.NANOSEC) { - return str.substring(0, 9); - } - return ""; //$NON-NLS-1$ - } - - /** - * FIXME Currently does nothing. - * - * @param opt - * The option name - * @param def - * The option value - * @param min - * The minimal accepted value - * @param max - * The maximal accepted value - * @return The value that was read - */ - static public int loadIntOption(String opt, int def, int min, int max) { - // int val = - // TraceUIPlugin.getDefault().getPreferenceStore().getInt(opt); - // if (0 == val) - // val = def; - // if (val < min) - // val = min; - // if (val > max) - // val = max; - return def; - } - - /** - * FIXME currently does nothing - * - * @param opt - * The option name - * @param val - * The option value - */ - static public void saveIntOption(String opt, int val) { - // TraceUIPlugin.getDefault().getPreferenceStore().setValue(opt, val); - } - - static ITimeEvent getFirstEvent(ITimeGraphEntry entry) { - if (null == entry || ! entry.hasTimeEvents()) { - return null; - } - Iterator iterator = entry.getTimeEventsIterator(); - if (iterator != null && iterator.hasNext()) { - return iterator.next(); - } - return null; - } - - /** - * N means:
  • -1: Previous Event
  • 0: Current Event
  • - * 1: Next Event
  • 2: Previous Event when located in a non Event Area - * - * - * @param entry - * @param time - * @param n - * @return - */ - static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { - if (null == entry || ! entry.hasTimeEvents()) { - return null; - } - Iterator iterator = entry.getTimeEventsIterator(); - if (iterator == null) { - return null; - } - ITimeEvent nextEvent = null; - ITimeEvent currEvent = null; - ITimeEvent prevEvent = null; - - while (iterator.hasNext()) { - nextEvent = iterator.next(); - long nextStartTime = nextEvent.getTime(); - - if (nextStartTime > time) { - break; - } - - if (currEvent == null || currEvent.getTime() != nextStartTime) { - prevEvent = currEvent; - currEvent = nextEvent; - } - } - - if (n == -1) { //previous - if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { - return prevEvent; - } - return currEvent; - } else if (n == 0) { //current - if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { - return currEvent; - } - return null; - } else if (n == 1) { //next - if (nextEvent != null && nextEvent.getTime() > time) { - return nextEvent; - } - return null; - } else if (n == 2) { //current or previous when in empty space - return currEvent; - } - - return null; - } - - /** - * Pretty-print a method signature. - * - * @param sig - * The original signature - * @return The pretty signature - */ - static public String fixMethodSignature(String sig) { - int pos = sig.indexOf('('); - if (pos >= 0) { - String ret = sig.substring(0, pos); - sig = sig.substring(pos); - sig = sig + " " + ret; //$NON-NLS-1$ - } - return sig; - } - - /** - * Restore an original method signature from a pretty-printed one. - * - * @param sig - * The pretty-printed signature - * @return The original method signature - */ - static public String restoreMethodSignature(String sig) { - String ret = ""; //$NON-NLS-1$ - int pos = sig.indexOf('('); - if (pos >= 0) { - ret = sig.substring(0, pos); - sig = sig.substring(pos + 1); - } - pos = sig.indexOf(')'); - if (pos >= 0) { - sig = sig.substring(0, pos); - } - String args[] = sig.split(","); //$NON-NLS-1$ - StringBuffer result = new StringBuffer("("); //$NON-NLS-1$ - for (int i = 0; i < args.length; i++) { - String arg = args[i].trim(); - if (arg.length() == 0 && args.length == 1) { - break; - } - result.append(getTypeSignature(arg)); - } - result.append(")").append(getTypeSignature(ret)); //$NON-NLS-1$ - return result.toString(); - } - - /** - * Get the mangled type information from an array of types. - * - * @param type - * The types to convert. See method implementation for what it - * expects. - * @return The mangled string of types - */ - @SuppressWarnings("nls") - static public String getTypeSignature(String type) { - int dim = 0; - for (int j = 0; j < type.length(); j++) { - if (type.charAt(j) == '[') { - dim++; - } - } - int pos = type.indexOf('['); - if (pos >= 0) { - type = type.substring(0, pos); - } - StringBuffer sig = new StringBuffer(""); //$NON-NLS-1$ - for (int j = 0; j < dim; j++) - { - sig.append("["); //$NON-NLS-1$ - } - if (type.equals("boolean")) { //$NON-NLS-1$ - sig.append('Z'); - } else if (type.equals("byte")) { //$NON-NLS-1$ - sig.append('B'); - } else if (type.equals("char")) { //$NON-NLS-1$ - sig.append('C'); - } else if (type.equals("short")) { //$NON-NLS-1$ - sig.append('S'); - } else if (type.equals("int")) { //$NON-NLS-1$ - sig.append('I'); - } else if (type.equals("long")) { //$NON-NLS-1$ - sig.append('J'); - } else if (type.equals("float")) { //$NON-NLS-1$ - sig.append('F'); - } else if (type.equals("double")) { //$NON-NLS-1$ - sig.append('D'); - } else if (type.equals("void")) { //$NON-NLS-1$ - sig.append('V'); - } - else { - sig.append('L').append(type.replace('.', '/')).append(';'); - } - return sig.toString(); - } - - /** - * Compare two doubles together. - * - * @param d1 - * First double - * @param d2 - * Second double - * @return 1 if they are different, and 0 if they are *exactly* the same. - * Because of the way doubles are stored, it's possible for the - * same number obtained in two different ways to actually look - * different. - */ - static public int compare(double d1, double d2) { - if (d1 > d2) { - return 1; - } - if (d1 < d2) { - return 1; - } - return 0; - } - - /** - * Compare two character strings alphabetically. This is simply a wrapper - * around String.compareToIgnoreCase but that will handle cases where - * strings can be null - * - * @param s1 - * The first string - * @param s2 - * The second string - * @return A number below, equal, or greater than zero if the first string - * is smaller, equal, or bigger (alphabetically) than the second - * one. - */ - static public int compare(String s1, String s2) { - if (s1 != null && s2 != null) { - return s1.compareToIgnoreCase(s2); - } - if (s1 != null) { - return 1; - } - if (s2 != null) { - return -1; - } - return 0; - } -} +/***************************************************************************** + * Copyright (c) 2007, 2008 Intel Corporation, 2009, 2012 Ericsson. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Intel Corporation - Initial API and implementation + * Ruslan A. Scherbakov, Intel - Initial API and implementation + * Alvaro Sanchez-Leon - Udpated for TMF + * Patrick Tasse - Refactoring + * + *****************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.timegraph.widgets; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Iterator; + +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeEvent; +import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Device; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Display; + +/** + * General utilities and definitions used by the time graph widget + * + * @version 1.0 + * @author Alvaro Sanchez-Leon + * @author Patrick Tasse + */ +public class Utils { + + /** Time format for dates and timestamp */ + public enum TimeFormat { + /** Relative to the start of the trace */ + RELATIVE, + /** Absolute timestamp (ie, relative to the Unix epoch) */ + ABSOLUTE + } + + static public final int IMG_THREAD_RUNNING = 0; + static public final int IMG_THREAD_SUSPENDED = 1; + static public final int IMG_THREAD_STOPPED = 2; + static public final int IMG_METHOD_RUNNING = 3; + static public final int IMG_METHOD = 4; + static public final int IMG_NUM = 5; + + static public final Object[] _empty = new Object[0]; + + public static enum Resolution { + SECONDS, MILLISEC, MICROSEC, NANOSEC + } + + static private final SimpleDateFormat stimeformat = new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$ + static private final SimpleDateFormat sdateformat = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$ + + static Rectangle clone(Rectangle source) { + return new Rectangle(source.x, source.y, source.width, source.height); + } + + /** + * Initialize a Rectangle object to default values (all equal to 0) + * + * @param rect + * The Rectangle to initialize + */ + static public void init(Rectangle rect) { + rect.x = 0; + rect.y = 0; + rect.width = 0; + rect.height = 0; + } + + /** + * Initialize a Rectangle object with all the given values + * + * @param rect + * The Rectangle object to initialize + * @param x + * The X coordinate + * @param y + * The Y coordinate + * @param width + * The width of the rectangle + * @param height + * The height of the rectangle + */ + static public void init(Rectangle rect, int x, int y, int width, int height) { + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + } + + /** + * Initialize a Rectangle object to another existing Rectangle's values. + * + * @param rect + * The Rectangle to initialize + * @param source + * The reference Rectangle to copy + */ + static public void init(Rectangle rect, Rectangle source) { + rect.x = source.x; + rect.y = source.y; + rect.width = source.width; + rect.height = source.height; + } + + /** + * Reduce the size of a given rectangle by the given amounts. + * + * @param rect + * The rectangle to modify + * @param x + * The reduction in width + * @param y + * The reduction in height + */ + static public void deflate(Rectangle rect, int x, int y) { + rect.x += x; + rect.y += y; + rect.width -= x + x; + rect.height -= y + y; + } + + /** + * Increase the size of a given rectangle by the given amounts. + * + * @param rect + * The rectangle to modify + * @param x + * The augmentation in width + * @param y + * The augmentation in height + */ + static public void inflate(Rectangle rect, int x, int y) { + rect.x -= x; + rect.y -= y; + rect.width += x + x; + rect.height += y + y; + } + + static void dispose(Color col) { + if (null != col) { + col.dispose(); + } + } + + /** + * Get the resulting color from a mix of two existing ones for a given + * display. + * + * @param display + * The display device (which might affect the color conversion) + * @param c1 + * The first color + * @param c2 + * The second color + * @param w1 + * The gamma level for color 1 + * @param w2 + * The gamma level for color 2 + * @return The resulting color + */ + static public Color mixColors(Device display, Color c1, Color c2, int w1, + int w2) { + return new Color(display, (w1 * c1.getRed() + w2 * c2.getRed()) + / (w1 + w2), (w1 * c1.getGreen() + w2 * c2.getGreen()) + / (w1 + w2), (w1 * c1.getBlue() + w2 * c2.getBlue()) + / (w1 + w2)); + } + + /** + * Get the system color with the given ID. + * + * @param id + * The color ID + * @return The resulting color + */ + static public Color getSysColor(int id) { + Color col = Display.getCurrent().getSystemColor(id); + return new Color(col.getDevice(), col.getRGB()); + } + + /** + * Get the resulting color from a mix of two existing ones for the current + * display. + * + * @param col1 + * The first color + * @param col2 + * The second color + * @param w1 + * The gamma level for color 1 + * @param w2 + * The gamma level for color 2 + * @return The resulting color + */ + static public Color mixColors(Color col1, Color col2, int w1, int w2) { + return mixColors(Display.getCurrent(), col1, col2, w1, w2); + } + + /** + * Draw text in a rectangle. + * + * @param gc + * The SWT GC object + * @param text + * The text to draw + * @param rect + * The rectangle object which is being drawn + * @param transp + * Should we transpose the color + * @return The X coordinate where we have written + */ + static public int drawText(GC gc, String text, Rectangle rect, boolean transp) { + Point size = gc.stringExtent(text); + gc.drawText(text, rect.x, rect.y, transp); + return size.x; + } + + /** + * Draw text at a given location. + * + * @param gc + * The SWT GC object + * @param text + * The text to draw + * @param x + * The X coordinate of the starting point + * @param y + * the Y coordinate of the starting point + * @param transp + * Should we transpose the color + * @return The X coordinate where we have written + */ + static public int drawText(GC gc, String text, int x, int y, boolean transp) { + Point size = gc.stringExtent(text); + gc.drawText(text, x, y, transp); + return size.x; + } + + /** + * Formats time in format: MM:SS:NNN + * + * @param time time + * @param format 0: MMMM:ss:nnnnnnnnn, 1: HH:MM:ss MMM.mmmm.nnn + * @param resolution the resolution + * @return the formatted time + */ + static public String formatTime(long time, TimeFormat format, Resolution resolution) { + // if format is absolute (Calendar) + if (format == TimeFormat.ABSOLUTE) { + return formatTimeAbs(time, resolution); + } + + StringBuffer str = new StringBuffer(); + boolean neg = time < 0; + if (neg) { + time = -time; + str.append('-'); + } + + long sec = (long) (time * 1E-9); + // TODO: Expand to make it possible to select the minute, second, nanosecond format + //printing minutes is suppressed just sec and ns + // if (sec / 60 < 10) + // str.append('0'); + // str.append(sec / 60); + // str.append(':'); + // sec %= 60; + // if (sec < 10) + // str.append('0'); + str.append(sec); + String ns = formatNs(time, resolution); + if (!ns.equals("")) { //$NON-NLS-1$ + str.append('.'); + str.append(ns); + } + + return str.toString(); + } + + /** + * From input time in nanoseconds, convert to Date format YYYY-MM-dd + * + * @param absTime + * The source time, in ns + * @return the formatted date + */ + public static String formatDate(long absTime) { + String sdate = sdateformat.format(new Date((long) (absTime * 1E-6))); + return sdate; + } + + /** + * Formats time in ns to Calendar format: HH:MM:SS MMM.mmm.nnn + * + * @param time + * The source time, in ns + * @param res + * The resolution to use + * @return the formatted time + */ + static public String formatTimeAbs(long time, Resolution res) { + StringBuffer str = new StringBuffer(); + + // format time from nanoseconds to calendar time HH:MM:SS + String stime = stimeformat.format(new Date((long) (time * 1E-6))); + str.append(stime); + str.append('.'); + // append the Milliseconds, MicroSeconds and NanoSeconds as specified in + // the Resolution + str.append(formatNs(time, res)); + return str.toString(); + } + + /** + * Obtains the remainder fraction on unit Seconds of the entered value in + * nanoseconds. e.g. input: 1241207054171080214 ns The number of fraction + * seconds can be obtained by removing the last 9 digits: 1241207054 the + * fractional portion of seconds, expressed in ns is: 171080214 + * + * @param time + * The source time in ns + * @param res + * The Resolution to use + * @return the formatted nanosec + */ + public static String formatNs(long time, Resolution res) { + StringBuffer str = new StringBuffer(); + boolean neg = time < 0; + if (neg) { + time = -time; + } + + // The following approach could be used although performance + // decreases in half. + // String strVal = String.format("%09d", time); + // String tmp = strVal.substring(strVal.length() - 9); + + long ns = time; + ns %= 1000000000; + if (ns < 10) { + str.append("00000000"); //$NON-NLS-1$ + } else if (ns < 100) { + str.append("0000000"); //$NON-NLS-1$ + } else if (ns < 1000) { + str.append("000000"); //$NON-NLS-1$ + } else if (ns < 10000) { + str.append("00000"); //$NON-NLS-1$ + } else if (ns < 100000) { + str.append("0000"); //$NON-NLS-1$ + } else if (ns < 1000000) { + str.append("000"); //$NON-NLS-1$ + } else if (ns < 10000000) { + str.append("00"); //$NON-NLS-1$ + } else if (ns < 100000000) { + str.append("0"); //$NON-NLS-1$ + } + str.append(ns); + + if (res == Resolution.MILLISEC) { + return str.substring(0, 3); + } else if (res == Resolution.MICROSEC) { + return str.substring(0, 6); + } else if (res == Resolution.NANOSEC) { + return str.substring(0, 9); + } + return ""; //$NON-NLS-1$ + } + + /** + * FIXME Currently does nothing. + * + * @param opt + * The option name + * @param def + * The option value + * @param min + * The minimal accepted value + * @param max + * The maximal accepted value + * @return The value that was read + */ + static public int loadIntOption(String opt, int def, int min, int max) { + // int val = + // TraceUIPlugin.getDefault().getPreferenceStore().getInt(opt); + // if (0 == val) + // val = def; + // if (val < min) + // val = min; + // if (val > max) + // val = max; + return def; + } + + /** + * FIXME currently does nothing + * + * @param opt + * The option name + * @param val + * The option value + */ + static public void saveIntOption(String opt, int val) { + // TraceUIPlugin.getDefault().getPreferenceStore().setValue(opt, val); + } + + static ITimeEvent getFirstEvent(ITimeGraphEntry entry) { + if (null == entry || ! entry.hasTimeEvents()) { + return null; + } + Iterator iterator = entry.getTimeEventsIterator(); + if (iterator != null && iterator.hasNext()) { + return iterator.next(); + } + return null; + } + + /** + * N means:
  • -1: Previous Event
  • 0: Current Event
  • + * 1: Next Event
  • 2: Previous Event when located in a non Event Area + * + * + * @param entry + * @param time + * @param n + * @return + */ + static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { + if (null == entry || ! entry.hasTimeEvents()) { + return null; + } + Iterator iterator = entry.getTimeEventsIterator(); + if (iterator == null) { + return null; + } + ITimeEvent nextEvent = null; + ITimeEvent currEvent = null; + ITimeEvent prevEvent = null; + + while (iterator.hasNext()) { + nextEvent = iterator.next(); + long nextStartTime = nextEvent.getTime(); + + if (nextStartTime > time) { + break; + } + + if (currEvent == null || currEvent.getTime() != nextStartTime) { + prevEvent = currEvent; + currEvent = nextEvent; + } + } + + if (n == -1) { //previous + if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { + return prevEvent; + } + return currEvent; + } else if (n == 0) { //current + if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { + return currEvent; + } + return null; + } else if (n == 1) { //next + if (nextEvent != null && nextEvent.getTime() > time) { + return nextEvent; + } + return null; + } else if (n == 2) { //current or previous when in empty space + return currEvent; + } + + return null; + } + + /** + * Pretty-print a method signature. + * + * @param sig + * The original signature + * @return The pretty signature + */ + static public String fixMethodSignature(String sig) { + int pos = sig.indexOf('('); + if (pos >= 0) { + String ret = sig.substring(0, pos); + sig = sig.substring(pos); + sig = sig + " " + ret; //$NON-NLS-1$ + } + return sig; + } + + /** + * Restore an original method signature from a pretty-printed one. + * + * @param sig + * The pretty-printed signature + * @return The original method signature + */ + static public String restoreMethodSignature(String sig) { + String ret = ""; //$NON-NLS-1$ + int pos = sig.indexOf('('); + if (pos >= 0) { + ret = sig.substring(0, pos); + sig = sig.substring(pos + 1); + } + pos = sig.indexOf(')'); + if (pos >= 0) { + sig = sig.substring(0, pos); + } + String args[] = sig.split(","); //$NON-NLS-1$ + StringBuffer result = new StringBuffer("("); //$NON-NLS-1$ + for (int i = 0; i < args.length; i++) { + String arg = args[i].trim(); + if (arg.length() == 0 && args.length == 1) { + break; + } + result.append(getTypeSignature(arg)); + } + result.append(")").append(getTypeSignature(ret)); //$NON-NLS-1$ + return result.toString(); + } + + /** + * Get the mangled type information from an array of types. + * + * @param type + * The types to convert. See method implementation for what it + * expects. + * @return The mangled string of types + */ + @SuppressWarnings("nls") + static public String getTypeSignature(String type) { + int dim = 0; + for (int j = 0; j < type.length(); j++) { + if (type.charAt(j) == '[') { + dim++; + } + } + int pos = type.indexOf('['); + if (pos >= 0) { + type = type.substring(0, pos); + } + StringBuffer sig = new StringBuffer(""); //$NON-NLS-1$ + for (int j = 0; j < dim; j++) + { + sig.append("["); //$NON-NLS-1$ + } + if (type.equals("boolean")) { //$NON-NLS-1$ + sig.append('Z'); + } else if (type.equals("byte")) { //$NON-NLS-1$ + sig.append('B'); + } else if (type.equals("char")) { //$NON-NLS-1$ + sig.append('C'); + } else if (type.equals("short")) { //$NON-NLS-1$ + sig.append('S'); + } else if (type.equals("int")) { //$NON-NLS-1$ + sig.append('I'); + } else if (type.equals("long")) { //$NON-NLS-1$ + sig.append('J'); + } else if (type.equals("float")) { //$NON-NLS-1$ + sig.append('F'); + } else if (type.equals("double")) { //$NON-NLS-1$ + sig.append('D'); + } else if (type.equals("void")) { //$NON-NLS-1$ + sig.append('V'); + } + else { + sig.append('L').append(type.replace('.', '/')).append(';'); + } + return sig.toString(); + } + + /** + * Compare two doubles together. + * + * @param d1 + * First double + * @param d2 + * Second double + * @return 1 if they are different, and 0 if they are *exactly* the same. + * Because of the way doubles are stored, it's possible for the + * same number obtained in two different ways to actually look + * different. + */ + static public int compare(double d1, double d2) { + if (d1 > d2) { + return 1; + } + if (d1 < d2) { + return 1; + } + return 0; + } + + /** + * Compare two character strings alphabetically. This is simply a wrapper + * around String.compareToIgnoreCase but that will handle cases where + * strings can be null + * + * @param s1 + * The first string + * @param s2 + * The second string + * @return A number below, equal, or greater than zero if the first string + * is smaller, equal, or bigger (alphabetically) than the second + * one. + */ + static public int compare(String s1, String s2) { + if (s1 != null && s2 != null) { + return s1.compareToIgnoreCase(s2); + } + if (s1 != null) { + return 1; + } + if (s2 != null) { + return -1; + } + return 0; + } +} diff --git a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/ColumnData.java b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/ColumnData.java index 67278e658d..15baedd82b 100644 --- a/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/ColumnData.java +++ b/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/ColumnData.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2010 Ericsson - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v1.0 which - * accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Matthew Khouzam - Extracted from TmfEventsView - ******************************************************************************/ - -package org.eclipse.linuxtools.tmf.ui.widgets.virtualtable; -/** - * ColumnData - * @author Matthew Khouzam - * @version 1.0 - * - */ -public class ColumnData { - /** - * The title of the column - */ - public final String header; - /** - * the width of the column in pixels - */ - public final int width; - /** - * the alignment of the column - */ - public final int alignment; - - /** - * Constructor - * @param h header (title) - * @param w width - * @param a alignment - */ - public ColumnData(String h, int w, int a) { - header = h; - width = w; - alignment = a; - } - -} +/******************************************************************************* + * Copyright (c) 2010 Ericsson + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Matthew Khouzam - Extracted from TmfEventsView + ******************************************************************************/ + +package org.eclipse.linuxtools.tmf.ui.widgets.virtualtable; +/** + * ColumnData + * @author Matthew Khouzam + * @version 1.0 + * + */ +public class ColumnData { + /** + * The title of the column + */ + public final String header; + /** + * the width of the column in pixels + */ + public final int width; + /** + * the alignment of the column + */ + public final int alignment; + + /** + * Constructor + * @param h header (title) + * @param w width + * @param a alignment + */ + public ColumnData(String h, int w, int a) { + header = h; + width = w; + alignment = a; + } + +} -- 2.34.1