-
-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathviews.py
2174 lines (1888 loc) · 79.7 KB
/
views.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
"""
UI views for larger elements such as Streams, Messages, Topics, Help, etc
"""
import threading
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pytz
import urwid
from typing_extensions import Literal
from zulipterminal.api_types import EditPropagateMode, Message
from zulipterminal.config.keys import (
HELP_CATEGORIES,
KEY_BINDINGS,
display_key_for_urwid_key,
display_keys_for_command,
is_command_key,
primary_key_for_command,
)
from zulipterminal.config.markdown_examples import MARKDOWN_ELEMENTS
from zulipterminal.config.symbols import (
CHECK_MARK,
COLUMN_TITLE_BAR_LINE,
PINNED_STREAMS_DIVIDER,
SECTION_DIVIDER_LINE,
)
from zulipterminal.config.ui_mappings import (
BOT_TYPE_BY_ID,
EDIT_MODE_CAPTIONS,
ROLE_BY_ID,
STATE_ICON,
STREAM_ACCESS_TYPE,
STREAM_POST_POLICY,
)
from zulipterminal.config.ui_sizes import LEFT_WIDTH
from zulipterminal.helper import (
TidiedUserInfo,
asynch,
match_emoji,
match_stream,
match_user,
)
from zulipterminal.platform_code import PLATFORM, detected_python_in_full
from zulipterminal.server_url import near_message_url
from zulipterminal.ui_tools.boxes import PanelSearchBox
from zulipterminal.ui_tools.buttons import (
DMButton,
EmojiButton,
HomeButton,
MentionedButton,
MessageLinkButton,
StarredButton,
StreamButton,
TopicButton,
UserButton,
)
from zulipterminal.ui_tools.messages import MessageBox
from zulipterminal.ui_tools.utils import create_msg_box_list
from zulipterminal.urwid_types import urwid_Size
MIDDLE_COLUMN_MOUSE_SCROLL_LINES = 1
SIDE_PANELS_MOUSE_SCROLL_LINES = 5
class ModListWalker(urwid.SimpleFocusListWalker):
def __init__(self, *, contents: List[Any], action: Callable[[], None]) -> None:
self._action = action
super().__init__(contents)
def set_focus(self, position: int) -> None:
# When setting focus via set_focus method.
self.focus = position
self._modified()
self._action()
def _set_focus(self, index: int) -> None:
# This method is called when directly setting focus via
# self.focus = focus_position
if not self: # type: ignore[truthy-bool] # Implemented in base class
self._focus = 0
return
if index < 0 or index >= len(self):
raise IndexError(f"focus index is out of range: {index}")
if index != int(index):
raise IndexError(f"invalid focus index: {index}")
index = int(index)
if index != self._focus:
self._focus_changed(index)
self._focus = index
self._action()
def extend(self, items: List[Any], focus_position: Optional[int] = None) -> int:
if focus_position is None:
focus = self._adjust_focus_on_contents_modified(
slice(len(self), len(self)), items
)
else:
focus = focus_position
rval = super(urwid.MonitoredFocusList, self).extend(items)
self._set_focus(focus)
return rval
class MessageView(urwid.ListBox):
def __init__(self, model: Any, view: Any) -> None:
self.model = model
self.view = view
# Initialize for reference
self.focus_msg = 0
self.log = ModListWalker(contents=self.main_view(), action=self.read_message)
super().__init__(self.log)
self.set_focus(self.focus_msg)
# if loading new/old messages - True
self.old_loading = False
self.new_loading = False
def main_view(self) -> List[Any]:
msg_btn_list = create_msg_box_list(self.model)
focus_msg = self.model.get_focus_in_current_narrow()
if focus_msg is None:
focus_msg = len(msg_btn_list) - 1
self.focus_msg = focus_msg
return msg_btn_list
@asynch
def load_old_messages(self, anchor: int) -> None:
self.old_loading = True
ids_to_keep = self.model.get_message_ids_in_current_narrow()
if self.log: # type: ignore[truthy-bool] # Implemented in base class
top_message_id = self.log[0].original_widget.message["id"]
ids_to_keep.remove(top_message_id) # update this id
no_update_baseline = {top_message_id}
else:
no_update_baseline = set()
self.model.get_messages(num_before=30, num_after=0, anchor=anchor)
ids_to_process = self.model.get_message_ids_in_current_narrow() - ids_to_keep
# Only update if more messages are provided
if ids_to_process != no_update_baseline:
if self.log: # type: ignore[truthy-bool] # Implemented in base class
self.log.remove(self.log[0]) # avoid duplication when updating
message_list = create_msg_box_list(self.model, ids_to_process)
message_list.reverse()
for msg_w in message_list:
self.log.insert(0, msg_w)
self.set_focus(self.focus_msg) # Return focus to original message
self.model.controller.update_screen()
self.old_loading = False
@asynch
def load_new_messages(self, anchor: int) -> None:
self.new_loading = True
current_ids = self.model.get_message_ids_in_current_narrow()
self.model.get_messages(num_before=0, num_after=30, anchor=anchor)
new_ids = self.model.get_message_ids_in_current_narrow() - current_ids
if self.log: # type: ignore[truthy-bool] # Implemented in base class
last_message = self.log[-1].original_widget.message
else:
last_message = None
message_list = create_msg_box_list(
self.model, new_ids, last_message=last_message
)
self.log.extend(message_list)
self.model.controller.update_screen()
self.new_loading = False
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(MIDDLE_COLUMN_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
if button == 5:
for _ in range(MIDDLE_COLUMN_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("GO_DOWN", key) and not self.new_loading:
try:
position = self.log.next_position(self.focus_position)
self.set_focus(position, "above")
self.set_focus_valign("middle")
return key
except Exception:
if self.focus:
id = self.focus.original_widget.message["id"]
self.load_new_messages(id)
return key
elif is_command_key("GO_UP", key) and not self.old_loading:
try:
position = self.log.prev_position(self.focus_position)
self.set_focus(position, "below")
self.set_focus_valign("middle")
return key
except Exception:
if self.focus:
id = self.focus.original_widget.message["id"]
self.load_old_messages(id)
return key
elif is_command_key("SCROLL_UP", key) and not self.old_loading:
if self.focus is not None and self.focus_position == 0:
return self.keypress(size, primary_key_for_command("GO_UP"))
else:
return super().keypress(size, primary_key_for_command("SCROLL_UP"))
elif is_command_key("SCROLL_DOWN", key) and not self.old_loading:
if self.focus is not None and self.focus_position == len(self.log) - 1:
return self.keypress(size, primary_key_for_command("GO_DOWN"))
else:
return super().keypress(size, primary_key_for_command("SCROLL_DOWN"))
elif is_command_key("THUMBS_UP", key) and self.focus is not None:
message = self.focus.original_widget.message
self.model.toggle_message_reaction(message, reaction_to_toggle="thumbs_up")
elif is_command_key("TOGGLE_STAR_STATUS", key) and self.focus is not None:
message = self.focus.original_widget.message
self.model.toggle_message_star_status(message)
elif is_command_key("REACTION_AGREEMENT", key) and self.focus is not None:
message = self.focus.original_widget.message
message_reactions = message["reactions"]
if len(message_reactions) > 0:
for reaction in message_reactions:
emoji = reaction["emoji_name"]
self.model.toggle_message_reaction(message, emoji)
break
key = super().keypress(size, key)
return key
def update_search_box_narrow(self, message_view: Any) -> None:
if not hasattr(self.model.controller, "view"):
return
# if view is ready display current narrow
# at the bottom of the view.
recipient_bar = message_view.recipient_header()
top_header = message_view.top_search_bar()
self.model.controller.view.search_box.conversation_focus.set_text(
top_header.markup
)
self.model.controller.view.search_box.msg_narrow.set_text(recipient_bar.markup)
self.model.controller.update_screen()
def read_message(self, index: int = -1) -> None:
# Message currently in focus
if hasattr(self.model.controller, "view"):
view = self.model.controller.view
else:
return
msg_w, curr_pos = self.body.get_focus()
if msg_w is None:
return
self.update_search_box_narrow(msg_w.original_widget)
# Do not read messages in explore mode.
if self.model.controller.in_explore_mode:
return
# Do not read messages in any search narrow.
if self.model.is_search_narrow():
return
# If this the last message in the view and focus is set on this message
# then read the message.
last_message_focused = curr_pos == len(self.log) - 1
# Only allow reading a message when middle column is
# in focus.
if not (view.body.focus_col == 1 or last_message_focused):
return
# save the current focus
self.model.set_focus_in_current_narrow(self.focus_position)
# msg ids that have been read
read_msg_ids = list()
# until we find a read message above the current message
while msg_w.attr_map == {None: "unread"}:
msg_id = msg_w.original_widget.message["id"]
read_msg_ids.append(msg_id)
self.model.index["messages"][msg_id]["flags"].append("read")
msg_w.set_attr_map({None: None})
msg_w, curr_pos = self.body.get_prev(curr_pos)
if msg_w is None:
break
self.model.mark_message_ids_as_read(read_msg_ids)
class StreamsViewDivider(urwid.Divider):
"""
A custom urwid.Divider to visually separate pinned and unpinned streams.
"""
def __init__(self) -> None:
# FIXME: Necessary since the divider is treated as a StreamButton.
# NOTE: This is specifically for stream search to work correctly.
self.stream_id = -1
self.stream_name = ""
super().__init__(div_char=PINNED_STREAMS_DIVIDER)
class StreamsView(urwid.Frame):
def __init__(self, streams_btn_list: List[Any], view: Any) -> None:
self.view = view
self.log = urwid.SimpleFocusListWalker(streams_btn_list)
self.streams_btn_list = streams_btn_list
self.focus_index_before_search = 0
list_box = urwid.ListBox(self.log)
self.stream_search_box = PanelSearchBox(
self, "SEARCH_STREAMS", self.update_streams
)
super().__init__(
list_box,
header=urwid.Pile(
[self.stream_search_box, urwid.Divider(SECTION_DIVIDER_LINE)]
),
)
self.search_lock = threading.Lock()
self.empty_search = False
@asynch
def update_streams(self, search_box: Any, new_text: str) -> None:
if not self.view.controller.is_in_editor_mode():
return
# wait for any previously started search to finish to avoid
# displaying wrong stream list.
with self.search_lock:
stream_buttons = [
(stream, stream.stream_name) for stream in self.streams_btn_list.copy()
]
streams_display = match_stream(
stream_buttons, new_text, self.view.pinned_streams
)[0]
streams_display_num = len(streams_display)
self.empty_search = streams_display_num == 0
# Add a divider to separate pinned streams from the rest.
pinned_stream_names = [
stream["name"] for stream in self.view.pinned_streams
]
first_unpinned_index = streams_display_num
for index, stream in enumerate(streams_display):
if stream.stream_name not in pinned_stream_names:
first_unpinned_index = index
break
# Do not add a divider when it is already present. This can
# happen when new_text=''.
if first_unpinned_index not in [0, streams_display_num] and not isinstance(
streams_display[first_unpinned_index], StreamsViewDivider
):
streams_display.insert(first_unpinned_index, StreamsViewDivider())
self.log.clear()
if not self.empty_search:
self.log.extend(streams_display)
else:
self.log.extend([self.stream_search_box.search_error])
self.view.controller.update_screen()
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_STREAMS", key):
_, self.focus_index_before_search = self.log.get_focus()
self.set_focus("header")
self.stream_search_box.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.stream_search_box)
return key
elif is_command_key("CLEAR_SEARCH", key):
self.stream_search_box.reset_search_text()
self.log.clear()
self.log.extend(self.streams_btn_list)
self.set_focus("body")
self.log.set_focus(self.focus_index_before_search)
self.view.controller.update_screen()
return key
return super().keypress(size, key)
class TopicsView(urwid.Frame):
def __init__(
self, topics_btn_list: List[Any], view: Any, stream_button: Any
) -> None:
self.view = view
self.log = urwid.SimpleFocusListWalker(topics_btn_list)
self.topics_btn_list = topics_btn_list
self.stream_button = stream_button
self.focus_index_before_search = 0
self.list_box = urwid.ListBox(self.log)
self.topic_search_box = PanelSearchBox(
self, "SEARCH_TOPICS", self.update_topics
)
self.header_list = urwid.Pile(
[
self.stream_button,
urwid.Divider(SECTION_DIVIDER_LINE),
self.topic_search_box,
urwid.Divider(SECTION_DIVIDER_LINE),
]
)
self.list_box.focus_position = self._focus_position_for_topic_name()
super().__init__(
self.list_box,
header=self.header_list,
)
self.search_lock = threading.Lock()
self.empty_search = False
def _focus_position_for_topic_name(self) -> int:
saved_topic_state = self.view.saved_topic_in_stream_id(
self.stream_button.stream_id
)
if saved_topic_state is not None:
for index, topic in enumerate(self.log):
if topic.topic_name == saved_topic_state:
return index
return 0
@asynch
def update_topics(self, search_box: Any, new_text: str) -> None:
if not self.view.controller.is_in_editor_mode():
return
# wait for any previously started search to finish to avoid
# displaying wrong topics list.
with self.search_lock:
new_text = new_text.lower()
topics_to_display = [
topic
for topic in self.topics_btn_list.copy()
if new_text in topic.topic_name.lower()
]
self.empty_search = len(topics_to_display) == 0
self.log.clear()
if not self.empty_search:
self.log.extend(topics_to_display)
else:
self.log.extend([self.topic_search_box.search_error])
self.view.controller.update_screen()
def update_topics_list(
self, stream_id: int, topic_name: str, sender_id: int
) -> None:
# More recent topics are found towards the beginning
# of the list.
for topic_iterator, topic_button in enumerate(self.log):
if topic_button.topic_name == topic_name:
self.log.insert(0, self.log.pop(topic_iterator))
self.list_box.set_focus_valign("bottom")
if sender_id == self.view.model.user_id:
self.list_box.set_focus(0)
return
# No previous topics with same topic names are found
# hence we create a new topic button for it.
new_topic_button = TopicButton(
stream_id=stream_id,
topic=topic_name,
controller=self.view.controller,
view=self.view,
count=0,
)
self.log.insert(0, new_topic_button)
self.list_box.set_focus_valign("bottom")
if sender_id == self.view.model.user_id:
self.list_box.set_focus(0)
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_TOPICS", key):
_, self.focus_index_before_search = self.log.get_focus()
self.set_focus("header")
self.header_list.set_focus(2)
self.topic_search_box.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.topic_search_box)
return key
elif is_command_key("CLEAR_SEARCH", key):
self.topic_search_box.reset_search_text()
self.log.clear()
self.log.extend(self.topics_btn_list)
self.set_focus("body")
self.log.set_focus(self.focus_index_before_search)
self.view.controller.update_screen()
return key
return super().keypress(size, key)
class UsersView(urwid.ListBox):
def __init__(self, controller: Any, users_btn_list: List[Any]) -> None:
self.users_btn_list = users_btn_list
self.log = urwid.SimpleFocusListWalker(users_btn_list)
self.controller = controller
super().__init__(self.log)
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 1 and self.controller.is_in_editor_mode():
return True
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return super().mouse_event(size, event, button, col, row, focus)
class MiddleColumnView(urwid.Frame):
def __init__(self, view: Any, model: Any, write_box: Any, search_box: Any) -> None:
message_view = MessageView(model, view)
self.model = model
self.controller = model.controller
self.view = view
self.search_box = search_box
view.message_view = message_view
super().__init__(message_view, header=search_box, footer=write_box)
def update_message_list_status_markers(self) -> None:
for message_w in self.body.log:
message_box = message_w.original_widget
message_box.update_message_author_status()
self.controller.update_screen()
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if self.focus_position in ["footer", "header"]:
return super().keypress(size, key)
elif is_command_key("SEARCH_MESSAGES", key):
self.controller.enter_editor_mode_with(self.search_box)
self.set_focus("header")
return key
elif is_command_key("REPLY_MESSAGE", key):
self.body.keypress(size, key)
if self.footer.focus is not None:
self.set_focus("footer")
self.footer.focus_position = 1
return key
elif is_command_key("STREAM_MESSAGE", key):
self.body.keypress(size, key)
# For new streams with no previous conversation.
if self.footer.focus is None:
stream_id = self.model.stream_id
stream_dict = self.model.stream_dict
if stream_id is None:
self.footer.stream_box_view(0)
else:
self.footer.stream_box_view(caption=stream_dict[stream_id]["name"])
self.set_focus("footer")
self.footer.focus_position = 0
return key
elif is_command_key("REPLY_AUTHOR", key):
self.body.keypress(size, key)
if self.footer.focus is not None:
self.set_focus("footer")
self.footer.focus_position = 1
return key
elif is_command_key("NEXT_UNREAD_TOPIC", key):
# narrow to next unread topic
focus = self.view.message_view.focus
narrow = self.model.narrow
if focus:
current_msg_id = focus.original_widget.message["id"]
stream_topic = self.model.next_unread_topic_from_message_id(
current_msg_id
)
if stream_topic is None:
return key
elif narrow[0][0] == "stream" and narrow[1][0] == "topic":
stream_topic = self.model.next_unread_topic_from_message_id(None)
else:
return key
stream_id, topic = stream_topic
self.controller.narrow_to_topic(
stream_name=self.model.stream_dict[stream_id]["name"],
topic_name=topic,
)
return key
elif is_command_key("NEXT_UNREAD_DM", key):
# narrow to next unread dm
dm = self.model.get_next_unread_pm()
if dm is None:
return key
email = self.model.user_id_email_dict[dm]
self.controller.narrow_to_user(
recipient_emails=[email],
contextual_message_id=dm,
)
elif is_command_key("DIRECT_MESSAGE", key):
# Create new DM message
self.footer.private_box_view()
self.set_focus("footer")
self.footer.focus_position = 0
return key
elif is_command_key("GO_LEFT", key):
self.view.show_left_panel(visible=True)
elif is_command_key("GO_RIGHT", key):
self.view.show_right_panel(visible=True)
return super().keypress(size, key)
class RightColumnView(urwid.Frame):
"""
Displays the users list on the right side of the app.
"""
def __init__(self, view: Any) -> None:
self.view = view
self.user_search = PanelSearchBox(self, "SEARCH_PEOPLE", self.update_user_list)
self.view.user_search = self.user_search
search_box = urwid.Pile([self.user_search, urwid.Divider(SECTION_DIVIDER_LINE)])
self.allow_update_user_list = True
self.search_lock = threading.Lock()
self.empty_search = False
super().__init__(self.users_view(), header=search_box)
@asynch
def update_user_list(
self,
search_box: Any = None,
new_text: Optional[str] = None,
user_list: Any = None,
) -> None:
"""
Updates user list via PanelSearchBox and _start_presence_updates.
"""
assert (user_list is None and search_box is not None) or ( # PanelSearchBox.
user_list is not None and search_box is None and new_text is None
) # _start_presence_updates.
# Return if the method is called by PanelSearchBox (ReadlineEdit) while
# the search is inactive and user_list is None.
# NOTE: The additional not user_list check is to not false trap
# _start_presence_updates but allow it to update the user list.
if not self.view.controller.is_in_editor_mode() and not user_list:
return
# Return if the method is called from _start_presence_updates while the
# search, via PanelSearchBox, is active.
if not self.allow_update_user_list and new_text is None:
return
# wait for any previously started search to finish to avoid
# displaying wrong user list.
with self.search_lock:
if user_list:
self.view.users = user_list
users = self.view.users.copy()
if new_text:
users_display = [user for user in users if match_user(user, new_text)]
else:
users_display = users
self.empty_search = len(users_display) == 0
# FIXME Update log directly?
if not self.empty_search:
self.body = self.users_view(users_display)
else:
self.body = UsersView(
self.view.controller, [self.user_search.search_error]
)
self.set_body(self.body)
self.view.controller.update_screen()
def users_view(self, users: Any = None) -> Any:
reset_default_view_users = False
if users is None:
users = self.view.users.copy()
reset_default_view_users = True
users_btn_list = list()
for user in users:
status = user["status"]
# Only include `inactive` users in search result.
if status == "inactive" and not self.view.controller.is_in_editor_mode():
continue
unread_count = self.view.model.unread_counts["unread_pms"].get(
user["user_id"], 0
)
is_current_user = user["user_id"] == self.view.model.user_id
users_btn_list.append(
UserButton(
user=user,
controller=self.view.controller,
view=self.view,
state_marker=STATE_ICON[status],
color=f"user_{status}",
count=unread_count,
is_current_user=is_current_user,
)
)
user_w = UsersView(self.view.controller, users_btn_list)
# Do not reset them while searching.
if reset_default_view_users:
self.users_btn_list = users_btn_list
self.view.user_w = user_w
return user_w
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_PEOPLE", key):
self.allow_update_user_list = False
self.set_focus("header")
self.user_search.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.user_search)
return key
elif is_command_key("CLEAR_SEARCH", key):
self.user_search.reset_search_text()
self.allow_update_user_list = True
self.body = UsersView(self.view.controller, self.users_btn_list)
self.set_body(self.body)
self.set_focus("body")
self.view.controller.update_screen()
return key
elif is_command_key("GO_LEFT", key):
self.view.show_right_panel(visible=False)
return super().keypress(size, key)
class LeftColumnView(urwid.Pile):
"""
Displays the buttons at the left column of the app.
"""
def __init__(self, view: Any) -> None:
self.model = view.model
self.view = view
self.controller = view.controller
self.menu_v = self.menu_view()
self.stream_v = self.streams_view()
self.is_in_topic_view = False
contents = [(4, self.menu_v), self.stream_v]
super().__init__(contents)
def menu_view(self) -> Any:
count = self.model.unread_counts.get("all_msg", 0)
self.view.home_button = HomeButton(controller=self.controller, count=count)
count = self.model.unread_counts.get("all_dms", 0)
self.view.dm_button = DMButton(controller=self.controller, count=count)
self.view.mentioned_button = MentionedButton(
controller=self.controller,
count=self.model.unread_counts["all_mentions"],
)
# Starred messages are by definition read already
count = len(self.model.initial_data["starred_messages"])
self.view.starred_button = StarredButton(
controller=self.controller, count=count
)
menu_btn_list = [
self.view.home_button,
self.view.dm_button,
self.view.mentioned_button,
self.view.starred_button,
]
w = urwid.ListBox(urwid.SimpleFocusListWalker(menu_btn_list))
return w
def streams_view(self) -> Any:
streams_btn_list = [
StreamButton(
properties=stream,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["streams"].get(stream["id"], 0),
)
for stream in self.view.pinned_streams
]
if len(streams_btn_list):
streams_btn_list += [StreamsViewDivider()]
streams_btn_list += [
StreamButton(
properties=stream,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["streams"].get(stream["id"], 0),
)
for stream in self.view.unpinned_streams
]
self.view.stream_id_to_button = {
stream.stream_id: stream
for stream in streams_btn_list
if hasattr(stream, "stream_id")
}
self.view.stream_w = StreamsView(streams_btn_list, self.view)
w = urwid.LineBox(
self.view.stream_w,
title="Streams",
title_attr="column_title",
tlcorner=COLUMN_TITLE_BAR_LINE,
tline=COLUMN_TITLE_BAR_LINE,
trcorner=COLUMN_TITLE_BAR_LINE,
blcorner="",
rline="",
lline="",
bline="",
brcorner="",
)
return w
def topics_view(self, stream_button: Any) -> Any:
stream_id = stream_button.stream_id
topics = self.model.topics_in_stream(stream_id)
topics_btn_list = [
TopicButton(
stream_id=stream_id,
topic=topic,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["unread_topics"].get(
(stream_id, topic), 0
),
)
for topic in topics
]
self.view.topic_w = TopicsView(topics_btn_list, self.view, stream_button)
w = urwid.LineBox(
self.view.topic_w,
title="Topics",
title_attr="column_title",
tlcorner=COLUMN_TITLE_BAR_LINE,
tline=COLUMN_TITLE_BAR_LINE,
trcorner=COLUMN_TITLE_BAR_LINE,
blcorner="",
rline="",
lline="",
bline="",
brcorner="",
)
return w
def is_in_topic_view_with_stream_id(self, stream_id: int) -> bool:
return (
self.is_in_topic_view
and stream_id == self.view.topic_w.stream_button.stream_id
)
def update_stream_view(self) -> None:
self.stream_v = self.streams_view()
if not self.is_in_topic_view:
self.show_stream_view()
def show_stream_view(self) -> None:
self.is_in_topic_view = False
self.contents[1] = (self.stream_v, self.options(height_type="weight"))
def show_topic_view(self, stream_button: Any) -> None:
self.is_in_topic_view = True
self.contents[1] = (
self.topics_view(stream_button),
self.options(height_type="weight"),
)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_STREAMS", key) or is_command_key(
"SEARCH_TOPICS", key
):
self.focus_position = 1
if self.is_in_topic_view:
self.view.topic_w.keypress(size, key)
else:
self.view.stream_w.keypress(size, key)
return key
elif is_command_key("GO_RIGHT", key):
self.view.show_left_panel(visible=False)
return super().keypress(size, key)
class TabView(urwid.WidgetWrap):
"""
Displays a tab that takes up the whole containers height
and has a flow width.
Currently used as closed tabs in the autohide layout.
"""
def __init__(self, text: str) -> None:
tab_widget_list = [urwid.Text(char) for char in text]
pile = urwid.Pile(tab_widget_list)
tab = urwid.Padding(urwid.Filler(pile), left=1, right=1, width=1)
super().__init__(tab)
# FIXME: This type could be improved, as Any isn't too explicit and clear.
# (this was previously str, but some types passed in can be more complex)
PopUpViewTableContent = Sequence[Tuple[str, Sequence[Union[str, Tuple[str, Any]]]]]
class PopUpView(urwid.Frame):
def __init__(
self,
controller: Any,
body: List[Any],
command: str,
requested_width: int,
title: str,
header: Optional[Any] = None,
footer: Optional[Any] = None,
) -> None:
self.controller = controller
self.command = command
self.title = title
self.log = urwid.SimpleFocusListWalker(body)
self.body = urwid.ListBox(self.log)
max_cols, max_rows = controller.maximum_popup_dimensions()
self.width = min(max_cols, requested_width)
height = self.calculate_popup_height(body, header, footer, self.width)
self.height = min(max_rows, height)
super().__init__(self.body, header=header, footer=footer)
@staticmethod
def calculate_popup_height(
body: List[Any],
header: Optional[Any],
footer: Optional[Any],
popup_width: int,
) -> int:
"""
Returns popup height. The popup height is calculated using urwid's
.rows method on every widget.
"""
height = sum(widget.rows((popup_width,)) for widget in body)
height += header.rows((popup_width,)) if header else 0
height += footer.rows((popup_width,)) if footer else 0
return height
@staticmethod
def calculate_table_widths(
contents: PopUpViewTableContent, title_len: int, dividechars: int = 2
) -> Tuple[int, List[int]]:
"""
Returns a tuple that contains the required width for the popup and a