Detect gestures and clean up

Detect gestures

The application now needs a way of triggering the gesture callback function when a touch event occurs on the screen. The application must call gestures_set_process_event() when a touch event is detected and needs to be handled. In the sample application, this is called from handle_screen_event() which itself is called from handle_events() when a screen event is detected in the main application loop.

handle_screen_event(bps_event_t *event)
{
    int screen_val, rc;

    screen_event_t screen_event = screen_event_get_event(event);
    mtouch_event_t mtouch_event;
    rc = screen_get_event_property_iv(screen_event, 
            SCREEN_PROPERTY_TYPE, &screen_val);
    if(screen_val == SCREEN_EVENT_MTOUCH_TOUCH 
            || screen_val == SCREEN_EVENT_MTOUCH_MOVE 
            || screen_val == SCREEN_EVENT_MTOUCH_RELEASE) {
        rc = screen_get_mtouch_event(screen_event, &mtouch_event, 0);
        if (rc) {
            fprintf(stderr, "Error: failed to get mtouch event\n");
        }
        rc = gestures_set_process_event(set, &mtouch_event, NULL);
In this function, the determination of a gesture event is based on whether the incoming event is a touch, move, or release event. If it is one of these events, the application calls gestures_set_process_event().

If the call to gestures_set_process_event() does not trigger any callbacks, the function returns 0. This case occurs when a touch, move, or release event was detected but there was no associated gesture. The following code treats this case as a pan and adjusts the viewport position accordingly:

if (!rc) {
   if (mtouch_event.contact_id == 0) {
      if(last_touch[0] && last_touch[1]) {
         fprintf(stderr,"Pan %d %d\n",
               (last_touch[0] - mtouch_event.x),
               (last_touch[1] - mtouch_event.y));
         viewport_pos[0] = (last_touch[0] - mtouch_event.x) >> 1;
         viewport_pos[1] = (last_touch[1] - mtouch_event.y) >> 1;
      }
      last_touch[0] = mtouch_event.x;
      last_touch[1] = mtouch_event.y;
   }
}

Clean up gestures

Now that the application can perform actions based on gestures, at some point it needs to clean itself up before closing. In other words, it's always a good idea to clean up any memory associated with gestures data structures. In gestures_cleanup(), the following lines of code free the memory associated with the gesture set:

if (NULL != set) {
        gestures_set_free(set);
        set = NULL;
}

That's it! The application can now set up the gestures library, process gesture events, and clean up after itself.