-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrealtime_annotate.py
executable file
·2254 lines (1787 loc) · 80 KB
/
realtime_annotate.py
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Some comments are prefixed by a number of "!" marks: they indicate
# some notable comments (more exclamation marks indicate more
# important comments).
"""
Real-time annotation tool.
Annotations are timestamped. They contain user-defined values.
Optionally, some real-time player (music player, video player, MIDI
player,...) can be controlled so that annotation timestamps are
synchronized with the player (the player time head is automatically
set to the annotation timestamp; the player is started and stopped at
the same times as the annotation process).
(c) 2015–2018 by Eric O. LEBIGOT (EOL)
"""
__version__ = "1.6.4"
__author__ = "Eric O. LEBIGOT (EOL) <[email protected]>"
# !! The optional player driven by this program must be defined by
# functions in a module stored in a variable named player_module. See
# the main program for two examples.
import collections
import pathlib
import cmd
import datetime
import shutil
import atexit
import curses # For Windows, maybe UniCurses would work
import time
import sched
import bisect
import sys
import glob
import json
import re
import tempfile
import subprocess
import os
import functools
import logging
logging.basicConfig(
# filename='realtime_annotate.log',
# filemode="w",
level=logging.INFO)
if sys.version_info < (3, 4):
sys.exit("This program requires Python 3.4+, sorry.")
try:
import readline # Optional
except ImportError: # Standard modules do not have to be all installed
pass
else:
# There is no need to complete on "-", for instance (the shell is
# not a programming shell):
readline.set_completer_delims(" ")
def has_text(text):
"""
Return False if the text is empty or has only spaces.
A true value is returned otherwise.
"""
# This is faster than "not text.rstrip()" because no new string is
# built.
return text and not text.isspace()
## Definition of a file locking function lock_file():
class FileLocked(OSError):
"""
Raised when a file is locked.
"""
# Testing for os.name is less robust than testing for the modules
# that are needed:
# The file must be kept open for the lock to remain active. Since we
# keep the lock for the duration of this program, there is no need to
# keep track of the file in order to unlock it later (the lock is
# released when the file closes, which happens automatically when this
# program exits):
lock_file_doc = """
Cooperatively lock the file at the given path.
Returns a value that must be kept in memory so that the lock not be
released.
Raises a FileLocked exception if the lock cannot
be obtained."""
try:
import fcntl
def lock_file(file_path):
locked_file = open(file_path, "r+")
try:
fcntl.flock(locked_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, PermissionError):
raise FileLocked
return locked_file
lock_file.__doc__ = lock_file_doc
except ImportError:
try:
# !!!! This part of the code is for Windows and is therefore currently
# irrelevant, because the curses library is required, which doesn't
# work on Windows. However, it is left here as a reference in case
# of a future Windows version.
import msvcrt
def lock_file(file_path):
# !!! WARNING: this function is yet untested
locked_file = open(file_path, "r+")
try:
msvcrt.locking(locked_file.fileno, msvcrt.LK_NBLCK, 1)
except OSError:
raise FileLocked
return locked_file
lock_file.__doc__ = lock_file_doc
except ImportError:
# No file locking available:
lock_file = lambda file_path: None
# Delay after the time of the last displayed annotation during which
# the back arrow command is interpreted as meaning to go past the last
# annotation time (this delay must be larger than the delay between repeated
# keys that the program receives, or the user might never be able to navigate
# backwards in time with the back arrow):
BACK_ARROW_THRESHOLD = datetime.timedelta(seconds=1)
# Time step when moving backward and forward in time during the
# annotation process (with the keys):
NAVIG_STEP = datetime.timedelta(seconds=2)
class Time(datetime.timedelta):
# ! A datetime.timedelta is used instead of a datetime.time
# because the internal scheduler of this program must be added to
# the current annotation timestamp so as to update it. This cannot
# be done with datetime.time objects (which cannot be added to a
# timedelta).
"""
Timestamps that can be added and subtracted.
They are also compatible with datetime.timedelta objects.
"""
def to_HMS(self):
"""
Returns the time as a tuple (hours, minutes, seconds), with
seconds and minutes between 0 and 60 (not included). The
number of hours has no limit.
Hours and minutes are integers.
Not tested with a negative duration.
This can be inverted with Time(hours=..., minutes=..., seconds=...).
"""
total_seconds = self.days*24*3600+self.seconds+self.microseconds/1e6
(hours, minutes) = divmod(total_seconds, 3600)
(minutes, seconds) = divmod(minutes, 60)
return (int(hours), int(minutes), seconds)
# Factory function:
@classmethod
def from_HMS(cls, HMS):
"""
Return an instance from a simple (hour, minute, seconds) sequence.
HMS -- (hour, minutes, seconds) iterable, with possibly missing
last elements.
"""
return cls(**dict(zip(("hours", "minutes", "seconds"), HMS)))
@classmethod
def from_timedelta(cls, timedelta):
"""
Return a object of this class from a datetime.timedelta object.
"""
return cls(timedelta.days, timedelta.seconds, timedelta.microseconds)
def __str__(self):
"""
...HH:MM:SS.d format.
"""
return "{:02}:{:02}:{:04.1f}".format(*self.to_HMS())
def __repr__(self):
"""
...HH:MM:S format.
"""
return "{:02}:{:02}:{}".format(*self.to_HMS())
def __sub__(self, other):
"""
Subtraction.
Returns an object of the same class (as self).
other -- datetime.timedelta.
"""
# ! We do not rely on __sub__() from datetime.timedelta because
# it forces the result to be a datetime.timedelta (where we
# want a Time object):
return self + (-other)
def __add__(self, other):
"""
Addition.
Return an object of the same class (as self).
other -- object to which a datetime.timedelta can be added.
"""
new_time = super().__add__(other)
# ! A datetime.timedelta apparently does not return an element of the
# type of self when adding to it, so this is done manually here:
#
# ! The class of the object cannot be changed, because it is a built-in
# or extension type, so we build a new object:
return self.from_timedelta(new_time)
class TimestampedAnnotation:
"""
Annotation made at a specific time.
Main attributes:
- time (datetime.timedelta)
- annotation ([key, index_in_history] pair)
A value can be added to the annotation. It is stored in the
optional 'value' attribute. This is typically used for indicating
an intensity (such as a small glitch, or a very uninspired
part). A merit of this approach is that there is no restriction on
the contents of value (which can be None, etc.). Another merit is
that only annotations that have a value store one (in memory, on
disk, etc.).
"""
def __init__(self, timestamp, annotation):
"""
timestamp -- timestamp for the annotation, as a datetime.timedelta.
annotation -- annotation to be stored, as a [key,
index_in_history] pair.
"""
self.time = timestamp
self.annotation = annotation
def set_value(self, value):
# !! This method exists mostly as a way of showing through
# code that the value attribute can be set (it is optional,
# and not set in __init__()).
"""
Set the annotation's value.
"""
self.value = value
def __str__(self):
result = "{} {}".format(self.time, self.annotation)
if hasattr(self, "value"):
result += " [value {}]".format(self.value)
return result
def to_builtins_fmt(self):
"""
Return a version of the annotation with only Python builtin types
(with no module dependency).
This is useful for serializing the annotation (e.g. for JSON).
Returns (time, annot), where time is an (hours, minutes, seconds)
sequence, and where annot is [annotation] or [annotation, value], if a
value is defined for the TimestampedAnnotation.
"""
annotation = [self.annotation]
if hasattr(self, "value"):
annotation.append(self.value)
return [self.time.to_HMS(), annotation]
@classmethod
def from_builtins_fmt(cls, timed_annotation):
"""
Reverse of to_builtins_fmt().
timed_annotation -- version of the annotation, as returned for
instance by to_builtins_fmt().
"""
annot = timed_annotation[1] # [ [key, index], optional_value ]
result = cls(Time.from_HMS(timed_annotation[0]), annot[0])
if len(annot) > 1: # Optional value associated with annotation
result.set_value(annot[1])
return result
class NoAnnotation(Exception):
"""
Raised when a requested annotation cannot be found.
"""
class TerminalNotHighEnough(Exception):
"""
Raised when the terminal is not high enough for a proper display.
"""
class EventData:
"""
Data associated to an event.
The event data is:
- list of annotations (for a single reference) sorted by timestamp,
- a live insertion cursor between annotations,
- text notes associated with the event.
An event is considered true if it contains either annotations or a
non-empty note.
Main attributes:
- list_: list of TimestampedAnnotations, sorted by increasing
timestamps. List-like operations on this list can be performed
directly on the EventData: len(), subscripting, and
iteration.
- cursor: index between annotations (0 = before the first
annotation, positive). The cursor corresponds to a time between
the two annotations (their timestamp included, since they can have
the same timestamp).
- note: string with the note associated with the event. Trailing whitespace
is automatically removed.
"""
def __init__(self, list_=None, cursor=0, note=""):
"""
list_ -- list of TimestampedAnnotations.
cursor -- insertion index for the next annotation.
"""
self.list_ = [] if list_ is None else list_
self.cursor = cursor
self.note = note # Note associated with the event
def __len__(self):
return len(self.list_)
def __getitem__(self, slice_):
"""
Return the annotations from the given slice.
"""
return self.list_[slice_]
def __bool__(self):
"""
Return True iff there are annotations or the note is not empty.
"""
return bool(self.list_) or bool(self.note)
def __iter__(self):
return iter(self.list_)
def set_cursor_at_time(self, timestamp):
"""
Set the internal cursor so that an annotation at the given
time would be inserted in timestamp order.
The cursor is put *after* any annotation with the same time
stamp.
timestamp -- the cursor is put between two annotations, so
that the given timestamp is between their timestamps.
"""
self.cursor = bisect.bisect(
[annotation.time for annotation in self], timestamp)
def cursor_skipping_prev_time(self):
"""
Return the cursor for the (last) annotation just before the time
of prev_annotation().
If this does not exist, returns None.
This typically returns self.cursor-2, but it more generally
returns self.cursor - ( 1 + number of annotations at the last
annotation time before self.cursor), unless this is negative (in which
case None is returned).
"""
# Time of the previous annotation:
prev_annotation = self.prev_annotation()
if prev_annotation is None:
return None # The cursor is at the first annotation
cursor_before_prev_time = bisect.bisect_left(
[annotation.time for annotation in self],
prev_annotation.time)
if cursor_before_prev_time < 1:
return None # No annotation before prev_annotation.time
return cursor_before_prev_time-1
def next_annotation(self):
"""
Return the first annotation after the cursor, or None if there
is none.
"""
try:
return self[self.cursor]
except IndexError:
return None
def prev_annotation(self):
"""
Return the annotation just before the cursor, or None if there
is none.
"""
return self[self.cursor-1] if self.cursor >= 1 else None
def insert(self, annotation):
"""
Insert the given annotation at the cursor location and moves
it to after the inserted annotation (so that a next insert()
on the next annotation in time puts it in the right place in
the list).
The cursor must be located so that the insertion is done in
timestamp order. Using set_cursor_at_time(annotation.time) does this
(but this call is not required, as the cursor can be set by
other means too, including outside of this class).
"""
self.list_.insert(self.cursor, annotation)
self.cursor += 1
def delete_prev(self):
"""
Delete the annotation just before the cursor and update the
cursor (which does not move compared to its following
annotation).
This annotation must exist.
"""
self.cursor -= 1
del self.list_[self.cursor]
def to_builtins_fmt(self):
# !!! This function should be updated anytime the annotation saving
# in Annotations.save() is updated.
"""
Return a version of the EventData that only uses built-in
Python types, and which is suitable for lossless serialization
through json.
This is the reverse of from_builtins_fmt().
"""
return {
"cursor": self.cursor,
"annotation_list": [timed_annotation.to_builtins_fmt()
for timed_annotation in self],
"note": self.note
}
@classmethod
def from_builtins_fmt(cls, event_data):
# !!! This function should be updated anytime the annotation saving
# in Annotations.save() is updated.
"""
Reverse of to_builtins_fmt().
event_data -- event data in the form returned by to_builtins_fmt().
"""
return cls(
cursor=event_data["cursor"],
list_=[
TimestampedAnnotation.from_builtins_fmt(annotation)
for annotation in event_data["annotation_list"]
],
note=event_data["note"]
)
def __repr__(self):
return "<{} {}>".format(self.__class__.__qualname__,
self.to_builtins_fmt())
def cancel_sched_events(scheduler, events):
"""
Cancel the scheduled events (except getting the next user key) and
empties their list.
events -- list of events, where each event was returned by a
sched.scheduler. Some events can be already passed.
"""
for event in events:
try:
# Highlighting events are not tracked, so they
# might have passed without this program knowing
# it, which makes the following fail:
scheduler.cancel(event)
except ValueError:
pass
events.clear()
def real_time_loop(stdscr, curr_event_ref, start_time, annotations,
meaning_history, key_assignments):
"""
Run the main real-time annotation loop and return the annotation
time at the time of exit.
Displays and updates the given annotation list based on
single characters entered by the user.
stdscr -- curses.WindowObject for displaying information.
curr_event_ref -- reference of the event (recording...) being annotated.
start_time -- starting annotation time (Time object).
annotations -- EventData to be updated.
meaning_history -- history that contains the text of all the
possible annotations in curr_event_ref, as a mapping from a user
key to the list of its possible text meanings.
key_assignments -- mapping that defines each user key: it maps
current keys to their corresponding index_in_history.
"""
# Events (get user key, transfer the next annotation to the list
# of previous annotations) are handled by the following scheduler:
scheduler = sched.scheduler(time.monotonic)
####################
# Basic settings for the terminal:
## The terminal's default is better than curses's default:
curses.use_default_colors()
## For looping without waiting for the user:
stdscr.nodelay(True)
## No need to see any cursor:
curses.curs_set(0)
## No need to have a cursor displayed at its position:
stdscr.leaveok(True)
####################
# Initializations:
## Terminal size:
(term_lines, term_cols) = stdscr.getmaxyx()
# !!! POSSIBLE FEATURE: Window resizing could be handled, with
# signal.signal(signal.SIGWINCH, resize_handler). This would
# involve drawing the screen again.
def addstr_width(y, x, text, attr=curses.A_NORMAL):
"""
Like stdscr.addstr, but truncates the string so that it does not
go beyond the last column, and so that there is no line
wrapping unless explicit.
text -- string with the text to be displayed. The only newline
can be at the end, and it might be removed if it is too far on
the right.
"""
stdscr.addstr(y, x, text[:term_cols-1-x], attr)
## Annotations cursor:
annotations.set_cursor_at_time(start_time)
####################
# Information display at start:
stdscr.clear()
addstr_width(0, 0, "Event:", curses.A_BOLD)
addstr_width(0, 7, curr_event_ref)
stdscr.hline(1, 0, curses.ACS_HLINE, term_cols)
addstr_width(2, 0, "Next annotation:", curses.A_BOLD)
addstr_width(3, 0, "Annotation timer:", curses.A_BOLD)
stdscr.hline(4, 0, curses.ACS_HLINE, term_cols)
# Help at the bottom of the screen:
help_start_line = term_lines - (len(key_assignments)+6)
stdscr.hline(help_start_line, 0, curses.ACS_HLINE, term_cols)
addstr_width(help_start_line+1, 0, "Commands:\n", curses.A_BOLD)
stdscr.addstr("<Space>: return to shell\n")
stdscr.addstr("<Del>/-: delete previous annotation / value\n")
stdscr.addstr("<4 arrows>, <, >: navigate (annotations and time)\n")
for (key, index) in key_assignments.items():
stdscr.addstr("{} {}\n".format(key, meaning_history[key][index]))
stdscr.addstr("0-9: sets the value of the previous annotation")
## Previous annotations:
## Scrolling region (for previous annotations):
stdscr.scrollok(True)
# Maximum number of previous annotations in window:
prev_annot_height = help_start_line-6
if prev_annot_height < 2:
# !! If the following is a problem, the help could be
# optionally removed OR displayed with a special key, possibly
# even as a window that can appear or disappear.
raise TerminalNotHighEnough
stdscr.setscrreg(6, 5+prev_annot_height)
addstr_width(5, 0, "Previous annotations:", curses.A_BOLD)
####################
# Synchronization between the annotation timer, the scheduler
# timer and the player timer:
# Counters for the event scheduling:
start_counter = time.monotonic()
# Starting the player is better done close to setting
# start_counter, so that there is no large discrepancy between
# the time in the player and this time measured by this
# function:
player_module.start()
def time_to_counter(timestamp):
"""
Return the scheduler counter corresponding to the given
annotation timestamp.
timestamp -- time (datetime.timedelta, including Time).
"""
return (timestamp-start_time).total_seconds() + start_counter
def counter_to_time(counter):
"""
Return the annotation timestamp corresponding to the given
scheduler counter.
counter -- scheduler counter (in seconds).
"""
return start_time + datetime.timedelta(seconds=counter-start_counter)
####################
# Display of annotations
# Annotations require times from the annotation timer, so this
# comes after setting the timers above.
# Utility for convenient displaying the text associated to (the
# internal form of) annotation:
def annot_str(ts_annotation):
"""
Return a string version of given time-stamped annotation, based on
the history in meaning_history.
ts_annotation -- TimestampedAnnotation.
"""
(timestamp, annotation) = (ts_annotation.time,
ts_annotation.annotation)
(key, index) = annotation
meaning = meaning_history[key][index]
value_str = (" [{}]".format(ts_annotation.value)
if hasattr(ts_annotation, "value")
else "")
return "{} {}{}".format(timestamp, meaning, value_str)
# In order to cancel upcoming updates of the next annotation
# (highlight and transfer to the list of previous events), the
# corresponding events are stored in this list:
cancelable_events = []
def display_annotations():
# !! This function is only here so that the code be more organized.
"""
Display the list of previous annotations, and the next annotation.
Schedule the next annotation list update (with the next
annotation going from the next annotation entry to the
previous annotations list).
The lines used for the display must be empty before calling
this function.
"""
# Previous annotations:
## If there is any annotation before the current time:
if annotations.cursor: # The slice below is cumbersome otherwise
slice_end = annotations.cursor-1-prev_annot_height
if slice_end < 0:
slice_end = None # For a Python slice
for (line_idx, annotation) in enumerate(
annotations[annotations.cursor-1 : slice_end :-1], 6):
addstr_width(line_idx, 0, annot_str(annotation))
# stdscr.clrtoeol() # For existing annotations
# else:
# line_idx = 5 # Last "written" line
# # The rest of the lines are erased:
# for line_idx in range(line_idx+1, 5+prev_annot_height):
# stdscr.move(line_idx, 0)
# stdscr.clrtoeol()
display_next_annotation()
def display_next_annotation():
"""
Display the next annotation.
Its highlighting and next scrolling down are scheduled (and
any previously scheduled highlighting and scrolling down is
canceled).
The previous annotation list must be displayed already.
"""
next_annotation = annotations.next_annotation()
# Coordinate for the display (aligned with the running timer):
x_display = 19
# Display
next_annotation_text = (
annot_str(next_annotation)
if next_annotation is not None else "<None>")
addstr_width(2, x_display, next_annotation_text)
stdscr.clrtoeol()
nonlocal cancelable_events
# Any queued event must be canceled, as they are made
# obsolete by the handling of the next annotation
# highlighting and scrolling below:
cancel_sched_events(scheduler, cancelable_events)
if next_annotation is not None:
cancelable_events = [
# Visual clue about upcoming annotation:
scheduler.enterabs(
# The chosen delay must be larger than the time
# that it takes for the user to add a value to an
# annotation (otherwise, he would not always have
# enough time to target the previous annotation
# and change its value before it is replaced by
# the next annotation).
time_to_counter(next_annotation.time)-1, getkey_priority-1,
lambda: stdscr.chgat(
2, x_display,
len(next_annotation_text), curses.A_STANDOUT)),
# The event scrolling must be scheduled *before*
# checking for a user key, because it is a requirement
# of getkey() that any annotation *at* or before the
# next_getkey_counter is in the list of previous
# annotation list.
# The transfer of next_annotation will require the
# list of previous annotations to be displayed:
scheduler.enterabs(time_to_counter(next_annotation.time),
getkey_priority-1, scroll_forwards)
]
def scroll_forwards():
"""
Move the annotations forwards in time.
The current next annotation is moved to the list of previous
annotations, and the next annotation (if any) is updated. The
screen is then refreshed.
The annotation cursor is moved forward, and the next scrolling
is scheduled (if necessary).
A next annotation must be present (both on screen and in
annotations, in a consistent way) when calling this function.
"""
# Transfer on screen to the list of previous annotations:
#
# This requires the previous annotations to be already displayed:
stdscr.scroll(-1)
addstr_width(6, 0, annot_str(annotations.next_annotation()))
# The cursor in the annotations list must be updated to
# reflect the screen update:
annotations.cursor += 1
display_next_annotation()
stdscr.refresh() # Instant feedback
def scroll_backwards(only_scroll_previous=False):
"""
Move the annotations backwards in time.
Scroll the list of previous annotations backwards in time
once, and the next annotation (if any) is updated. The screen
is then refreshed.
The annotation cursor is moved backwards once, and the next
scrolling is scheduled.
There must be an annotation before the cursor when calling
this function.
only_scroll_previous -- if true, only the list of previous
annotations is scrolled (the next annotation is not updated,
and the annotation cursor is not updated either). This case is
useful for updating the list of previous annotations after
deleting the annotation before the cursor.
"""
if not only_scroll_previous:
# Corresponding cursor movement:
annotations.cursor -= 1
display_next_annotation()
stdscr.scroll()
# The last line in the list of previous annotations might have
# to be updated with an annotation that was not displayed
# previously:
index_new_prev_annot = annotations.cursor-prev_annot_height
if index_new_prev_annot >= 0:
addstr_width(5+prev_annot_height, 0,
annot_str(annotations[index_new_prev_annot]))
# Instant feedback:
stdscr.refresh()
def navigate(key, key_time, time_sync, annotations: EventData):
"""
Given a navigation key entered at the given time for the given
annotations, update the annotation time and screen.
Beeps are emitted for impossible operations (like going to the
previous annotation when there is none).
key -- "KEY_RIGHT", "KEY_LEFT" or "KEY_DOWN". KEY_RIGHT goes to the
next annotation, if any. KEY_LEFT goes to the previous
annotation, if any, or two annotations back, if key_time is
close to the previous annotation. KEY_DOWN goes back NAVIG_STEP
in time.
key_time -- time at which the key is considered
pressed (compatible with a datetime.timedelta).
time_sync -- function that takes a new Time for the annotation
timer and synchronizes the scheduler counter with it, along
with the external player play head time.
annotations -- EventData which is navigated through the key. Its cursor
must correspond to key_time (i.e. set_cursor_at_time(key_time) is
where the cursor is currently).
"""
logging.debug("")
logging.debug("navigate(key_time=%s)", key_time)
# It is important to synchronize the times early: otherwise,
# time scheduling is broken (like for instance the automatic
# scrolling of annotations). This is why the screen display is
# only run after performing the time synchronization.
if key == "KEY_RIGHT":
next_annotation = annotations.next_annotation()
if next_annotation is not None:
time_sync(next_annotation.time)
scroll_forwards()
else:
curses.beep()
elif key == "KEY_LEFT":
logging.debug("KEY LEFT")
# Where is the previous annotation?
prev_annotation = annotations.prev_annotation()
if prev_annotation is None:
curses.beep()
else:
prev_annot_time = prev_annotation.time
logging.debug(
"prev_annot_time = %s", prev_annot_time)
# The back arrow means two possible things:
#
# 1) If the timer is past the latest annotation by more than
# BACK_ARROW_THRESHOLD, then the back arrow key instructs the
# program to go back to the latest annotation time (and so
# the displayed list of past annotations doesn't change).
#
# 2) Otherwise, the back key means instead to go *past*
# the time of the last annotation (in which case the
# annotations found at the time of the last annotation
# disappear from the list of annotations).
if key_time-prev_annot_time < BACK_ARROW_THRESHOLD:
# This is the case where the back arrow is understood
# as a command to go back past the last annotation time
# (instead of to the last annotation time):
target_cursor = annotations.cursor_skipping_prev_time()
logging.debug("Cursor = %s", annotations.cursor)
logging.debug("prev_annotation_time = %s", prev_annot_time)
logging.debug("target_cursor = %s", target_cursor)
if target_cursor is None:
# It is not possible to go before the last annotation
# time, because there is no annotation before it:
curses.beep()
else:
# The time is set to the now top annotation:
time_sync(annotations[target_cursor].time)
# When multiple annotations are found at the same
# timestamp, the list of annotations must be scrolled
# multiple times:
for _ in range(annotations.cursor-target_cursor-1):
logging.debug("scroll_backwards()")
scroll_backwards()
else:
# We were far from the previous annotation: only the
# time changes (to the previous annotation); the last
# displayed annotation is correct: there is no need to
# scroll the annotations.
logging.debug(
"time_sync(new_time=%s)",
prev_annot_time)
time_sync(prev_annot_time)
# It is important to update the Next annotation
# events, if any, since the user sees them in the
# annotation timer time, but they are scheduled in
# the old scheduler time:
logging.debug("display_next_annotation()")
display_next_annotation()
else: # KEY_DOWN or KEY_UP
if key == "KEY_UP":
# Time to be reached:
target_time = key_time + NAVIG_STEP
# Function for moving to the next annotation *in the
# chosen direction*:
next_annot = annotations.next_annotation
# Screen update for going to the next annotation *in
# the chosen direction*:
scroll = scroll_forwards
def must_scroll(time_):
"""
Return true if scrolling is needed in order to reach a
situation where the next and previous annotations
are correctly displayed.
time_ -- time stamp of an annotation in the Next
annotation field.
"""
# Any annotation at the same time as the
# annotation timer must be in the list of previous
# annotations, in order to satisfy the getkey()
# requirement:
return time_ <= target_time
else: # KEY_DOWN:
target_time = key_time - NAVIG_STEP
next_annot = annotations.prev_annotation
scroll = scroll_backwards