File: routing.c

package info (click to toggle)
brltty 6.9-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 44,828 kB
  • sloc: ansic: 154,246; java: 13,514; sh: 9,934; xml: 5,672; tcl: 2,679; makefile: 2,346; awk: 713; lisp: 366; python: 321; ml: 301
file content (648 lines) | stat: -rw-r--r-- 17,337 bytes parent folder | download | duplicates (2)
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/*
 * BRLTTY - A background process providing access to the console screen (when in
 *          text mode) for a blind person using a refreshable braille display.
 *
 * Copyright (C) 1995-2025 by The BRLTTY Developers.
 *
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU Lesser General Public License, as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any
 * later version. Please see the file LICENSE-LGPL for details.
 *
 * Web Page: http://brltty.app/
 *
 * This software is maintained by Dave Mielke <dave@mielke.cc>.
 */

#include "prologue.h"

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>

#include "parameters.h"
#include "log.h"
#include "async_alarm.h"
#include "async_handle.h"
#include "timing.h"
#include "scr.h"
#include "routing.h"
#include "embed.h"

typedef enum {
  CRR_DONE,
  CRR_NEAR,
  CRR_FAIL
} RoutingResult;

typedef enum {
  CURSOR_DIR_LEFT,
  CURSOR_DIR_RIGHT,
  CURSOR_DIR_UP,
  CURSOR_DIR_DOWN
} CursorDirection;

typedef struct {
  const char *name;
  ScreenKey key;
} CursorDirectionEntry;

static const CursorDirectionEntry cursorDirectionTable[] = {
  [CURSOR_DIR_LEFT]  = {.name="left" , .key=SCR_KEY_CURSOR_LEFT },
  [CURSOR_DIR_RIGHT] = {.name="right", .key=SCR_KEY_CURSOR_RIGHT},
  [CURSOR_DIR_UP]    = {.name="up"   , .key=SCR_KEY_CURSOR_UP   },
  [CURSOR_DIR_DOWN]  = {.name="down" , .key=SCR_KEY_CURSOR_DOWN }
};

typedef enum {
  CURSOR_AXIS_HORIZONTAL,
  CURSOR_AXIS_VERTICAL
} CursorAxis;

typedef struct {
  const CursorDirectionEntry *forward;
  const CursorDirectionEntry *backward;
} CursorAxisEntry;

static const CursorAxisEntry cursorAxisTable[] = {
  [CURSOR_AXIS_HORIZONTAL] = {
    .forward  = &cursorDirectionTable[CURSOR_DIR_RIGHT],
    .backward = &cursorDirectionTable[CURSOR_DIR_LEFT]
  }
  ,
  [CURSOR_AXIS_VERTICAL] = {
    .forward  = &cursorDirectionTable[CURSOR_DIR_DOWN],
    .backward = &cursorDirectionTable[CURSOR_DIR_UP]
  }
};

typedef enum {
  RS_IDLE,
  RS_INITIAL_POSITION,
  RS_ADJUSTING,
  RS_WAITING_FOR_MOTION,
  RS_COMPLETED
} RoutingState;

typedef enum {
  RP_INITIAL_VERTICAL,
  RP_INITIAL_HORIZONTAL,
  RP_RETRY_VERTICAL,
  RP_RETRY_HORIZONTAL_FINAL
} RoutingPhase;

typedef struct {
  RoutingState state;
  RoutingPhase phase;

  struct {
    int column;
    int row;
    int screen;
  } target;

  struct {
    int number;
    int width;
    int height;
  } screen;

  struct {
    int scroll;
    int row;
    ScreenCharacter *buffer;
  } vertical;

  struct {
    int column;
    int row;
  } current;

  struct {
    int column;
    int row;
  } previous;

  struct {
    long sum;
    int count;
  } time;

  struct {
    TimeValue start;
    long timeout;
    int hasMoved;
    int direction;
    const CursorAxisEntry *axis;
    int where;
    int targetRow;
    int targetColumn;
  } motion;

  RoutingStatus status;
  AsyncHandle timeoutAlarm;
} RoutingContext;

static RoutingContext routingContext = {
  .state = RS_IDLE
};

#define logRouting(...) logMessage(LOG_CATEGORY(CURSOR_ROUTING), __VA_ARGS__)

static void completeRouting(RoutingStatus status);
static void processRoutingStateMachine(void);
static RoutingResult evaluateCursorMotion(RoutingContext *ctx);

static int
readRow (RoutingContext *ctx, ScreenCharacter *buffer, int row) {
  if (!buffer) buffer = ctx->vertical.buffer;
  if (readScreenRow(row, ctx->screen.width, buffer)) return 1;
  logRouting("read failed: row=%d", row);
  return 0;
}

static int
getCurrentPosition (RoutingContext *ctx) {
  ScreenDescription description;
  describeScreen(&description);

  if (description.number != ctx->screen.number) {
    logRouting("screen changed: %d -> %d", ctx->screen.number, description.number);
    ctx->screen.number = description.number;
    return 0;
  }

  if (!ctx->vertical.buffer) {
    ctx->screen.width = description.cols;
    ctx->screen.height = description.rows;
    ctx->vertical.scroll = 0;

    if (!(ctx->vertical.buffer = malloc(ARRAY_SIZE(ctx->vertical.buffer, ctx->screen.width)))) {
      logMallocError();
      goto error;
    }

    logRouting("screen: num=%d cols=%d rows=%d",
               ctx->screen.number,
               ctx->screen.width, ctx->screen.height);
  } else if ((ctx->screen.width != description.cols) ||
             (ctx->screen.height != description.rows)) {
    logRouting("size changed: %dx%d -> %dx%d",
               ctx->screen.width, ctx->screen.height,
               description.cols, description.rows);
    goto error;
  }

  ctx->current.row = description.posy + ctx->vertical.scroll;
  ctx->current.column = description.posx;
  return 1;

error:
  ctx->screen.number = -1;
  return 0;
}

static void
handleVerticalScrolling (RoutingContext *ctx, int direction) {
  int firstRow = ctx->vertical.row;
  int currentRow = firstRow;

  int bestRow = firstRow;
  int bestLength = 0;

  do {
    ScreenCharacter buffer[ctx->screen.width];
    if (!readRow(ctx, buffer, currentRow)) break;

    int length;
    {
      int before = ctx->current.column;
      int after = before;

      while (buffer[before].text == ctx->vertical.buffer[before].text)
        if (--before < 0)
          break;

      while (buffer[after].text == ctx->vertical.buffer[after].text)
        if (++after >= ctx->screen.width)
          break;

      length = after - before - 1;
    }

    if (length > bestLength) {
      bestRow = currentRow;
      if ((bestLength = length) == ctx->screen.width) break;
    }

    currentRow -= direction;
  } while ((currentRow >= 0) && (currentRow < ctx->screen.height));

  int delta = bestRow - firstRow;
  ctx->vertical.scroll -= delta;
  ctx->current.row -= delta;
}

static void
startMotionTimeout(RoutingContext *ctx) {
  long timeout = ctx->time.sum / ctx->time.count;

  if (ctx->timeoutAlarm) {
    asyncCancelRequest(ctx->timeoutAlarm);
  }

  getMonotonicTime(&ctx->motion.start);
  ctx->motion.timeout = timeout;
  ctx->motion.hasMoved = 0;
}

ASYNC_ALARM_CALLBACK(handleRoutingTimeout) {
  RoutingContext *ctx = &routingContext;

  asyncDiscardHandle(ctx->timeoutAlarm);
  ctx->timeoutAlarm = NULL;

  logRouting("timeout: cursor did not move within %ldms", ctx->motion.timeout);

  // Cursor didn't move - treat this as reaching the nearest position
  handleVerticalScrolling(ctx, ctx->motion.direction);

  // Evaluate the result - cursor stuck means we're as close as we can get
  RoutingResult result = evaluateCursorMotion(ctx);

  if (result == CRR_NEAR || result == CRR_FAIL) {
    // Can't get closer or failed
    if (ctx->current.row != ctx->target.row) {
      completeRouting(ROUTING_STATUS_ROW);
    } else if (ctx->current.column != ctx->target.column) {
      completeRouting(ROUTING_STATUS_COLUMN);
    } else {
      completeRouting(ROUTING_STATUS_FAILURE);
    }
  } else {
    // CRR_DONE - shouldn't happen in timeout, but handle it
    ctx->state = RS_ADJUSTING;
    processRoutingStateMachine();
  }
}

static int
moveCursor (RoutingContext *ctx, const CursorDirectionEntry *direction) {
  ctx->vertical.row = ctx->current.row - ctx->vertical.scroll;
  if (!readRow(ctx, NULL, ctx->vertical.row)) return 0;

  logRouting("move: %s", direction->name);
  insertScreenKey(direction->key);

  return 1;
}

static RoutingResult
evaluateCursorMotion(RoutingContext *ctx) {
  int trgy = ctx->motion.targetRow;
  int trgx = ctx->motion.targetColumn;
  int where = ctx->motion.where;
  int dir = ctx->motion.direction;

  if (ctx->current.row != ctx->previous.row) {
    if (ctx->previous.row != trgy) {
      if (((ctx->current.row - ctx->previous.row) * dir) > 0) {
        int dif = trgy - ctx->current.row;
        int dify = trgy - ctx->previous.row;
        if ((dif * dify) >= 0) return CRR_DONE; // Continue moving
        if (where > 0) {
          if (ctx->current.row > trgy) return CRR_NEAR;
        } else if (where < 0) {
          if (ctx->current.row < trgy) return CRR_NEAR;
        } else {
          if ((dif * dif) < (dify * dify)) return CRR_NEAR;
        }
      }
    }
  } else if (ctx->current.column != ctx->previous.column) {
    if (((ctx->current.column - ctx->previous.column) * dir) > 0) {
      int dif = trgx - ctx->current.column;
      int difx = trgx - ctx->previous.column;
      if (ctx->current.row != trgy) return CRR_DONE; // Continue
      if ((dif * difx) >= 0) return CRR_DONE; // Continue
      if (where > 0) {
        if (ctx->current.column > trgx) return CRR_NEAR;
      } else if (where < 0) {
        if (ctx->current.column < trgx) return CRR_NEAR;
      } else {
        if ((dif * dif) < (difx * difx)) return CRR_NEAR;
      }
    }
  } else {
    // Cursor didn't move at all
    return CRR_NEAR;
  }

  // Getting farther - try going back
  if (!moveCursor(ctx, ((dir > 0)? ctx->motion.axis->backward: ctx->motion.axis->forward))) {
    return CRR_FAIL;
  }

  ctx->motion.direction = -dir;
  ctx->state = RS_WAITING_FOR_MOTION;
  startMotionTimeout(ctx);

  // Schedule timeout alarm
  asyncNewRelativeAlarm(&ctx->timeoutAlarm, ctx->motion.timeout,
                        handleRoutingTimeout, NULL);

  return CRR_NEAR; // Will be handled after motion
}

static void
startCursorAdjustment(RoutingContext *ctx, int where, int trgy, int trgx,
                      const CursorAxisEntry *axis) {
  logRouting("to: [%d,%d]", trgx, trgy);

  ctx->motion.where = where;
  ctx->motion.targetRow = trgy;
  ctx->motion.targetColumn = trgx;
  ctx->motion.axis = axis;

  int dify = trgy - ctx->current.row;
  int difx = (trgx < 0)? 0: (trgx - ctx->current.column);
  int dir;

  if (dify) {
    dir = (dify > 0)? 1: -1;
  } else if (difx) {
    dir = (difx > 0)? 1: -1;
  } else {
    // Already at target
    processRoutingStateMachine();
    return;
  }

  ctx->motion.direction = dir;

  if (!moveCursor(ctx, ((dir > 0)? axis->forward: axis->backward))) {
    completeRouting(ROUTING_STATUS_FAILURE);
    return;
  }

  ctx->previous.column = ctx->current.column;
  ctx->previous.row = ctx->current.row;
  ctx->state = RS_WAITING_FOR_MOTION;

  startMotionTimeout(ctx);

  // Schedule timeout alarm
  asyncNewRelativeAlarm(&ctx->timeoutAlarm, ctx->motion.timeout,
                        handleRoutingTimeout, NULL);
}

static void
processRoutingStateMachine(void) {
  RoutingContext *ctx = &routingContext;

  switch (ctx->state) {
    case RS_IDLE:
      // Nothing to do
      break;

    case RS_INITIAL_POSITION:
      if (!getCurrentPosition(ctx)) {
        completeRouting(ROUTING_STATUS_FAILURE);
        return;
      }

      logRouting("from: [%d,%d]", ctx->current.column, ctx->current.row);

      if (ctx->target.column < 0) {
        // Only adjust vertical
        ctx->phase = RP_INITIAL_VERTICAL;
        ctx->state = RS_ADJUSTING;
        startCursorAdjustment(ctx, 0, ctx->target.row, -1,
                            &cursorAxisTable[CURSOR_AXIS_VERTICAL]);
      } else {
        // Start with vertical adjustment
        ctx->phase = RP_INITIAL_VERTICAL;
        ctx->state = RS_ADJUSTING;
        startCursorAdjustment(ctx, -1, ctx->target.row, -1,
                            &cursorAxisTable[CURSOR_AXIS_VERTICAL]);
      }
      break;

    case RS_ADJUSTING: {
      // Check if we reached the target
      int dify = ctx->motion.targetRow - ctx->current.row;
      int difx = (ctx->motion.targetColumn < 0)? 0:
                 (ctx->motion.targetColumn - ctx->current.column);

      if (!dify && !difx) {
        // Reached exact target
        if (ctx->phase == RP_INITIAL_VERTICAL && ctx->target.column >= 0) {
          // Move to horizontal adjustment
          ctx->phase = RP_INITIAL_HORIZONTAL;
          startCursorAdjustment(ctx, 0, ctx->target.row, ctx->target.column,
                              &cursorAxisTable[CURSOR_AXIS_HORIZONTAL]);
        } else {
          completeRouting(ROUTING_STATUS_SUCCEESS);
        }
        return;
      }

      // Need to continue adjusting - inject next movement
      int dir = ctx->motion.direction;
      if (!moveCursor(ctx, ((dir > 0)? ctx->motion.axis->forward:
                                       ctx->motion.axis->backward))) {
        completeRouting(ROUTING_STATUS_FAILURE);
        return;
      }

      ctx->previous.column = ctx->current.column;
      ctx->previous.row = ctx->current.row;
      ctx->state = RS_WAITING_FOR_MOTION;

      startMotionTimeout(ctx);
      asyncNewRelativeAlarm(&ctx->timeoutAlarm, ctx->motion.timeout,
                           handleRoutingTimeout, NULL);
      break;
    }

    case RS_WAITING_FOR_MOTION:
      // Should not be called in this state - wait for cursor change or timeout
      break;

    case RS_COMPLETED:
      // Already completed
      break;
  }
}

static void
completeRouting(RoutingStatus status) {
  RoutingContext *ctx = &routingContext;

  if (ctx->timeoutAlarm) {
    asyncCancelRequest(ctx->timeoutAlarm);
    ctx->timeoutAlarm = NULL;
  }

  // Check final position
  if (ctx->screen.number != ctx->target.screen) {
    status = ROUTING_STATUS_FAILURE;
  } else if (status == ROUTING_STATUS_SUCCEESS) {
    if (ctx->current.row != ctx->target.row) {
      status = ROUTING_STATUS_ROW;
    } else if ((ctx->target.column >= 0) &&
               (ctx->current.column != ctx->target.column)) {
      status = ROUTING_STATUS_COLUMN;
    }
  }

  logRouting("completed: status=%d at [%d,%d]", status,
             ctx->current.column, ctx->current.row);

  ctx->status = status;
  ctx->state = RS_COMPLETED;

  // Wake up the main loop to process the completion
  brlttyInterrupt(WAIT_CONTINUE);
}

static void
cleanupRoutingContext(void) {
  if (routingContext.vertical.buffer) {
    free(routingContext.vertical.buffer);
    routingContext.vertical.buffer = NULL;
  }

  if (routingContext.timeoutAlarm) {
    asyncCancelRequest(routingContext.timeoutAlarm);
    routingContext.timeoutAlarm = NULL;
  }

  routingContext.state = RS_IDLE;
}

void
onCursorPositionChanged(void) {
  RoutingContext *ctx = &routingContext;

  if (ctx->state != RS_WAITING_FOR_MOTION) return;

  int oldX = ctx->current.column;
  int oldY = ctx->current.row;

  if (!getCurrentPosition(ctx)) {
    completeRouting(ROUTING_STATUS_FAILURE);
    return;
  }

  if ((ctx->current.row == oldY) && (ctx->current.column == oldX)) {
    // Position hasn't changed yet
    return;
  }

  // Cursor moved!
  if (ctx->timeoutAlarm) {
    asyncCancelRequest(ctx->timeoutAlarm);
    ctx->timeoutAlarm = NULL;
  }

  TimeValue now;
  getMonotonicTime(&now);
  long int time = millisecondsBetween(&ctx->motion.start, &now) + 1;

  logRouting("moved: [%d,%d] -> [%d,%d] (%ldms)",
             oldX, oldY, ctx->current.column, ctx->current.row, time);

  if (!ctx->motion.hasMoved) {
    ctx->motion.hasMoved = 1;
    ctx->motion.timeout = (time * 2) + 1;

    ctx->time.sum += time * 8;
    ctx->time.count += 1;
  }

  handleVerticalScrolling(ctx, ctx->motion.direction);

  // Evaluate if we should continue or if we've reached near enough
  RoutingResult result = evaluateCursorMotion(ctx);

  if (result == CRR_NEAR) {
    // Check phase and decide next action
    if (ctx->phase == RP_INITIAL_HORIZONTAL && ctx->current.row < ctx->target.row) {
      // Try moving down one more row and retry horizontal
      ctx->phase = RP_RETRY_VERTICAL;
      ctx->state = RS_ADJUSTING;
      startCursorAdjustment(ctx, 1, ctx->current.row + 1, -1,
                          &cursorAxisTable[CURSOR_AXIS_VERTICAL]);
      return;
    } else if (ctx->phase == RP_RETRY_VERTICAL) {
      // Try horizontal again
      ctx->phase = RP_RETRY_HORIZONTAL_FINAL;
      ctx->state = RS_ADJUSTING;
      startCursorAdjustment(ctx, 0, ctx->target.row, ctx->target.column,
                          &cursorAxisTable[CURSOR_AXIS_HORIZONTAL]);
      return;
    }

    // Can't get closer
    if (ctx->current.row != ctx->target.row) {
      completeRouting(ROUTING_STATUS_ROW);
    } else {
      completeRouting(ROUTING_STATUS_COLUMN);
    }
  } else if (result == CRR_FAIL) {
    completeRouting(ROUTING_STATUS_FAILURE);
  } else {
    // CRR_DONE - continue adjusting
    ctx->state = RS_ADJUSTING;
    processRoutingStateMachine();
  }
}

int
startRouting(int column, int row, int screen) {
  // Cancel any existing routing
  if (routingContext.state != RS_IDLE) {
    cleanupRoutingContext();
  }

  // Initialize context
  routingContext.state = RS_INITIAL_POSITION;
  routingContext.phase = RP_INITIAL_VERTICAL;
  routingContext.target.column = column;
  routingContext.target.row = row;
  routingContext.target.screen = screen;
  routingContext.screen.number = screen;
  routingContext.vertical.buffer = NULL;
  routingContext.time.sum = ROUTING_MAXIMUM_TIMEOUT;
  routingContext.time.count = 1;
  routingContext.status = ROUTING_STATUS_NONE;
  routingContext.timeoutAlarm = NULL;

  logRouting("start: target=[%d,%d] screen=%d", column, row, screen);

  // Start the state machine
  processRoutingStateMachine();

  return 1;
}

int
isRouting(void) {
  return routingContext.state != RS_IDLE &&
         routingContext.state != RS_COMPLETED;
}

RoutingStatus
getRoutingStatus(int wait) {
  if (routingContext.state == RS_COMPLETED) {
    RoutingStatus status = routingContext.status;
    cleanupRoutingContext();
    return status;
  }

  return ROUTING_STATUS_NONE;
}