1 package org
.argeo
.app
.ui
.widgets
;
3 import java
.util
.ArrayList
;
5 import java
.util
.concurrent
.Executors
;
6 import java
.util
.concurrent
.ScheduledExecutorService
;
7 import java
.util
.concurrent
.ScheduledFuture
;
8 import java
.util
.concurrent
.TimeUnit
;
9 import java
.util
.function
.Consumer
;
11 import org
.eclipse
.rap
.rwt
.service
.ServerPushSession
;
12 import org
.eclipse
.swt
.events
.ModifyEvent
;
13 import org
.eclipse
.swt
.events
.ModifyListener
;
14 import org
.eclipse
.swt
.widgets
.Composite
;
15 import org
.eclipse
.swt
.widgets
.Text
;
18 * A text input which notifies changes after a delay, typically in order to
21 public class DelayedText
{
22 private final static ScheduledExecutorService scheduler
;
24 // create only one scheduler, in order not to exhaust threads
25 scheduler
= Executors
.newScheduledThreadPool(0, (r
) -> {
26 Thread thread
= new Thread(r
, "Delayed text scheduler");
27 // we mark threads as deamons so that the shutdown hook is triggered
28 thread
.setDaemon(true);
31 Runtime
.getRuntime().addShutdownHook(new Thread(() -> {
33 }, "Shutdown delayed text scheduler"));
35 private final static int DEFAULT_DELAY
= 800;
37 private final long delay
;
38 private final InternalModifyListener modifyListener
;
39 private final Text text
;
40 protected List
<Consumer
<String
>> toDos
= new ArrayList
<>();
41 private ServerPushSession pushSession
;
43 private ScheduledFuture
<String
> lastTask
;
45 public DelayedText(Composite parent
, int style
) {
46 this(parent
, style
, DEFAULT_DELAY
);
49 public DelayedText(Composite parent
, int style
, long delayInMs
) {
50 this.delay
= delayInMs
;
51 this.modifyListener
= new InternalModifyListener();
52 pushSession
= new ServerPushSession();
53 text
= new Text(parent
, style
);
55 text
.addDisposeListener((e
) -> pushSession
.stop());
56 text
.addModifyListener(modifyListener
);
59 protected void notifyText(String txt
) {
60 // text.getDisplay().syncExec(()-> pushSession.start());
61 for (Consumer
<String
> toDo
: toDos
) {
62 text
.getDisplay().syncExec(() -> toDo
.accept(txt
));
64 // text.getDisplay().syncExec(()->pushSession.stop());
67 public Text
getText() {
71 public void addListener(Consumer
<String
> toDo
) {
75 private class InternalModifyListener
implements ModifyListener
{
76 private static final long serialVersionUID
= -6178431173400385005L;
78 public void modifyText(ModifyEvent e
) {
79 String txt
= text
.getText();
80 ScheduledFuture
<String
> task
= scheduler
.schedule(() -> {
83 }, delay
, TimeUnit
.MILLISECONDS
);
84 // cancel previous task
85 if (lastTask
!= null && !lastTask
.isDone()) {
86 lastTask
.cancel(false);