Class: Processing::Watcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-processing/runners/watch.rb

Overview

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

Instance Method Summary collapse

Constructor Details

#initializeWatcher

Sic a new Processing::Watcher on the sketch



8
9
10
11
12
# File 'lib/ruby-processing/runners/watch.rb', line 8

def initialize
  reload_files_to_watch
  @time = Time.now
  start_watching
end

Instance Method Details

#reload_files_to_watchObject



49
50
51
# File 'lib/ruby-processing/runners/watch.rb', line 49

def reload_files_to_watch
  @files = ([SKETCH_PATH] + Dir.glob(File.dirname(SKETCH_PATH) + '/*.rb')).uniq
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.



33
34
35
36
37
38
# File 'lib/ruby-processing/runners/watch.rb', line 33

def report_errors
  yield
rescue Exception => e
  warn "Exception occured while running sketch #{File.basename SKETCH_PATH}..."
  puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
end

#start_runnerObject



40
41
42
43
44
45
46
47
# File 'lib/ruby-processing/runners/watch.rb', line 40

def start_runner
  @runner.kill if @runner && @runner.alive?
  @runner = Thread.start do
    report_errors do
      Processing.load_and_run_sketch
    end
  end
end

#start_watchingObject

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



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ruby-processing/runners/watch.rb', line 16

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