Arthur POULET
3469024b23
This change tries to modivy the event to be a "generic entity" that holds the data about the event (type, code, modifiers). It does not use crystal generics. I don't plan to merge it on master because it adds a overheat.
80 lines
2.1 KiB
Crystal
80 lines
2.1 KiB
Crystal
require "../../src/ui/event_handler"
|
|
|
|
class TestingEvent; end
|
|
|
|
class TestingEventA < TestingEvent
|
|
getter :code, :alt, :control, :shift, :system, :stuff
|
|
def initialize(@code = "001", @alt = false, @control = false, @shift = false, @system = false, @stuff = false)
|
|
end
|
|
end
|
|
|
|
class TestingEventB < TestingEvent
|
|
getter :code
|
|
def initialize(@code = "001")
|
|
end
|
|
end
|
|
|
|
class UI::Event
|
|
TEST_MAPPING = { TestingEventA => Type::KeyPressed, TestingEventB => Type::KeyReleased, }
|
|
def initialize(event : TestingEvent)
|
|
@type = TEST_MAPPING[event.class]? || Type::Unknown
|
|
@code = event.responds_to?(:code) ? event.code : nil
|
|
@alt = event.responds_to?(:alt) ? event.alt.to_s : nil
|
|
@control = event.responds_to?(:control) ? event.control.to_s : nil
|
|
@shift = event.responds_to?(:shift) ? event.shift.to_s : nil
|
|
@system = event.responds_to?(:system) ? event.system.to_s : nil
|
|
end
|
|
|
|
class Handler
|
|
def event_callbacks(event : TestingEvent.class)
|
|
event = TEST_MAPPING[event]
|
|
event_callbacks(event)
|
|
end
|
|
|
|
def handle(event : TestingEvent)
|
|
handle(Event.new(event))
|
|
end
|
|
end
|
|
end
|
|
|
|
describe UI::Event::Handler do
|
|
it "verifies event accumulates and remove callbacks" do
|
|
|
|
a = UI::Event::Handler.new
|
|
counter = 0
|
|
a.add(UI::Event::Type::KeyPressed) do |cb, _|
|
|
counter += 1
|
|
end
|
|
a.add(UI::Event::Type::KeyReleased) do |cb, _|
|
|
counter += 10
|
|
end
|
|
|
|
# test having multiple events with different types
|
|
counter.should eq(0)
|
|
a.handle(TestingEventA.new)
|
|
counter.should eq(1)
|
|
a.handle(TestingEventA.new)
|
|
counter.should eq(2)
|
|
a.handle(TestingEventB.new)
|
|
counter.should eq(12)
|
|
|
|
# test 2 callbacks on the same event
|
|
a.add(UI::Event::Type::KeyPressed) do |cb, _|
|
|
counter += 1
|
|
end
|
|
a.handle(TestingEventA.new)
|
|
counter.should eq(14)
|
|
|
|
# test a callback with autoremove (useful for keypressing)
|
|
a.add(UI::Event::Type::KeyPressed) do |cb, _|
|
|
counter += 100
|
|
a.remove(UI::Event::Type::KeyPressed, cb)
|
|
end
|
|
a.handle(TestingEventA.new)
|
|
counter.should eq(116)
|
|
a.handle(TestingEventA.new)
|
|
counter.should eq(118)
|
|
|
|
end
|
|
end
|