package com.positive.charts.widgets;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import com.positive.charts.axis.ValueAxis;
import com.positive.charts.data.Range;
import com.positive.charts.event.AxisChangeEvent;
import com.positive.charts.event.AxisChangeListener;
/**
* Instances of this scrollbar are attached to a given {@link ValueAxis} to
* track its displayed range and allow changing it.
*/
public class AxisScrollbar extends TinyScrollbar implements AxisChangeListener,
SelectionListener {
private final ValueAxis axis;
private boolean notify = true;
private long firstMoment = 0;
private long lastMoment;
private boolean autoScroll = true;
public AxisScrollbar(final Composite parent, final int style,
final ValueAxis axis) {
super(parent, style);
this.axis = axis;
axis.addChangeListener(this);
this.axisChanged(null); // Force setting the range and thumb.
this.addSelectionListener(this);
this.addDisposeListener(new DisposeListener() {
public void widgetDisposed(final DisposeEvent e) {
AxisScrollbar.this.axis
.removeChangeListener(AxisScrollbar.this);
}
});
}
public void axisChanged(final AxisChangeEvent event) {
this.notify = false;
this.setThumb((long) this.axis.getRange().getLength());
if (this.autoScroll) {
this.setSelection((long) this.axis.getRange().getLowerBound());
}
this.notify = true;
}
public boolean isAutoScrolling() {
return this.autoScroll;
}
public void scrollToSee(final long lastMoment) {
if (this.autoScroll) {
final Range range = this.axis.getRange();
if ((this.getMaximum() - this.getMinimum() > this.thumb)
|| (lastMoment > range.getUpperBound())) {
this.setLastMoment(lastMoment);
}
}
}
public void setAutoScroll(final boolean value) {
this.autoScroll = value;
}
public void setFirstMoment(final long timeStamp) {
this.firstMoment = timeStamp;
this.setMinimum(this.firstMoment);
}
public void setLastMoment(final long lastMoment) {
this.lastMoment = lastMoment;
this.setMaximum(lastMoment);
if (this.autoScroll) {
this.axis.setRange(lastMoment - this.thumb, lastMoment);
}
}
public void widgetDefaultSelected(final SelectionEvent e) {
// No-op
}
public void widgetSelected(final SelectionEvent e) {
if (!this.notify) {
return;
}
this.axis.setRange(this.selection, this.selection + this.thumb);
this.autoScroll = this.selection + this.thumb >= this.lastMoment;
}
}