Duncan McIntyre / SimpleGUITouchScreen

Dependents:   TouchScreenGUIDemo

TouchScreenEventSource.cpp

Committer:
duncanFrance
Date:
2016-03-25
Revision:
1:6fb3545bddf7
Parent:
0:b250e56f3514
Child:
3:45777fe81448

File content as of revision 1:6fb3545bddf7:

#include "TouchScreenEventSource.h"
/**
* Implementation of TouchScreenEventSource which adds timers to detect and dispatch
* tap and double-tap events
**/

TouchScreenEventSource::TouchScreenEventSource(TouchScreen* touchScreen, EventDispatcher* dispatcher) 
: EventSource(dispatcher), _touchScreen(touchScreen), _state(Idle)
{
}

void TouchScreenEventSource::touchStartHandler(TouchPosition p)
{
    if(_state == Idle) {
        // see if we get the touchEnd event before the timeout
        _state = SingleTimer;
        _timeout.attach_us(this, &TouchScreenEventSource::_timeoutHandler, TAP_TIMEOUT_MICROS);
    }
    
    Event e;
    e.screenX = p.screenX;
    e.screenY = p.screenY;
    e.type = touchStartEvent;
    _dispatcher->dispatchEvent(e);
}

void TouchScreenEventSource::touchMoveHandler(TouchPosition p)
{
    
    Event e;
    e.screenX = p.screenX;
    e.screenY = p.screenY;
    e.type = touchMoveEvent;
    _dispatcher->dispatchEvent(e);
}

void TouchScreenEventSource::touchEndHandler(TouchPosition p)
{
    // Work out what events we need before we dispatch them, so the handler doesn't interfere with any timers
    Event endEvent;
    Event tapEvent;
    bool tapped = false;
    
    // We always want to dispatch a touchEndEvent
    endEvent.screenX = p.screenX;
    endEvent.screenY = p.screenY;
    endEvent.type = touchEndEvent;
    
    tapEvent.screenX = p.screenX;
    tapEvent.screenY = p.screenY;

    // We'll want a touchTapEvent if we haven't timed out and we're looking for it
    if(_state == SingleTimer) {
        // Reset the timer to look for a double-tap
        _timeout.attach_us(this, &TouchScreenEventSource::_timeoutHandler, DOUBLE_TAP_TIMEOUT_MICROS);
        _state = DoubleTimer;
        
        tapEvent.type = touchTapEvent;
        tapped = true;
    } else if(_state == DoubleTimer) {
        
        _timeout.detach();
        _state = Idle;
        
        tapEvent.type = touchDoubleTapEvent;
        tapped = true;
    }
        
    _dispatcher->dispatchEvent(endEvent);
    
    if(tapped) {
        _dispatcher->dispatchEvent(tapEvent);
    }
}

void TouchScreenEventSource::_timeoutHandler() {
    // Timed out waiting for whatever, so clear the state
    _state = Idle;
}