voicemeeter-rb/lib/voicemeeter/event.rb

84 lines
2.0 KiB
Ruby
Raw Normal View History

module Voicemeeter
module Events
module Director
def observers
@observers ||= {}
end
def on(event, method = nil, &block)
(observers[event] ||= []) << (block || method)
end
def register(cbs)
cbs = Array(cbs) unless cbs.respond_to? :each
cbs.each { |cb| on(cb.name[3..].to_sym, cb) }
end
def deregister(cbs)
cbs = Array(cbs) unless cbs.respond_to? :each
cbs.each { |cb| observers[cb.name[3..].to_sym]&.reject! { |o| cbs.include? o } }
end
def fire(event)
observers[event]&.each { |block| block.call }
end
end
class Tracker
include Logging
2023-07-14 11:44:49 +01:00
class << self
private def attr_events(*params)
params.each do |param|
define_method("#{param}=") do |value|
instance_variable_set("@#{param}", value)
info("#{param} #{value ? "added to" : "removed from"}")
end
end
end
end
attr_reader :pdirty, :mdirty, :midi, :ldirty
attr_events :pdirty, :mdirty, :midi, :ldirty
def initialize(**kwargs)
kwargs.each do |key, value|
instance_variable_set("@#{key}", value || false)
end
end
def to_s
2023-07-14 11:44:49 +01:00
self.class.name.split("::").last.to_s
end
def info(msg = nil)
info_msg = msg ? ["#{msg} events."] : []
2023-07-31 15:04:34 +01:00
info_msg << if any?
2023-07-14 11:44:49 +01:00
["Now listening for #{get.join(", ")} events"]
else
2023-07-14 11:44:49 +01:00
["Not listening for any events"]
end
2023-08-01 23:41:23 +01:00
logger.info info_msg.join(" ")
end
def get
2023-07-20 09:50:44 +01:00
%i[pdirty mdirty midi ldirty].reject { |ev| !send(ev) }
end
def any?
[pdirty, mdirty, midi, ldirty].any?
end
def add(events)
2023-07-22 16:44:24 +01:00
events = [events] unless events.respond_to? :each
events.each { |e| send("#{e}=", true) }
end
def remove(events)
2023-07-22 16:44:24 +01:00
events = [events] unless events.respond_to? :each
events.each { |e| send("#{e}=", false) }
end
end
end
end