Class: Processing::Watcher

Inherits:
Object
  • Object
show all
Defined in:
lib/jruby_art/runners/watch.rb

Overview

A sketch loader, observer, and reloader, to tighten the feedback between code and effect.

Constant Summary collapse

SLEEP_TIME =
0.2

Instance Method Summary collapse

Constructor Details

#initializeWatcher

Returns a new instance of Watcher.



23
24
25
26
27
28
29
30
# File 'lib/jruby_art/runners/watch.rb', line 23

def initialize
  count = Dir["**.*rb"].length
  max_watch = RP_CONFIG.fetch('MAX_WATCH', 20)
  return warn format(WATCH_MESSAGE, max_watch, count) if count > max_watch.to_i
  reload_files_to_watch
  @time = Time.now
  start_watching
end

Instance Method Details

#reload_files_to_watchObject



75
76
77
# File 'lib/jruby_art/runners/watch.rb', line 75

def reload_files_to_watch
  @files = Dir.glob(File.join(SKETCH_ROOT, '**/*.{rb,glsl}'))
end

#report_errorsObject

Convenience function to report errors when loading and running a sketch, instead of having them eaten by the thread they are loaded in.



51
52
53
54
55
56
57
58
# File 'lib/jruby_art/runners/watch.rb', line 51

def report_errors
  yield
rescue Exception => e
  wformat = 'Exception occured while running sketch %s...'
  tformat = "Backtrace:\n\t%s"
  warn format(wformat, File.basename(SKETCH_PATH))
  puts format(tformat, e.backtrace.join("\n\t"))
end

#start_originalObject



60
61
62
63
64
65
66
# File 'lib/jruby_art/runners/watch.rb', line 60

def start_original
  @runner = Thread.start do
    report_errors do
      Processing.load_and_run_sketch
    end
  end
end

#start_runnerObject



68
69
70
71
72
73
# File 'lib/jruby_art/runners/watch.rb', line 68

def start_runner
  @runner.kill if @runner && @runner.alive?
  @runner.join
  @runner = nil
  start_original
end

#start_watchingObject

Kicks off a thread to watch the sketch, reloading JRubyArt and restarting the sketch whenever it changes.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jruby_art/runners/watch.rb', line 34

def start_watching
  start_original
  Kernel.loop do
    if @files.find { |file| FileTest.exist?(file) && File.stat(file).mtime > @time }
      puts 'reloading sketch...'
      Processing.app && Processing.app.close
      java.lang.System.gc
      @time = Time.now
      start_runner
      reload_files_to_watch
    end
    sleep SLEEP_TIME
  end
end