1 /*******************************************************************************
\r
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
\r
3 * in Industry THTH ry.
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.utils.ui;
\r
14 import org.eclipse.swt.widgets.Display;
\r
17 * An overridable Runnable class that can be implemented to execute the runnable
\r
18 * with a specific delay. The delay is implemented using SWT's
\r
19 * {@link Display#timerExec(int, Runnable)}.
\r
22 * The nice thing is that this class allows the user to schedule runs repeatedly
\r
23 * but guarantees that the runnable is still only ran once.
\r
26 * <p>Use as follows:
\r
28 * DelayRunnable runnable = new DelayRunnable(display, delay) {
\r
29 * public void perform() {
\r
30 * // Do the things you want...
\r
34 * After this you can do multiple schedulings of the runnable as follows,
\r
35 * but the Runnable will only get ran once after the specified delay.
\r
37 * runnable.scheduleRefresh();
\r
41 * @author Tuukka Lehtonen
\r
43 public abstract class DelayRunnable implements Runnable {
\r
45 /** Default delay: 500 ms */
\r
46 private static final int DEFAULT_REFRESH_DELAY_MS = 500;
\r
48 private int refreshDelay;
\r
50 private volatile boolean scheduled = false;
\r
52 private Display display;
\r
54 public DelayRunnable(Display display) {
\r
55 this(display, DEFAULT_REFRESH_DELAY_MS);
\r
58 public DelayRunnable(Display display, int refreshDelay) {
\r
59 this.display = display;
\r
60 this.refreshDelay = refreshDelay;
\r
63 protected void release() {
\r
67 public boolean isScheduled() {
\r
71 public void scheduleRefresh() {
\r
72 synchronized (this) {
\r
77 display.asyncExec(timerSync);
\r
81 * The default implementation of run calls release first in order to allow
\r
82 * more schedulings of this Runnable to happen. After releasing the runnable
\r
83 * {@link #perform()} is called.
\r
86 * If you need to override the release-behaviour of this DelayRunnable, you
\r
87 * need to override this method instead of {@link #perform()}.
\r
96 * The method to override for performing your own actions when this runnable
\r
97 * gets ran. The default implementation is empty.
\r
99 public void perform() {
\r
103 * This exists because timerExec can only be ran from the SWT thread or the
\r
104 * thread that created the tree.
\r
106 private Runnable timerSync = new Runnable() {
\r
107 public void run() {
\r
108 display.timerExec(refreshDelay, DelayRunnable.this);
\r