Skip to content

Commit 0de59c2

Browse files
committed
Add watcher on sketch files
Reloads sketch content if the Editor is not in foreground and isomething happens in the backing storage files. Note that no confirmation dialog is displayed (same behaviour as SublimeText, differs from other IDEs) Fixes #4551 and #5345
1 parent e7d290b commit 0de59c2

File tree

3 files changed

+256
-4
lines changed

3 files changed

+256
-4
lines changed

app/src/processing/app/Editor.java

+44-3
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,15 @@
110110
import processing.app.tools.MenuScroller;
111111
import processing.app.tools.Tool;
112112

113+
import processing.app.tools.WatchDir;
114+
import static java.nio.file.StandardWatchEventKinds.*;
115+
import java.nio.file.WatchService;
116+
import java.nio.file.WatchKey;
117+
import java.nio.file.WatchEvent;
118+
import java.nio.file.FileSystems;
119+
import java.nio.file.Path;
120+
import java.io.File;
121+
113122
/**
114123
* Main editor panel for the Processing Development Environment.
115124
*/
@@ -124,6 +133,7 @@ public class Editor extends JFrame implements RunnerListener {
124133
private final Box upper;
125134
private ArrayList<EditorTab> tabs = new ArrayList<>();
126135
private int currentTabIndex = -1;
136+
private static boolean watcherDisable = false;
127137

128138
private static class ShouldSaveIfModified
129139
implements Predicate<SketchController> {
@@ -238,6 +248,8 @@ public boolean test(SketchController controller) {
238248
private Runnable timeoutUploadHandler;
239249

240250
private Map<String, Tool> internalToolCache = new HashMap<String, Tool>();
251+
protected Thread watcher = null;
252+
protected Runnable task = null;
241253

242254
public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception {
243255
super("Arduino");
@@ -263,12 +275,20 @@ public void windowClosing(WindowEvent e) {
263275
// When bringing a window to front, let the Base know
264276
addWindowListener(new WindowAdapter() {
265277
public void windowActivated(WindowEvent e) {
278+
if (watcher != null) {
279+
watcher.interrupt();
280+
watcher = null;
281+
}
266282
base.handleActivated(Editor.this);
267283
}
268284

269285
// added for 1.0.5
270286
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
271287
public void windowDeactivated(WindowEvent e) {
288+
if (watcher == null) {
289+
watcher = new Thread(task);
290+
watcher.start();
291+
}
272292
List<Component> toolsMenuItemsToRemove = new LinkedList<>();
273293
for (Component menuItem : toolsMenu.getMenuComponents()) {
274294
if (menuItem instanceof JComponent) {
@@ -383,7 +403,6 @@ public void windowDeactivated(WindowEvent e) {
383403
EditorConsole.setCurrentEditorConsole(console);
384404
}
385405

386-
387406
/**
388407
* Handles files dragged & dropped from the desktop and into the editor
389408
* window. Dragging files into the editor window is the same as using
@@ -1562,7 +1581,7 @@ public void reorderTabs() {
15621581
* the given file.
15631582
* @throws IOException
15641583
*/
1565-
protected void addTab(SketchFile file, String contents) throws IOException {
1584+
public synchronized void addTab(SketchFile file, String contents) throws IOException {
15661585
EditorTab tab = new EditorTab(this, file, contents);
15671586
tab.getTextArea().getDocument()
15681587
.addDocumentListener(new DocumentTextChangeListener(
@@ -1571,9 +1590,12 @@ protected void addTab(SketchFile file, String contents) throws IOException {
15711590
reorderTabs();
15721591
}
15731592

1574-
protected void removeTab(SketchFile file) throws IOException {
1593+
public synchronized void removeTab(SketchFile file) throws IOException {
15751594
int index = findTabIndex(file);
15761595
tabs.remove(index);
1596+
if (index == currentTabIndex) {
1597+
currentTabIndex = currentTabIndex -1;
1598+
}
15771599
}
15781600

15791601
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
@@ -1849,6 +1871,25 @@ protected boolean handleOpenInternal(File sketchFile) {
18491871
// Disable untitled setting from previous document, if any
18501872
untitled = false;
18511873

1874+
if (watcherDisable == true) {
1875+
return true;
1876+
}
1877+
1878+
// Add FS watcher for current Editor instance
1879+
Path dir = file.toPath().getParent();
1880+
1881+
Editor instance = this;
1882+
1883+
task = new Runnable() {
1884+
public void run() {
1885+
try {
1886+
new WatchDir(dir, true).processEvents(instance);
1887+
} catch (IOException x) {
1888+
watcherDisable = true;
1889+
}
1890+
}
1891+
};
1892+
18521893
// opening was successful
18531894
return true;
18541895
}

app/src/processing/app/EditorTab.java

+14-1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@
4949
import javax.swing.text.DefaultCaret;
5050
import javax.swing.text.Document;
5151

52+
import static java.nio.file.StandardWatchEventKinds.*;
53+
import java.nio.file.WatchService;
54+
import java.nio.file.WatchKey;
55+
import java.nio.file.WatchEvent;
56+
import java.nio.file.FileSystems;
57+
import java.nio.file.Path;
58+
import java.io.File;
59+
5260
import org.apache.commons.lang3.StringUtils;
5361
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
5462
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
@@ -63,6 +71,7 @@
6371
import processing.app.syntax.SketchTextArea;
6472
import processing.app.syntax.SketchTextAreaEditorKit;
6573
import processing.app.tools.DiscourseFormat;
74+
import processing.app.tools.WatchDir;
6675

6776
/**
6877
* Single tab, editing a single file, in the main window.
@@ -483,7 +492,11 @@ public void setSelection(int start, int stop) {
483492
public int getScrollPosition() {
484493
return scrollPane.getVerticalScrollBar().getValue();
485494
}
486-
495+
496+
public RTextScrollPane getScrollPane() {
497+
return scrollPane;
498+
}
499+
487500
public void setScrollPosition(int pos) {
488501
scrollPane.getVerticalScrollBar().setValue(pos);
489502
}
+198
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
/*
2+
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions
6+
* are met:
7+
*
8+
* - Redistributions of source code must retain the above copyright
9+
* notice, this list of conditions and the following disclaimer.
10+
*
11+
* - Redistributions in binary form must reproduce the above copyright
12+
* notice, this list of conditions and the following disclaimer in the
13+
* documentation and/or other materials provided with the distribution.
14+
*
15+
* - Neither the name of Oracle nor the names of its
16+
* contributors may be used to endorse or promote products derived
17+
* from this software without specific prior written permission.
18+
*
19+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20+
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21+
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22+
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23+
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24+
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25+
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26+
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27+
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28+
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30+
*/
31+
32+
package processing.app.tools;
33+
34+
import java.nio.file.*;
35+
import static java.nio.file.StandardWatchEventKinds.*;
36+
import static java.nio.file.LinkOption.*;
37+
import java.nio.file.attribute.*;
38+
import java.io.*;
39+
import java.util.*;
40+
import processing.app.Editor;
41+
import processing.app.EditorTab;
42+
import processing.app.Sketch;
43+
import processing.app.SketchFile;
44+
import processing.app.helpers.FileUtils;
45+
46+
/**
47+
* Example to watch a directory (or tree) for changes to files.
48+
*/
49+
50+
public class WatchDir {
51+
52+
private final WatchService watcher;
53+
private final Map<WatchKey,Path> keys;
54+
private final boolean recursive;
55+
private boolean trace = false;
56+
57+
@SuppressWarnings("unchecked")
58+
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
59+
return (WatchEvent<T>)event;
60+
}
61+
62+
/**
63+
* Register the given directory with the WatchService
64+
*/
65+
private void register(Path dir) throws IOException {
66+
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
67+
if (trace) {
68+
Path prev = keys.get(key);
69+
if (prev == null) {
70+
} else {
71+
if (!dir.equals(prev)) {
72+
}
73+
}
74+
}
75+
keys.put(key, dir);
76+
}
77+
78+
/**
79+
* Register the given directory, and all its sub-directories, with the
80+
* WatchService.
81+
*/
82+
private void registerAll(final Path start) throws IOException {
83+
// register directory and sub-directories
84+
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
85+
@Override
86+
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
87+
throws IOException
88+
{
89+
register(dir);
90+
return FileVisitResult.CONTINUE;
91+
}
92+
});
93+
}
94+
95+
/**
96+
* Creates a WatchService and registers the given directory
97+
*/
98+
public WatchDir(Path dir, boolean recursive) throws IOException {
99+
this.watcher = FileSystems.getDefault().newWatchService();
100+
this.keys = new HashMap<WatchKey,Path>();
101+
this.recursive = recursive;
102+
103+
if (recursive) {
104+
registerAll(dir);
105+
} else {
106+
register(dir);
107+
}
108+
109+
// enable trace after initial registration
110+
this.trace = true;
111+
}
112+
113+
/**
114+
* Process all events for keys queued to the watcher
115+
*/
116+
public void processEvents(Editor editor) {
117+
for (;;) {
118+
119+
// wait for key to be signalled
120+
WatchKey key;
121+
try {
122+
key = watcher.take();
123+
} catch (InterruptedException x) {
124+
return;
125+
}
126+
127+
Path dir = keys.get(key);
128+
if (dir == null) {
129+
continue;
130+
}
131+
132+
for (WatchEvent<?> event: key.pollEvents()) {
133+
WatchEvent.Kind kind = event.kind();
134+
135+
// TBD - provide example of how OVERFLOW event is handled
136+
if (kind == OVERFLOW) {
137+
continue;
138+
}
139+
140+
// Context for directory entry event is the file name of entry
141+
WatchEvent<Path> ev = cast(event);
142+
Path name = ev.context();
143+
Path child = dir.resolve(name);
144+
145+
// reload the tab content
146+
if (kind == ENTRY_CREATE) {
147+
try {
148+
String filename = name.toString();
149+
FileUtils.SplitFile split = FileUtils.splitFilename(filename);
150+
if (Sketch.EXTENSIONS.contains(split.extension.toLowerCase())) {
151+
SketchFile sketch = editor.getSketch().addFile(filename);
152+
editor.addTab(sketch, null);
153+
}
154+
} catch (Exception e) {
155+
return;
156+
}
157+
} else if (kind == ENTRY_DELETE) {
158+
try {
159+
Thread.sleep(100);
160+
int index = editor.getSketch().findFileIndex(child.toAbsolutePath().toFile());
161+
editor.removeTab(editor.getSketch().getFile(index));
162+
} catch (Exception e1) {
163+
// Totally fine, if the sleep gets interrupted it means that
164+
// the action was executed in the UI, not externally
165+
return;
166+
}
167+
}
168+
editor.getTabs().forEach(tab -> {
169+
if (!tab.isModified()) {
170+
tab.reload();
171+
}
172+
});
173+
// if directory is created, and watching recursively, then
174+
// register it and its sub-directories
175+
if (recursive && (kind == ENTRY_CREATE)) {
176+
try {
177+
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
178+
registerAll(child);
179+
}
180+
} catch (IOException x) {
181+
// ignore to keep sample readbale
182+
}
183+
}
184+
}
185+
186+
// reset key and remove from set if directory no longer accessible
187+
boolean valid = key.reset();
188+
if (!valid) {
189+
keys.remove(key);
190+
191+
// all directories are inaccessible
192+
if (keys.isEmpty()) {
193+
break;
194+
}
195+
}
196+
}
197+
}
198+
}

0 commit comments

Comments
 (0)