'''
Multistroke gesture recognizer
==============================

.. versionadded::
    1.9.0

.. warning::

    This is experimental and subject to change as long as this warning notice
    is present.

See :file:`kivy/examples/demo/multistroke/main.py` for a complete application
example.

Conceptual Overview
-------------------

This module implements the Protractor gesture recognition algorithm.

:class:`Recognizer` is the search/database API similar to
:class:`~kivy.gesture.GestureDatabase`. It maintains a list of
:class:`MultistrokeGesture` objects and allows you to search for a
user-input gestures among them.

:class:`ProgressTracker` tracks the progress of a :meth:`Recognizer.recognize`
call. It can be used to interact with the running recognizer task, for example
forcing it to stop half-way, or analyzing results as they arrive.

:class:`MultistrokeGesture` represents a gesture in the gesture database
(:attr:`Recognizer.db`). It is a container for :class:`UnistrokeTemplate`
objects, and implements the heap permute algorithm to automatically generate
all possible stroke orders (if desired).

:class:`UnistrokeTemplate` represents a single stroke path. It's typically
instantiated automatically by :class:`MultistrokeGesture`, but sometimes you
may need to create them manually.

:class:`Candidate` represents a user-input gesture that is used to search
the gesture database for matches. It is normally instantiated automatically
by calling :meth:`Recognizer.recognize`.

Usage examples
--------------

See :file:`kivy/examples/demo/multistroke/main.py` for a complete application
example.

You can bind to events on :class:`Recognizer` to track the state of all
calls to :meth:`Recognizer.recognize`. The callback function will receive an
instance of :class:`ProgressTracker` that can be used to analyze and control
various aspects of the recognition process ::

    from kivy.vector import Vector
    from kivy.multistroke import Recognizer

    gdb = Recognizer()

    def search_start(gdb, pt):
        print("A search is starting with %d tasks" % (pt.tasks))

    def search_stop(gdb, pt):
        # This will call max() on the result dictionary, so it's best to store
        # it instead of calling it 3 times consecutively
        best = pt.best
        print("Search ended (%s). Best is %s (score %f, distance %f)" % (
            pt.status, best['name'], best['score'], best['dist'] ))

    # Bind your callbacks to track all matching operations
    gdb.bind(on_search_start=search_start)
    gdb.bind(on_search_complete=search_stop)

    # The format below is referred to as `strokes`, a list of stroke paths.
    # Note that each path shown here consists of two points, ie a straight
    # line; if you plot them it looks like a T, hence the name.
    gdb.add_gesture('T', [
        [Vector(30, 7), Vector(103, 7)],
        [Vector(66, 7), Vector(66, 87)]])

    # Now you can search for the 'T' gesture using similar data (user input).
    # This will trigger both of the callbacks bound above.
    gdb.recognize([
        [Vector(45, 8), Vector(110, 12)],
        [Vector(88, 9), Vector(85, 95)]])

On the next :class:`~kivy.clock.Clock` tick, the matching process starts
(and, in this case, completes).

To track individual calls to :meth:`Recognizer.recognize`, use the return
value (also a :class:`ProgressTracker` instance) ::

    # Same as above, but keep track of progress using returned value
    progress = gdb.recognize([
        [Vector(45, 8), Vector(110, 12)],
        [Vector(88, 9), Vector(85, 95)]])

    progress.bind(on_progress=my_other_callback)
    print(progress.progress) # = 0

    # [ assuming a kivy.clock.Clock.tick() here ]

    print(result.progress) # = 1

Algorithm details
-----------------

For more information about the matching algorithm, see:

"Protractor: A fast and accurate gesture recognizer" by Yang Li
  http://yangl.org/pdf/protractor-chi2010.pdf

"$N-Protractor" by Lisa Anthony and Jacob O. Wobbrock
  http://depts.washington.edu/aimgroup/proj/dollar/ndollar-protractor.pdf

Some of the code is derived from the JavaScript implementation here:
  http://depts.washington.edu/aimgroup/proj/dollar/ndollar.html
'''

__all__ = ('Recognizer', 'ProgressTracker', 'MultistrokeGesture',
           'UnistrokeTemplate', 'Candidate')

import pickle
import base64
import zlib
from re import match as re_match
from collections import deque
from math import sqrt, pi, radians, acos, atan, atan2, pow, floor
from math import sin as math_sin, cos as math_cos
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.event import EventDispatcher
from kivy.properties import ListProperty
from io import BytesIO


# Default number of gesture matches per frame
# FIXME: relevant number
DEFAULT_GPF = 10

# Algorithm data
SQUARESIZE = 250.0
ONEDTHRESHOLD = 0.25
ORIGIN = Vector(0, 0)


class MultistrokeError(Exception):
    pass


# -----------------------------------------------------------------------------
# Recognizer
# -----------------------------------------------------------------------------

class Recognizer(EventDispatcher):
    ''':class:`Recognizer` provides a gesture database with matching
    facilities.

    :Events:
        `on_search_start`
            Fired when a new search is started using this Recognizer.

        `on_search_complete`
            Fired when a running search ends, for whatever reason.
            (use :data:`ProgressTracker.status` to find out)

    :Properties:
        `db`
            A :class:`ListProperty` that contains the available
            :class:`MultistrokeGesture` objects.

            :attr:`db` is a
            :class:`~kivy.properties.ListProperty` and defaults to []
    '''

    db = ListProperty([])

    def __init__(self, **kwargs):
        super(Recognizer, self).__init__(**kwargs)
        self.register_event_type('on_search_start')
        self.register_event_type('on_search_complete')

    def filter(self, **kwargs):
        ''':meth:`filter` returns a subset of objects in :attr:`self.db`,
        according to given criteria. This is used by many other methods of
        the :class:`Recognizer`; the arguments below can for example be
        used when calling :meth:`Recognizer.recognize` or
        :meth:`Recognizer.export_gesture`. You normally don't need to call
        this directly.

        :Arguments:

            `name`
                Limits the returned list to gestures where
                :attr:`MultistrokeGesture.name` matches given regular
                expression(s). If re.match(name, MultistrokeGesture.name)
                tests true, the gesture is included in the returned list.
                Can be a string or an array of strings ::

                    gdb = Recognizer()

                    # Will match all names that start with a capital N
                    # (ie Next, New, N, Nebraska etc, but not "n" or "next")
                    gdb.filter(name='N')

                    # exactly 'N'
                    gdb.filter(name='N$')

                    # Nebraska, teletubbies, France, fraggle, N, n, etc
                    gdb.filter(name=['[Nn]', '(?i)T', '(?i)F'])

            `priority`
                Limits the returned list to gestures with certain
                :attr:`MultistrokeGesture.priority` values. If specified as an
                integer, only gestures with a lower priority are returned. If
                specified as a list (min/max) ::

                    # Max priority 50
                    gdb.filter(priority=50)

                    # Max priority 50 (same result as above)
                    gdb.filter(priority=[0, 50])

                    # Min priority 50, max 100
                    gdb.filter(priority=[50, 100])

                When this option is used, :attr:`Recognizer.db` is
                automatically sorted according to priority, incurring extra
                cost. You can use `force_priority_sort` to override this
                behavior if your gestures are already sorted according to
                priority.

            `orientation_sensitive`
                Limits the returned list to gestures that are
                orientation sensitive (True), gestures that are not orientation
                sensitive (False) or None (ignore template sensitivity, this is
                the default).

            `numstrokes`
                Limits the returned list to gestures that have the specified
                number of strokes (in :attr:`MultistrokeGesture.strokes`).
                Can be a single integer or a list of integers.

            `numpoints`
                Limits the returned list to gestures that have specific
                :attr:`MultistrokeGesture.numpoints` values. This is provided
                for flexibility, do not use it unless you understand what it
                does. Can be a single integer or a list of integers.

            `force_priority_sort`
                Can be used to override the default sort behavior. Normally
                :class:`MultistrokeGesture` objects are returned in priority
                order if the `priority` option is used. Setting this to True
                will return gestures sorted in priority order, False will
                return in the order gestures were added. None means decide
                automatically (the default).

                .. Note ::
                    For improved performance, you can load your gesture
                    database in priority order and set this to False when
                    calling :meth:`Recognizer.recognize`

            `db`
                Can be set if you want to filter a different list of objects
                than :attr:`Recognizer.db`. You probably don't want to do this;
                it is used internally by :meth:`import_gesture`.
        '''
        have_filters = False

        kwargs_get = kwargs.get

        name = kwargs_get('name', None)
        if name is not None:
            have_filters = True
            if not isinstance(name, list):
                name = [name]

        priority = kwargs_get('priority', None)
        min_p, max_p = None, None
        if priority is not None:
            have_filters = True
            if isinstance(priority, list):
                min_p, max_p = priority
            elif isinstance(priority, int):
                min_p, max_p = None, priority

        numstrokes = kwargs_get('numstrokes', None)
        if numstrokes is not None:
            have_filters = True
            if not isinstance(numstrokes, list):
                numstrokes = [numstrokes]

        numpoints = kwargs_get('numpoints', None)
        if numpoints is not None:
            have_filters = True
            if not isinstance(numpoints, list):
                numpoints = [numpoints]

        orientation_sens = kwargs_get('orientation_sensitive', None)
        if orientation_sens is not None:
            have_filters = True

        # Prepare a correctly sorted tasklist
        force_priority_sort = kwargs.get('force_priority_sort', None)
        force_sort_on = force_priority_sort and True
        force_sort_off = (force_priority_sort is False) and True

        db = kwargs.get('db', None) or self.db
        if (force_sort_on or priority) and not force_sort_off:
            tasklist = sorted(db, key=lambda n: n.priority)
        else:
            tasklist = db

        # Now test each gesture in the database against filter criteria
        out = deque()
        if not have_filters:
            out.extend(tasklist)
            return out

        out_append = out.append
        for gesture in tasklist:

            if (orientation_sens is not None and
                    orientation_sens != gesture.orientation_sens):
                continue

            if numpoints and gesture.numpoints not in numpoints:
                continue

            if numstrokes and len(gesture.strokes) not in numstrokes:
                continue

            if min_p is not None and gesture.priority < min_p:
                continue

            if max_p is not None and gesture.priority > max_p:
                return out

            if name:
                for f in name:
                    if re_match(f, gesture.name):
                        out_append(gesture)
                        break
            else:
                out_append(gesture)

        return out

    def add_gesture(self, name, strokes, **kwargs):
        '''Add a new gesture to the database. This will instantiate a new
        :class:`MultistrokeGesture` with `strokes` and append it to self.db.

        .. Note ::
            If you already have instantiated a :class:`MultistrokeGesture`
            object and wish to add it, append it to :attr:`Recognizer.db`
            manually.
        '''
        if not strokes:
            return False
        self.db.append(
            MultistrokeGesture(name=name, strokes=strokes, **kwargs)
        )
        return True

    def parse_gesture(self, data):
        '''Parse data formatted by export_gesture(). Returns a list of
        :class:`MultistrokeGesture` objects. This is used internally by
        :meth:`import_gesture`, you normally don't need to call this
        directly.'''
        io = BytesIO(zlib.decompress(base64.b64decode(data)))

        p = pickle.Unpickler(io)
        multistrokes = []
        ms_append = multistrokes.append
        for multistroke in p.load():
            strokes = multistroke['strokes']
            multistroke['strokes'] = [[Vector(
                x, y) for x, y in line] for line in strokes]
            ms_append(MultistrokeGesture(**multistroke))
        return multistrokes

    # FIXME: use a try block, maybe shelve or something
    def export_gesture(self, filename=None, **kwargs):
        '''Export a list of :class:`MultistrokeGesture` objects. Outputs a
        base64-encoded string that can be decoded to a Python list with
        the :meth:`parse_gesture` function or imported directly to
        :attr:`self.db` using :meth:`Recognizer.import_gesture`. If
        `filename` is specified, the output is written to disk, otherwise
        returned.

        This method accepts optional :meth:`Recognizer.filter` arguments.
        '''
        io = BytesIO()
        p = pickle.Pickler(io, protocol=0)
        multistrokes = []
        defaults = {'priority': 100, 'numpoints': 16, 'stroke_sens': True,
                    'orientation_sens': False, 'angle_similarity': 30.0}
        dkeys = defaults.keys()

        for multistroke in self.filter(**kwargs):
            m = dict(defaults)
            m = {'name': multistroke.name}
            for attr in dkeys:
                m[attr] = getattr(multistroke, attr)
            m['strokes'] = tuple([(p.x, p.y) for p in line]
                                 for line in multistroke.strokes)
            multistrokes.append(m)
        p.dump(multistrokes)

        if filename:
            f = open(filename, 'wb')
            f.write(base64.b64encode(zlib.compress(io.getvalue(), 9)))
            f.close()
        else:
            return base64.b64encode(zlib.compress(io.getvalue(), 9))

    # FIXME: match them all with protractor, and don't load exacts? or
    # just compare the data or something; seems better to do this on import
    # than on every subsequent call to recognize(). And fix it in general,
    # too.
    def import_gesture(self, data=None, filename=None, **kwargs):
        '''Import a list of gestures as formatted by :meth:`export_gesture`.
        One of `data` or `filename` must be specified.

        This method accepts optional :meth:`Recognizer.filter` arguments,
        if none are specified then all gestures in specified data are
        imported.'''
        if filename is not None:
            with open(filename, "rb") as infile:
                data = infile.read()
        elif data is None:
            raise MultistrokeError('import_gesture needs data= or filename=')

        new = self.filter(db=self.parse_gesture(data), **kwargs)
        if new:
            self.db.extend(new)

    def transfer_gesture(self, tgt, **kwargs):
        '''Transfers :class:`MultistrokeGesture` objects from
        :attr:`Recognizer.db` to another :class:`Recognizer` instance `tgt`.

        This method accepts optional :meth:`Recognizer.filter` arguments.
        '''
        if hasattr(tgt, 'db') and isinstance(tgt.db, list):
            send = self.filter(**kwargs)
            if send:
                tgt.db.append(None)
                tgt.db[-1:] = send
                return True

    def prepare_templates(self, **kwargs):
        '''This method is used to prepare :class:`UnistrokeTemplate` objects
        within the gestures in self.db. This is useful if you want to minimize
        punishment of lazy resampling by preparing all vectors in advance. If
        you do this before a call to :meth:`Recognizer.export_gesture`, you
        will have the vectors computed when you load the data later.

        This method accepts optional :meth:`Recognizer.filter` arguments.

        `force_numpoints`, if specified, will prepare all templates to the
        given number of points (instead of each template's preferred n; ie
        :data:`UnistrokeTemplate.numpoints`). You normally don't want to
        do this.'''
        for gesture in self.filter(**kwargs):
            for tpl in gesture:
                n = kwargs.get('force_numpoints', tpl.numpoints)
                tpl.prepare(n)

    def recognize(self, strokes, goodscore=None, timeout=0, delay=0, **kwargs):
        '''Search for gestures matching `strokes`. Returns a
        :class:`ProgressTracker` instance.

        This method accepts optional :meth:`Recognizer.filter` arguments.

        :Arguments:

            `strokes`
                A list of stroke paths (list of lists of
                :class:`~kivy.vector.Vector` objects) that will be matched
                against gestures in the database. Can also be a
                :class:`Candidate` instance.

                .. Warning ::

                    If you manually supply a :class:`Candidate` that has a
                    skip-flag, make sure that the correct filter arguments
                    are set. Otherwise the system will attempt to load vectors
                    that have not been computed. For example, if you set
                    `skip_bounded` and do not set `orientation_sensitive` to
                    False, it will raise an exception if an
                    orientation_sensitive :class:`UnistrokeTemplate`
                    is encountered.

            `goodscore`
                If this is set (between 0.0 - 1.0) and a gesture score is
                equal to or higher than the specified value, the search is
                immediately halted and the on_search_complete event is
                fired (+ the on_complete event of the associated
                :class:`ProgressTracker` instance). Default is None (disabled).

            `timeout`
                Specifies a timeout (in seconds) for when the search is
                aborted and the results returned. This option applies only
                when `max_gpf` is not 0. Default value is 0, meaning all
                gestures in the database will be tested, no matter how long
                it takes.

            `max_gpf`
                Specifies the maximum number of :class:`MultistrokeGesture`
                objects that can be processed per frame. When exceeded, will
                cause the search to halt and resume work in the next frame.
                Setting to 0 will complete the search immediately (and block
                the UI).

                .. Warning ::

                    This does not limit the number of
                    :class:`UnistrokeTemplate` objects matched! If a single
                    gesture has a million templates, they will all be
                    processed in a single frame with max_gpf=1!

            `delay`
                Sets an optional delay between each run of the recognizer
                loop. Normally, a run is scheduled for the next frame until
                the tasklist is exhausted. If you set this, there will be an
                additional delay between each run (specified in seconds).
                Default is 0, resume in the next frame.

            `force_numpoints`
                forces all templates (and candidate) to be prepared to a
                certain number of points. This can be useful for example if
                you are evaluating templates for optimal n (do not use this
                unless you understand what it does).
        '''
        GPF = kwargs.get('max_gpf', DEFAULT_GPF)

        # Obtain a list of MultistrokeGesture objects matching filter arguments
        tasklist = self.filter(**kwargs)

        # Initialize the candidate and result objects
        cand = self._candidate(strokes)
        result = ProgressTracker(cand, len(tasklist))

        # This is done to inform caller if they bind to on_complete and there
        # is nothing to do; perhaps should just return None?
        if not tasklist:
            result.status = 'complete'
            self.dispatch('on_search_complete', result)

            def result_hack(dt):
                result.dispatch('on_complete')
            Clock.schedule_once(result_hack)
            return result

        # This callback is scheduled once per frame until completed
        def _recognize_tick(dt):
            start_gc = result._completed
            stop_now = False

            while not stop_now and (tasklist and not result._break_flag) and \
                    (not GPF or (result._completed - start_gc < GPF)):

                if (timeout and
                        Clock.get_time() - result._start_time >= timeout):
                    result.status = 'timeout'
                    stop_now = True
                    break

                # Get the best distance and number of matching operations done
                gesture = tasklist.popleft()
                tpl, d, res, mos = gesture.match_candidate(
                    cand, **kwargs)

                if tpl is not None:
                    score = result._add_result(gesture, d, tpl, res)
                    if goodscore is not None and score >= goodscore:
                        result.status = 'goodscore'
                        stop_now = True

                result._match_ops += mos
                result._completed += 1
                result.dispatch('on_progress')

            # The loop has ended. Prepare to dispatch 'complete'
            def _dispatch():
                result.dispatch('on_complete')
                self.dispatch('on_search_complete', result)
                return False

            # Dispatch or reschedule another run
            if not tasklist:
                result.status = 'complete'
                return _dispatch()
            elif result._break_flag:
                result.status = 'stop'
                return _dispatch()
            elif stop_now:
                return _dispatch()
            else:
                Clock.schedule_once(_recognize_tick, delay)
                return True
        # End _recognize_tick()

        self.dispatch('on_search_start', result)
        if not GPF:
            _recognize_tick(0)
        else:
            Clock.schedule_once(_recognize_tick, 0)

        return result

    def _candidate(self, strokes, **kwargs):
        # recognize() helper function, do not use directly. Set up a
        # Candidate object from arguments. Either use a specified object
        # or make a new one from strokes and apply safe skip_* settings to
        # use less resources.
        if isinstance(strokes, Candidate):
            return strokes

        if (not isinstance(strokes, list) or not len(strokes) or not
                isinstance(strokes[0], list)):
            raise MultistrokeError('recognize() needs strokes= '
                                   'list or Candidate')

        cand = Candidate(strokes)
        o_filter = kwargs.get('orientation_sensitive', None)
        if o_filter is False:
            cand.skip_bounded = True
        elif o_filter is True:
            cand.skip_invariant = True

        return cand

    # Default event handlers
    def on_search_start(self, result):
        pass

    def on_search_complete(self, result):
        pass


# -----------------------------------------------------------------------------
# ProgressTracker
# -----------------------------------------------------------------------------

class ProgressTracker(EventDispatcher):
    '''Represents an ongoing (or completed) search operation. Instantiated and
    returned by the :meth:`Recognizer.recognize` method when it is called. The
    `results` attribute is a dictionary that is  updated as the recognition
    operation progresses.

    .. Note ::
        You do not need to instantiate this class.

    :Arguments:
        `candidate`
            :class:`Candidate` object to be evaluated
        `tasks`
            Total number of gestures in tasklist (to test against)

    :Events:
        `on_progress`
            Fired for every gesture that is processed
        `on_result`
            Fired when a new result is added, and it is the first match
            for the `name` so far, or a consecutive match with better score.
        `on_complete`
            Fired when the search is completed, for whatever reason.
            (use `ProgressTracker.status` to find out)

    :Attributes:
        `results`
            A dictionary of all results (so far). The key is the name of the
            gesture (ie :attr:`UnistrokeTemplate.name` usually inherited from
            :class:`MultistrokeGesture`). Each item in the dictionary is a
            dict with the following entries:

                `name`
                    Name of the matched template (redundant)
                `score`
                    Computed score from 1.0 (perfect match) to 0.0
                `dist`
                    Cosine distance from candidate to template (low=closer)
                `gesture`
                    The :class:`MultistrokeGesture` object that was matched
                `best_template`
                    Index of the best matching template (in
                    :attr:`MultistrokeGesture.templates`)
                `template_results`
                    List of distances for all templates. The list index
                    corresponds to a :class:`UnistrokeTemplate` index in
                    gesture.templates.

        `status`
            `search`
                Currently working
            `stop`
                Was stopped by the user (:meth:`stop` called)
            `timeout`
                A timeout occurred (specified as `timeout=` to recognize())
            `goodscore`
                The search was stopped early because a gesture with a high
                enough score was found (specified as `goodscore=` to
                recognize())
            `complete`
                The search is complete (all gestures matching filters were
                tested)
    '''
    def __init__(self, candidate, tasks, **kwargs):
        self.status = 'search'
        self.candidate = candidate
        self.results = {}
        self.tasks = tasks
        self._start_time = Clock.get_time()
        self._match_ops = 0
        self._completed = 0
        self._break_flag = False

        # fired by recognize()
        self.register_event_type('on_complete')
        self.register_event_type('on_progress')

        # fired locally
        self.register_event_type('on_result')
        super(ProgressTracker, self).__init__(**kwargs)

    @property
    def progress(self):
        '''Returns the progress as a float, 0 is 0% done, 1 is 100%. This
        is a Python property.'''
        if not self.tasks:
            return 1
        return self._completed / float(self.tasks)

    @property
    def best(self):
        '''Return the best match found by recognize() so far. It returns a
        dictionary with three keys, 'name', 'dist' and 'score' representing
        the template's name, distance (from candidate path) and the
        computed score value. This is a Python property.'''
        results = self.results  # to avoid too many self. lookups
        if not results:
            return {'name': None, 'dist': None, 'score': 0}
        b = max(results, key=lambda r: results[r]['score'])
        return {
            'name': results[b]['name'],
            'dist': results[b]['dist'],
            'score': results[b]['score']
        }

    def stop(self):
        '''Raises a stop flag that is checked by the search process. It will
        be stopped on the next clock tick (if it is still running).'''
        self._break_flag = True

    def _add_result(self, gesture, dist, tpl, res):
        # Add a result; used internally by the recognize() function
        if tpl <= len(res):
            n = gesture.templates[tpl].name
        else:
            return 0.

        if n not in self.results or dist < self.results[n]['dist']:
            self.results[n] = {
                'name': n,
                'dist': dist,
                'gesture': gesture,
                'best_template': tpl,
                'template_results': res
            }

            if not dist:
                self.results[n]['score'] = 1.0
            else:
                self.results[n]['score'] = 1.0 - (dist / pi)

            self.dispatch('on_result', self.results[n])
            return self.results[n]['score']
        else:
            return 0.

    def on_complete(self):
        pass

    def on_progress(self):
        pass

    def on_result(self, result):
        pass


# -----------------------------------------------------------------------------
# MultistrokeGesture
# -----------------------------------------------------------------------------

class MultistrokeGesture(object):
    ''':class:`MultistrokeGesture` represents a gesture. It maintains a set of
    `strokes` and generates unistroke (ie :class:`UnistrokeTemplate`)
    permutations that are used for evaluating candidates against this gesture
    later.

    :Arguments:
        `name`
            Identifies the name of the gesture - it is returned to you in the
            results of a :meth:`Recognizer.recognize` search. You can have any
            number of MultistrokeGesture objects with the same name; many
            definitions of one gesture. The same name is given to all the
            generated unistroke permutations. Required, no default.
        `strokes`
            A list of paths that represents the gesture. A path is a list of
            Vector objects::

                gesture = MultistrokeGesture('my_gesture', strokes=[
                  [Vector(x1, y1), Vector(x2, y2), ...... ], # stroke 1
                  [Vector(), Vector(), Vector(), Vector() ]  # stroke 2
                  #, [stroke 3], [stroke 4], ...
                ])

            For template matching purposes, all the strokes are combined to a
            single list (unistroke). You should still specify the strokes
            individually, and set `stroke_sensitive` True (whenever possible).

            Once you do this, unistroke permutations are immediately generated
            and stored in `self.templates` for later, unless you set the
            `permute` flag to False.
        `priority`
            Determines when :func:`Recognizer.recognize` will attempt to match
            this template, lower priorities are evaluated first (only if
            a priority `filter` is used). You should use lower priority on
            gestures that are more likely to match. For example, set user
            templates at lower number than generic templates. Default is 100.
        `numpoints`
            Determines the number of points this gesture should be resampled to
            (for matching purposes). The default is 16.
        `stroke_sensitive`
            Determines if the number of strokes (paths) in this gesture is
            required to be the same in the candidate (user input) gesture
            during matching. If this is False, candidates will always be
            evaluated, disregarding the number of strokes. Default is True.
        `orientation_sensitive`
            Determines if this gesture is orientation sensitive. If True,
            aligns the indicative orientation with the one of eight base
            orientations that requires least rotation. Default is True.
        `angle_similarity`
