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();
54 text
= new Text(parent
, style
);
55 text
.addModifyListener(modifyListener
);
58 protected void notifyText(String txt
) {
59 // text.getDisplay().syncExec(()-> pushSession.start());
60 for (Consumer
<String
> toDo
: toDos
) {
61 text
.getDisplay().syncExec(() -> toDo
.accept(txt
));
63 // text.getDisplay().syncExec(()->pushSession.stop());
66 public Text
getText() {
70 public void addListener(Consumer
<String
> toDo
) {
74 private class InternalModifyListener
implements ModifyListener
{
75 private static final long serialVersionUID
= -6178431173400385005L;
77 public void modifyText(ModifyEvent e
) {
78 String txt
= text
.getText();
79 ScheduledFuture
<String
> task
= scheduler
.schedule(() -> {
82 }, delay
, TimeUnit
.MILLISECONDS
);
83 // cancel previous task
84 if (lastTask
!= null && !lastTask
.isDone()) {
85 lastTask
.cancel(false);