summaryrefslogtreecommitdiff
path: root/NxWidgets/nxwm/src/ctouchscreen.cxx
blob: 3792811a4caaa2dd026c7238b68bb1341a61d2da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/********************************************************************************************
 * NxWidgets/nxwm/src/ctouchscreen.cxx
 *
 *   Copyright (C) 2012 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX, NxWidgets, nor the names of its contributors
 *    me be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ********************************************************************************************/

/********************************************************************************************
 * Included Files
 ********************************************************************************************/

#include <nuttx/config.h>

#include <cunistd>
#include <cerrno>
#include <cfcntl>

#include <sys/boardctl.h>
#include <sched.h>
#include <pthread.h>
#include <assert.h>
#include <debug.h>

#include <nuttx/nx/nxglib.h>

#include "nxconfig.hxx"
#include "cwidgetcontrol.hxx"
#include "cgraphicsport.hxx"

#include "nxwmconfig.hxx"
#include "nxwmglyphs.hxx"
#include "ctouchscreen.hxx"

/********************************************************************************************
 * Pre-Processor Definitions
 ********************************************************************************************/
/* We want debug output from this file if either input/touchscreen or graphics debug is
 * enabled.
 */

#if !defined(CONFIG_DEBUG_INPUT) && !defined(CONFIG_DEBUG_GRAPHICS)
#  undef dbg
#  undef vdbg
#  ifdef CONFIG_CPP_HAVE_VARARGS
#    define dbg(x...)
#    define vdbg(x...)
#  else
#    define dbg  (void)
#    define vdbg (void)
#  endif
#endif

/********************************************************************************************
 * CTouchscreen Method Implementations
 ********************************************************************************************/

using namespace NxWM;

/**
 * CTouchscreen Constructor
 *
 * @param server. An instance of the NX server.  This will be needed for
 *   injecting mouse data.
 * @param windowSize.  The size of the physical window in pixels.  This
 *   is needed for touchscreen scaling.
 */

CTouchscreen::CTouchscreen(NXWidgets::CNxServer *server, struct nxgl_size_s *windowSize)
{
  m_server      = server;              // Save the NX server
  m_touchFd     = -1;                  // Device driver is not opened
  m_state       = LISTENER_NOTRUNNING; // The listener thread is not running yet
  m_enabled     = false;               // Normal forwarding is not enabled
  m_capture     = false;               // There is no thread waiting for touchscreen data
  m_calibrated  = false;               // We have no calibration data

  // Save the window size

  m_windowSize = *windowSize;

  // Use the default touch data buffer

  m_touch       = &m_sample;

  // Initialize the m_waitSem semaphore so that any waits for data will block

  sem_init(&m_waitSem, 0, 0);
}

/**
 * CTouchscreen Destructor
 */

CTouchscreen::~CTouchscreen(void)
{
  // Stop the listener thread

  m_state = LISTENER_STOPREQUESTED;

  // Wake up the listener thread so that it will use our buffer
  // to receive data
  // REVISIT:  Need wait here for the listener thread to terminate

  (void)pthread_kill(m_thread, CONFIG_NXWM_TOUCHSCREEN_SIGNO);

  // Close the touchscreen device (or should these be done when the thread exits?)

  if (m_touchFd >= 0)
    {
      std::close(m_touchFd);
    }

   // Destroy the semaphores that we created.

   sem_destroy(&m_waitSem);
}

/**
 * Start the touchscreen listener thread.
 *
 * @return True if the touchscreen listener thread was correctly started.
 */

bool CTouchscreen::start(void)
{
  pthread_attr_t attr;

  vdbg("Starting listener\n");

  // Start a separate thread to listen for touchscreen events

  (void)pthread_attr_init(&attr);

  struct sched_param param;
  param.sched_priority = CONFIG_NXWM_TOUCHSCREEN_LISTENERPRIO;
  (void)pthread_attr_setschedparam(&attr, &param);

  (void)pthread_attr_setstacksize(&attr, CONFIG_NXWM_TOUCHSCREEN_LISTENERSTACK);

  m_state  = LISTENER_STARTED; // The listener thread has been started, but is not yet running

  int ret = pthread_create(&m_thread, &attr, listener, (FAR void *)this);
  if (ret != 0)
    {
      dbg("CTouchscreen::start: pthread_create failed: %d\n", ret);
      return false;
    }

  // Detach from the thread

  (void)pthread_detach(m_thread);

  // Don't return until we are sure that the listener thread is running
  // (or until it reports an error).

  while (m_state == LISTENER_STARTED)
    {
      // Wait for the listener thread to wake us up when we really
      // are connected.

      (void)sem_wait(&m_waitSem);
    }

  // Then return true only if the listener thread reported successful
  // initialization.

  vdbg("Listener m_state=%d\n", (int)m_state);
  return m_state == LISTENER_RUNNING;
}

/**
 * Provide touchscreen calibration data.  If calibration data is received (and
 * the touchscreen is enabled), then received touchscreen data will be scaled
 * using the calibration data and forward to the NX layer which dispatches the
 * touchscreen events in window-relative positions to the correct NX window.
 *
 * @param data.  A reference to the touchscreen data.
 */

void CTouchscreen::setCalibrationData(const struct SCalibrationData &caldata)
{
  // Save a copy of the calibration data

  m_calibData = caldata;

  // Note that we have calibration data.  Data will now be scaled and forwarded
  // to NX (unless we are still in cpature mode)

   m_calibrated = true;

  // Wake up the listener thread so that it will use our buffer
  // to receive data

  (void)pthread_kill(m_thread, CONFIG_NXWM_TOUCHSCREEN_SIGNO);
}

/**
 * Capture raw driver data.  This method will capture mode one raw touchscreen
 * input.  The normal use of this method is for touchscreen calibration.
 *
 * This function is not re-entrant:  There may be only one thread waiting for
 * raw touchscreen data.
 *
 * @return True if the raw touchscreen data was successfully obtained
 */

bool CTouchscreen::waitRawTouchData(struct touch_sample_s *touch)
{
  vdbg("Capturing touch input\n");

  // Setup to cpature raw data into the user provided buffer

  sched_lock();
  m_touch   = touch;
  m_capture = true;

  // Wake up the listener thread so that it will use our buffer
  // to receive data

  (void)pthread_kill(m_thread, CONFIG_NXWM_TOUCHSCREEN_SIGNO);

  // And wait for touch data

  int ret = OK;
  while (m_capture)
    {
      ret = sem_wait(&m_waitSem);
      DEBUGASSERT(ret == 0 || errno == EINTR);
    }
  sched_unlock();

  // And return success.  The listener thread will have (1) reset both
  // m_touch and m_capture and (2) posted m_waitSem

  vdbg("Returning touch input: %d\n", ret);
  return ret == OK;
}

/**
 * The touchscreen listener thread.  This is the entry point of a thread that
 * listeners for and dispatches touchscreen events to the NX server.
 *
 * @param arg.  The CTouchscreen 'this' pointer cast to a void*.
 * @return This function normally does not return but may return NULL on
 *   error conditions.
 */

FAR void *CTouchscreen::listener(FAR void *arg)
{
  CTouchscreen *This = (CTouchscreen *)arg;

  vdbg("Listener started\n");

#ifdef CONFIG_NXWM_TOUCHSCREEN_DEVINIT
  // Initialize the touchscreen device

  int ret = boardctl(BOARDIOC_TSCTEST_SETUP, CONFIG_NXWM_TOUCHSCREEN_DEVNO);
  if (ret < 0)
    {
      dbg("ERROR Failed initialize the touchscreen device: %d\n", ret);
      This->m_state = LISTENER_FAILED;
      sem_post(&This->m_waitSem);
      return (FAR void *)0;
    }
#endif

  // Open the touchscreen device that we just created.

  This->m_touchFd = std::open(CONFIG_NXWM_TOUCHSCREEN_DEVPATH, O_RDONLY);
  if (This->m_touchFd < 0)
    {
      dbg("ERROR Failed to open %s for reading: %d\n",
           CONFIG_NXWM_TOUCHSCREEN_DEVPATH, errno);
      This->m_state = LISTENER_FAILED;
      sem_post(&This->m_waitSem);
      return (FAR void *)0;
    }

  // Indicate that we have successfully initialized

  This->m_state = LISTENER_RUNNING;
  sem_post(&This->m_waitSem);

  // Now loop, reading and dispatching touchscreen data

  while (This->m_state == LISTENER_RUNNING)
    {
      // We may be running in one of three states
      //
      // 1. Disabled or no calibration data:  In this case, just wait for a signal
      //    indicating that the state has changed.
      // 2. Performing calibration and reporting raw touchscreen data
      // 3. Normal operation, reading touchscreen data and forwarding it to NX

      // Check if we need to collect touchscreen data.  That is, that we are enabled,
      // AND have calibration data OR if we need to collect data for the calibration
      // process.

      while ((!This->m_enabled || !This->m_calibrated) && !This->m_capture)
        {
          // No.. just sleep.  This sleep will be awakened by a signal if there
          // is anything for this thread to do

          sleep(1);

          // We woke up here either because the one second elapsed or because we
          // were signalled.  In either case we need to check the conditions and
          // determine what to do next.
        }

      // We are going to collect a sample..
      //
      // The sample pointer can change dynamically let's sample it once
      // and stick with that pointer.

      struct touch_sample_s *sample = This->m_touch;

      // Read one touchscreen sample

      vdbg("Listening for sample %p\n", sample);
      DEBUGASSERT(sample);
      ssize_t nbytes = read(This->m_touchFd, sample,
                            sizeof(struct touch_sample_s));

      // Check for errors

      if (nbytes < 0)
        {
          // The only expect error is to be interrupt by a signal
#ifdef CONFIG_DEBUG
          int errval = errno;

          dbg("read %s failed: %d\n",
              CONFIG_NXWM_TOUCHSCREEN_DEVPATH, errval);
          DEBUGASSERT(errval == EINTR);
#endif
        }

      // On a truly successful read, the size of the returned data will
      // be greater than or equal to size of one touchscreen sample.  It
      // be greater only in the case of a multi-touch touchscreen device
      // when multi-touches are reported.

      else if (nbytes >= (ssize_t)sizeof(struct touch_sample_s))
        {
          // Looks like good touchscreen input... process it

          This->handleMouseInput(sample);
        }
      else
        {
          dbg("ERROR Unexpected read size=%d, expected=%d\n",
              nbytes, sizeof(struct touch_sample_s));
        }
    }

  // We should get here only if we were asked to terminate via
  // m_state = LISTENER_STOPREQUESTED

  vdbg("Listener exiting\n");
  This->m_state = LISTENER_TERMINATED;
  return (FAR void *)0;
}

/**
 *  Inject touchscreen data into NX as mouse intput
 */

void CTouchscreen::handleMouseInput(struct touch_sample_s *sample)
{
  vdbg("Touch id: %d flags: %02x x: %d y: %d h: %d w: %d pressure: %d\n",
       sample->point[0].id, sample->point[0].flags, sample->point[0].x,
       sample->point[0].y,  sample->point[0].h,     sample->point[0].w,
       sample->point[0].pressure);

  // Verify the touchscreen data

  if (sample->npoints < 1 ||
      ((sample->point[0].flags & TOUCH_POS_VALID) == 0 &&
       (sample->point[0].flags & TOUCH_UP) == 0))
    {
      // The pen is (probably) down, but we have do not have valid
      // X/Y position data to report.  This should not happen.

      return;
    }

  // Was this data captured by some external logic? (probably the
  // touchscreen calibration logic)

  if (m_capture && sample != &m_sample)
    {
      // Yes.. let waitRawTouchData know that the data is available
      // and restore normal buffering

      m_touch   = &m_sample;
      m_capture = false;
      sem_post(&m_waitSem);
      return;
    }

  // Sanity checks.  Re-directed touch data should never reach this point.
  // After posting m_waitSem, m_touch might change asynchronously.

  DEBUGASSERT(sample == &m_sample);

  // Check if normal processing of touchscreen data is enabled.  Check if
  // we have been given calibration data.

  if (!m_enabled || !m_calibrated)
    {
      // No.. we are not yet ready to process touchscreen data (We don't
      // really every get to this condition.

      return;
    }

  // Now we will inject the touchscreen into NX as mouse input.  First
  // massage the data a little so that it behaves a little more like a
  // mouse with only a left button
  //
  // Was the button up or down?

  uint8_t buttons;
  if ((sample->point[0].flags & (TOUCH_DOWN | TOUCH_MOVE)) != 0)
    {
      buttons = NX_MOUSE_LEFTBUTTON;
    }
  else if ((sample->point[0].flags & TOUCH_UP) != 0)
    {
      buttons = NX_MOUSE_NOBUTTONS;
    }
  else
    {
      // The pen is neither up nor down. This should not happen

      return;
    }

  // Get the "raw" touch coordinates (if they are valid)

  nxgl_coord_t x;
  nxgl_coord_t y;

  if ((sample->point[0].flags & TOUCH_POS_VALID) == 0)
    {
       x = 0;
       y = 0;
    }
  else
    {
#ifdef CONFIG_NXWM_CALIBRATION_ANISOTROPIC
      // We have valid coordinates.  Get the raw touch
      // position from the sample

      float rawX = (float)sample->point[0].x;
      float rawY = (float)sample->point[0].y;

      // Create a line (varying in X) that have the same matching Y values
      // X lines:
      //
      //   x2 = slope*y1 + offset
      //
      // X value calculated on the left side for the given value of y

      float leftX  = rawY * m_calibData.left.slope + m_calibData.left.offset;

      // X value calculated on the right side for the given value of y

      float rightX = rawY * m_calibData.right.slope + m_calibData.right.offset;

      // Line of X values between (m_calibData.leftX,leftX) and (m_calibData.rightX,rightX) the
      // are possible solutions:
      //
      //  x2 = slope * x1 - offset

      struct SCalibrationLine xLine;
      xLine.slope  = (float)((int)m_calibData.rightX - (int)m_calibData.leftX) / (rightX - leftX);
      xLine.offset = (float)m_calibData.leftX - leftX * xLine.slope;

      // Create a line (varying in Y) that have the same matching X value
      // X lines:
      //
      //   y2 = slope*x1 + offset
      //
      // Y value calculated on the top side for a given value of X

      float topY = rawX * m_calibData.top.slope + m_calibData.top.offset;

      // Y value calculated on the bottom side for a give value of X

      float bottomY = rawX * m_calibData.bottom.slope + m_calibData.bottom.offset;

      // Line of Y values between (topy,m_calibData.topY) and (bottomy,m_calibData.bottomY) that
      // are possible solutions:
      //
      //  y2 = slope * y1 - offset

      struct SCalibrationLine yLine;
      yLine.slope  = (float)((int)m_calibData.bottomY - (int)m_calibData.topY) / (bottomY - topY);
      yLine.offset = (float)m_calibData.topY - topY * yLine.slope;

      // Then scale the raw x and y positions

      float scaledX = rawX * xLine.slope + xLine.offset;
      float scaledY = rawY * yLine.slope + yLine.offset;

      x = (nxgl_coord_t)scaledX;
      y = (nxgl_coord_t)scaledY;

      vdbg("raw: (%6.2f, %6.2f) scaled: (%6.2f, %6.2f) (%d, %d)\n",
           rawX, rawY, scaledX, scaledY, x, y);
#else
      // We have valid coordinates.  Get the raw touch
      // position from the sample

      uint32_t rawX = (uint32_t)sample->point[0].x;
      uint32_t rawY = (uint32_t)sample->point[0].y;

      // Get the fixed precision, scaled X and Y values

      b16_t scaledX = rawX * m_calibData.xSlope + m_calibData.xOffset;
      b16_t scaledY = rawY * m_calibData.ySlope + m_calibData.yOffset;

      // Get integer scaled X and Y positions and clip
      // to fix in the window

      int32_t bigX = b16toi(scaledX + b16HALF);
      int32_t bigY = b16toi(scaledY + b16HALF);

      // Clip to the display

      if (bigX < 0)
        {
          x = 0;
        }
      else if (bigX >= m_windowSize.w)
        {
          x = m_windowSize.w - 1;
        }
      else
        {
          x = (nxgl_coord_t)bigX;
        }

      if (bigY < 0)
        {
          y = 0;
        }
      else if (bigY >= m_windowSize.h)
        {
          y = m_windowSize.h - 1;
        }
      else
        {
          y = (nxgl_coord_t)bigY;
        }

      vdbg("raw: (%d, %d) scaled: (%d, %d)\n", rawX, rawY, x, y);
#endif
    }

  // Get the server handle and "inject the mouse data

  NXHANDLE handle = m_server->getServer();
  (void)nx_mousein(handle, x, y, buttons);
}