Skip to content

Commit 198c856

Browse files
committedFeb 16, 2018
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 fe276cf commit 198c856

File tree

3 files changed

+256
-5
lines changed

3 files changed

+256
-5
lines changed
 

‎app/src/processing/app/Editor.java

+47-3
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import processing.app.syntax.SketchTextArea;
4545
import processing.app.tools.MenuScroller;
4646
import processing.app.tools.Tool;
47+
import processing.app.tools.WatchDir;
4748

4849
import javax.swing.*;
4950
import javax.swing.event.*;
@@ -73,12 +74,19 @@
7374
import static processing.app.Theme.scale;
7475

7576
import processing.app.helpers.FileUtils;
77+
import static java.nio.file.StandardWatchEventKinds.*;
78+
import java.nio.file.WatchService;
79+
import java.nio.file.WatchKey;
80+
import java.nio.file.WatchEvent;
81+
import java.nio.file.FileSystems;
82+
import java.nio.file.Path;
83+
import java.io.File;
7684

7785
/**
7886
* Main editor panel for the Processing Development Environment.
7987
*/
8088
@SuppressWarnings("serial")
81-
public class Editor extends JFrame implements RunnerListener {
89+
public class Editor extends JFrame implements RunnerListener, FocusListener {
8290

8391
public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000;
8492

@@ -201,6 +209,8 @@ public boolean test(SketchController sketch) {
201209
private Runnable timeoutUploadHandler;
202210

203211
private Map<String, Tool> internalToolCache = new HashMap<String, Tool>();
212+
protected Thread watcher = null;
213+
protected Runnable task = null;
204214

205215
public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception {
206216
super("Arduino");
@@ -348,6 +358,21 @@ public void windowDeactivated(WindowEvent e) {
348358
EditorConsole.setCurrentEditorConsole(console);
349359
}
350360

361+
@Override
362+
public void focusGained(FocusEvent fe){
363+
if (watcher != null) {
364+
watcher.interrupt();
365+
watcher = null;
366+
}
367+
}
368+
369+
@Override
370+
public void focusLost(FocusEvent fe){
371+
if (watcher == null) {
372+
watcher = new Thread(task);
373+
watcher.start();
374+
}
375+
}
351376

352377
/**
353378
* Handles files dragged & dropped from the desktop and into the editor
@@ -1689,7 +1714,7 @@ public void reorderTabs() {
16891714
* the given file.
16901715
* @throws IOException
16911716
*/
1692-
protected void addTab(SketchFile file, String contents) throws IOException {
1717+
public synchronized void addTab(SketchFile file, String contents) throws IOException {
16931718
EditorTab tab = new EditorTab(this, file, contents);
16941719
tab.getTextArea().getDocument()
16951720
.addDocumentListener(new DocumentTextChangeListener(
@@ -1698,7 +1723,7 @@ protected void addTab(SketchFile file, String contents) throws IOException {
16981723
reorderTabs();
16991724
}
17001725

1701-
protected void removeTab(SketchFile file) throws IOException {
1726+
public synchronized void removeTab(SketchFile file) throws IOException {
17021727
int index = findTabIndex(file);
17031728
tabs.remove(index);
17041729
}
@@ -1967,6 +1992,25 @@ protected boolean handleOpenInternal(File sketchFile) {
19671992
// Disable untitled setting from previous document, if any
19681993
untitled = false;
19691994

1995+
// Add FS watcher for current Editor instance
1996+
Path dir = file.toPath().getParent();
1997+
1998+
Editor instance = this;
1999+
2000+
task = new Runnable() {
2001+
public void run() {
2002+
try {
2003+
new WatchDir(dir, true).processEvents(instance);
2004+
} catch (IOException x) {
2005+
System.err.println(x);
2006+
}
2007+
}
2008+
};
2009+
2010+
addFocusListener(this);
2011+
getTabs().forEach(tab -> tab.getScrollPane().addFocusListener(this));
2012+
getTabs().forEach(tab -> tab.getTextArea().addFocusListener(this));
2013+
19702014
// opening was successful
19712015
return true;
19722016
}

‎app/src/processing/app/EditorTab.java

+15-2
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@
5050
import javax.swing.text.DefaultCaret;
5151
import javax.swing.text.Document;
5252

53+
import static java.nio.file.StandardWatchEventKinds.*;
54+
import java.nio.file.WatchService;
55+
import java.nio.file.WatchKey;
56+
import java.nio.file.WatchEvent;
57+
import java.nio.file.FileSystems;
58+
import java.nio.file.Path;
59+
import java.io.File;
60+
5361
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
5462
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
5563
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
@@ -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.
@@ -109,7 +118,7 @@ public EditorTab(Editor editor, SketchFile file, String contents)
109118
file.setStorage(this);
110119
applyPreferences();
111120
add(scrollPane, BorderLayout.CENTER);
112-
textarea.addMouseWheelListener(this);
121+
textarea.addMouseWheelListener(this);
113122
}
114123

115124
private RSyntaxDocument createDocument(String contents) {
@@ -472,7 +481,11 @@ public void setSelection(int start, int stop) {
472481
public int getScrollPosition() {
473482
return scrollPane.getVerticalScrollBar().getValue();
474483
}
475-
484+
485+
public RTextScrollPane getScrollPane() {
486+
return scrollPane;
487+
}
488+
476489
public void setScrollPosition(int pos) {
477490
scrollPane.getVerticalScrollBar().setValue(pos);
478491
}
+194
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
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 (IOException e) {}
155+
} else if (kind == ENTRY_DELETE) {
156+
List<EditorTab> tabs = editor.getTabs();
157+
Iterator<EditorTab> iter = tabs.iterator();
158+
while (iter.hasNext()) {
159+
EditorTab tab = iter.next();
160+
if (name.getFileName().toString().equals(tab.getSketchFile().getFileName())) {
161+
try {
162+
editor.removeTab(tab.getSketchFile());
163+
} catch (IOException e) {}
164+
}
165+
}
166+
}
167+
editor.getTabs().forEach(tab -> tab.reload());
168+
169+
// if directory is created, and watching recursively, then
170+
// register it and its sub-directories
171+
if (recursive && (kind == ENTRY_CREATE)) {
172+
try {
173+
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
174+
registerAll(child);
175+
}
176+
} catch (IOException x) {
177+
// ignore to keep sample readbale
178+
}
179+
}
180+
}
181+
182+
// reset key and remove from set if directory no longer accessible
183+
boolean valid = key.reset();
184+
if (!valid) {
185+
keys.remove(key);
186+
187+
// all directories are inaccessible
188+
if (keys.isEmpty()) {
189+
break;
190+
}
191+
}
192+
}
193+
}
194+
}

0 commit comments

Comments
 (0)
Failed to load comments.