class Processing::Watcher

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

Constants

SLEEP_TIME

Public Class Methods

new() click to toggle source
# File lib/jruby_art/runners/watch.rb, line 24
def initialize
  count = Dir['**.*rb'].length
  max_watch = RP_CONFIG.fetch('MAX_WATCH', 20)
  abort format(WATCH_MESSAGE, max_watch, count) if count > max_watch.to_i

  reload_files_to_watch
  @time = Time.now
  start_watching
end

Public Instance Methods

reload_files_to_watch() click to toggle source
# File lib/jruby_art/runners/watch.rb, line 77
def reload_files_to_watch
  @files = Dir.glob(File.join(SKETCH_ROOT, '**/*.{rb,glsl}'))
end
report_errors() { || ... } click to toggle source

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

# File lib/jruby_art/runners/watch.rb, line 53
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_original() click to toggle source
# File lib/jruby_art/runners/watch.rb, line 62
def start_original
  @runner = Thread.start do
    report_errors do
      Processing.load_and_run_sketch
    end
  end
end
start_runner() click to toggle source
# File lib/jruby_art/runners/watch.rb, line 70
def start_runner
  @runner.kill if @runner&.alive?
  @runner.join
  @runner = nil
  start_original
end
start_watching() click to toggle source

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

# File lib/jruby_art/runners/watch.rb, line 36
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&.close
      java.lang.System.gc
      @time = Time.now
      start_runner
      reload_files_to_watch
    end
    sleep SLEEP_TIME
  end
end