Commit d13d4b9f7f

d13d4b9f7fe240df13027ce807750e082015a44b

parent: 54ce042384

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-13 05:20 UTC

Support replying to messages (#3)

Layout: unified · split

README.md +1 −1
@@ -62,7 +62,7 @@ two other TUI clients and Element Web:
62| Accepting Invites | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | 62| Accepting Invites | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
63| Typing Notification | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | 63| Typing Notification | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
64| E2E | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | 64| E2E | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
65| Replies | :x: ([#3]) | :heavy_check_mark: | :x: | :heavy_check_mark: | 65| Replies | :heavy_check_mark: | :heavy_check_mark: | :x: | :heavy_check_mark: |
66| Attachment uploading | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | 66| Attachment uploading | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: |
67| Attachment downloading | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | 67| Attachment downloading | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
68| Send stickers | :x: | :x: | :x: | :heavy_check_mark: | 68| Send stickers | :x: | :x: | :x: | :heavy_check_mark: |
src/base.rs +2
@@ -61,7 +61,9 @@ pub enum VerifyAction {
61 61
62#[derive(Clone, Debug, Eq, PartialEq)] 62#[derive(Clone, Debug, Eq, PartialEq)]
63pub enum MessageAction { 63pub enum MessageAction {
64 Cancel,
64 Download(Option<String>, bool), 65 Download(Option<String>, bool),
66 Reply,
65} 67}
66 68
67#[derive(Clone, Debug, Eq, PartialEq)] 69#[derive(Clone, Debug, Eq, PartialEq)]
src/commands.rs +24
@@ -133,6 +133,28 @@ fn iamb_members(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
133 return Ok(step); 133 return Ok(step);
134} 134}
135 135
136fn iamb_cancel(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
137 if !desc.arg.text.is_empty() {
138 return Result::Err(CommandError::InvalidArgument);
139 }
140
141 let ract = IambAction::from(MessageAction::Cancel);
142 let step = CommandStep::Continue(ract.into(), ctx.context.take());
143
144 return Ok(step);
145}
146
147fn iamb_reply(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
148 if !desc.arg.text.is_empty() {
149 return Result::Err(CommandError::InvalidArgument);
150 }
151
152 let ract = IambAction::from(MessageAction::Reply);
153 let step = CommandStep::Continue(ract.into(), ctx.context.take());
154
155 return Ok(step);
156}
157
136fn iamb_rooms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult { 158fn iamb_rooms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
137 if !desc.arg.text.is_empty() { 159 if !desc.arg.text.is_empty() {
138 return Result::Err(CommandError::InvalidArgument); 160 return Result::Err(CommandError::InvalidArgument);
@@ -231,11 +253,13 @@ fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult
231} 253}
232 254
233fn add_iamb_commands(cmds: &mut ProgramCommands) { 255fn add_iamb_commands(cmds: &mut ProgramCommands) {
256 cmds.add_command(ProgramCommand { names: vec!["cancel".into()], f: iamb_cancel });
234 cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms }); 257 cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
235 cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download }); 258 cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
236 cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite }); 259 cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
237 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join }); 260 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
238 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members }); 261 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
262 cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply });
239 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms }); 263 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
240 cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set }); 264 cmds.add_command(ProgramCommand { names: vec!["set".into()], f: iamb_set });
241 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces }); 265 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
src/message.rs +83 −56
@@ -11,9 +11,12 @@ use unicode_segmentation::UnicodeSegmentation;
11use unicode_width::UnicodeWidthStr; 11use unicode_width::UnicodeWidthStr;
12 12
13use matrix_sdk::ruma::{ 13use matrix_sdk::ruma::{
14 events::{ 14 events::room::message::{
15 room::message::{MessageType, RoomMessageEventContent}, 15 MessageType,
16 MessageLikeEvent, 16 OriginalRoomMessageEvent,
17 RedactedRoomMessageEvent,
18 RoomMessageEvent,
19 RoomMessageEventContent,
17 }, 20 },
18 MilliSecondsSinceUnixEpoch, 21 MilliSecondsSinceUnixEpoch,
19 OwnedEventId, 22 OwnedEventId,
@@ -33,8 +36,7 @@ use crate::{
33 config::ApplicationSettings, 36 config::ApplicationSettings,
34}; 37};
35 38
36pub type MessageEvent = MessageLikeEvent<RoomMessageEventContent>; 39pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>;
37pub type MessageFetchResult = IambResult<(Option<String>, Vec<MessageEvent>)>;
38pub type MessageKey = (MessageTimeStamp, OwnedEventId); 40pub type MessageKey = (MessageTimeStamp, OwnedEventId);
39pub type Messages = BTreeMap<MessageKey, Message>; 41pub type Messages = BTreeMap<MessageKey, Message>;
40 42
@@ -146,6 +148,13 @@ impl MessageTimeStamp {
146 fn is_local_echo(&self) -> bool { 148 fn is_local_echo(&self) -> bool {
147 matches!(self, MessageTimeStamp::LocalEcho) 149 matches!(self, MessageTimeStamp::LocalEcho)
148 } 150 }
151
152 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
153 match self {
154 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
155 MessageTimeStamp::LocalEcho => None,
156 }
157 }
149} 158}
150 159
151impl Ord for MessageTimeStamp { 160impl Ord for MessageTimeStamp {
@@ -304,61 +313,65 @@ impl PartialOrd for MessageCursor {
304} 313}
305 314
306#[derive(Clone)] 315#[derive(Clone)]
307pub enum MessageContent { 316pub enum MessageEvent {
308 Original(Box<RoomMessageEventContent>), 317 Original(Box<OriginalRoomMessageEvent>),
309 Redacted, 318 Redacted(Box<RedactedRoomMessageEvent>),
319 Local(Box<RoomMessageEventContent>),
310} 320}
311 321
312impl MessageContent { 322impl MessageEvent {
313 pub fn show(&self) -> Cow<'_, str> { 323 pub fn show(&self) -> Cow<'_, str> {
314 match self { 324 match self {
315 MessageContent::Original(ev) => { 325 MessageEvent::Original(ev) => show_room_content(&ev.content),
316 let s = match &ev.msgtype { 326 MessageEvent::Redacted(_) => Cow::Borrowed("[redacted]"),
317 MessageType::Text(content) => content.body.as_ref(), 327 MessageEvent::Local(content) => show_room_content(content),
318 MessageType::Emote(content) => content.body.as_ref(),
319 MessageType::Notice(content) => content.body.as_str(),
320 MessageType::ServerNotice(content) => content.body.as_str(),
321
322 MessageType::VerificationRequest(_) => {
323 // XXX: implement
324
325 return Cow::Owned("[verification request]".into());
326 },
327 MessageType::Audio(content) => {
328 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
329 },
330 MessageType::File(content) => {
331 return Cow::Owned(format!("[Attached File: {}]", content.body));
332 },
333 MessageType::Image(content) => {
334 return Cow::Owned(format!("[Attached Image: {}]", content.body));
335 },
336 MessageType::Video(content) => {
337 return Cow::Owned(format!("[Attached Video: {}]", content.body));
338 },
339 _ => {
340 return Cow::Owned(format!("[Unknown message type: {:?}]", ev.msgtype()));
341 },
342 };
343
344 Cow::Borrowed(s)
345 },
346 MessageContent::Redacted => Cow::Borrowed("[redacted]"),
347 } 328 }
348 } 329 }
349} 330}
350 331
332fn show_room_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
333 let s = match &content.msgtype {
334 MessageType::Text(content) => content.body.as_ref(),
335 MessageType::Emote(content) => content.body.as_ref(),
336 MessageType::Notice(content) => content.body.as_str(),
337 MessageType::ServerNotice(content) => content.body.as_str(),
338
339 MessageType::VerificationRequest(_) => {
340 // XXX: implement
341
342 return Cow::Owned("[verification request]".into());
343 },
344 MessageType::Audio(content) => {
345 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
346 },
347 MessageType::File(content) => {
348 return Cow::Owned(format!("[Attached File: {}]", content.body));
349 },
350 MessageType::Image(content) => {
351 return Cow::Owned(format!("[Attached Image: {}]", content.body));
352 },
353 MessageType::Video(content) => {
354 return Cow::Owned(format!("[Attached Video: {}]", content.body));
355 },
356 _ => {
357 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
358 },
359 };
360
361 Cow::Borrowed(s)
362}
363
351#[derive(Clone)] 364#[derive(Clone)]
352pub struct Message { 365pub struct Message {
353 pub content: MessageContent, 366 pub event: MessageEvent,
354 pub sender: OwnedUserId, 367 pub sender: OwnedUserId,
355 pub timestamp: MessageTimeStamp, 368 pub timestamp: MessageTimeStamp,
356 pub downloaded: bool, 369 pub downloaded: bool,
357} 370}
358 371
359impl Message { 372impl Message {
360 pub fn new(content: MessageContent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self { 373 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
361 Message { content, sender, timestamp, downloaded: false } 374 Message { event, sender, timestamp, downloaded: false }
362 } 375 }
363 376
364 pub fn show( 377 pub fn show(
@@ -369,7 +382,7 @@ impl Message {
369 settings: &ApplicationSettings, 382 settings: &ApplicationSettings,
370 ) -> Text { 383 ) -> Text {
371 let width = vwctx.get_width(); 384 let width = vwctx.get_width();
372 let mut msg = self.content.show(); 385 let mut msg = self.event.show();
373 386
374 if self.downloaded { 387 if self.downloaded {
375 msg.to_mut().push_str(" \u{2705}"); 388 msg.to_mut().push_str(" \u{2705}");
@@ -465,24 +478,38 @@ impl Message {
465 } 478 }
466} 479}
467 480
468impl From<MessageEvent> for Message { 481impl From<OriginalRoomMessageEvent> for Message {
469 fn from(event: MessageEvent) -> Self { 482 fn from(event: OriginalRoomMessageEvent) -> Self {
470 match event { 483 let timestamp = event.origin_server_ts.into();
471 MessageLikeEvent::Original(ev) => { 484 let user_id = event.sender.clone();
472 let content = MessageContent::Original(ev.content.into()); 485 let content = MessageEvent::Original(event.into());
473 486
474 Message::new(content, ev.sender, ev.origin_server_ts.into()) 487 Message::new(content, user_id, timestamp)
475 }, 488 }
476 MessageLikeEvent::Redacted(ev) => { 489}
477 Message::new(MessageContent::Redacted, ev.sender, ev.origin_server_ts.into()) 490
478 }, 491impl From<RedactedRoomMessageEvent> for Message {
492 fn from(event: RedactedRoomMessageEvent) -> Self {
493 let timestamp = event.origin_server_ts.into();
494 let user_id = event.sender.clone();
495 let content = MessageEvent::Redacted(event.into());
496
497 Message::new(content, user_id, timestamp)
498 }
499}
500
501impl From<RoomMessageEvent> for Message {
502 fn from(event: RoomMessageEvent) -> Self {
503 match event {
504 RoomMessageEvent::Original(ev) => ev.into(),
505 RoomMessageEvent::Redacted(ev) => ev.into(),
479 } 506 }
480 } 507 }
481} 508}
482 509
483impl ToString for Message { 510impl ToString for Message {
484 fn to_string(&self) -> String { 511 fn to_string(&self) -> String {
485 self.content.show().into_owned() 512 self.event.show().into_owned()
486 } 513 }
487} 514}
488 515
src/tests.rs +40 −24
@@ -3,10 +3,11 @@ use std::path::PathBuf;
3 3
4use matrix_sdk::ruma::{ 4use matrix_sdk::ruma::{
5 event_id, 5 event_id,
6 events::room::message::RoomMessageEventContent, 6 events::room::message::{OriginalRoomMessageEvent, RoomMessageEventContent},
7 server_name, 7 server_name,
8 user_id, 8 user_id,
9 EventId, 9 EventId,
10 OwnedEventId,
10 OwnedRoomId, 11 OwnedRoomId,
11 OwnedUserId, 12 OwnedUserId,
12 RoomId, 13 RoomId,
@@ -30,7 +31,7 @@ use crate::{
30 }, 31 },
31 message::{ 32 message::{
32 Message, 33 Message,
33 MessageContent, 34 MessageEvent,
34 MessageKey, 35 MessageKey,
35 MessageTimeStamp::{LocalEcho, OriginServer}, 36 MessageTimeStamp::{LocalEcho, OriginServer},
36 Messages, 37 Messages,
@@ -45,54 +46,69 @@ lazy_static! {
45 pub static ref TEST_USER3: OwnedUserId = user_id!("@user3:example.com").to_owned(); 46 pub static ref TEST_USER3: OwnedUserId = user_id!("@user3:example.com").to_owned();
46 pub static ref TEST_USER4: OwnedUserId = user_id!("@user4:example.com").to_owned(); 47 pub static ref TEST_USER4: OwnedUserId = user_id!("@user4:example.com").to_owned();
47 pub static ref TEST_USER5: OwnedUserId = user_id!("@user5:example.com").to_owned(); 48 pub static ref TEST_USER5: OwnedUserId = user_id!("@user5:example.com").to_owned();
48 pub static ref MSG1_KEY: MessageKey = (LocalEcho, EventId::new(server_name!("example.com"))); 49 pub static ref MSG1_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
49 pub static ref MSG2_KEY: MessageKey = 50 pub static ref MSG2_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
50 (OriginServer(UInt::new(1).unwrap()), EventId::new(server_name!("example.com"))); 51 pub static ref MSG3_EVID: OwnedEventId =
51 pub static ref MSG3_KEY: MessageKey = ( 52 event_id!("$5jRz3KfVhaUzXtVj7k:example.com").to_owned();
52 OriginServer(UInt::new(2).unwrap()), 53 pub static ref MSG4_EVID: OwnedEventId =
53 event_id!("$5jRz3KfVhaUzXtVj7k:example.com").to_owned() 54 event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned();
54 ); 55 pub static ref MSG5_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
55 pub static ref MSG4_KEY: MessageKey = ( 56 pub static ref MSG1_KEY: MessageKey = (LocalEcho, MSG1_EVID.clone());
56 OriginServer(UInt::new(2).unwrap()), 57 pub static ref MSG2_KEY: MessageKey = (OriginServer(UInt::new(1).unwrap()), MSG2_EVID.clone());
57 event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned() 58 pub static ref MSG3_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG3_EVID.clone());
58 ); 59 pub static ref MSG4_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG4_EVID.clone());
59 pub static ref MSG5_KEY: MessageKey = 60 pub static ref MSG5_KEY: MessageKey = (OriginServer(UInt::new(8).unwrap()), MSG5_EVID.clone());
60 (OriginServer(UInt::new(8).unwrap()), EventId::new(server_name!("example.com"))); 61}
62
63pub fn mock_room1_message(
64 content: RoomMessageEventContent,
65 sender: OwnedUserId,
66 key: MessageKey,
67) -> Message {
68 let origin_server_ts = key.0.as_millis().unwrap();
69 let event_id = key.1;
70
71 let event = OriginalRoomMessageEvent {
72 content,
73 event_id,
74 sender,
75 origin_server_ts,
76 room_id: TEST_ROOM1_ID.clone(),
77 unsigned: Default::default(),
78 };
79
80 event.into()
61} 81}
62 82
63pub fn mock_message1() -> Message { 83pub fn mock_message1() -> Message {
64 let content = RoomMessageEventContent::text_plain("writhe"); 84 let content = RoomMessageEventContent::text_plain("writhe");
65 let content = MessageContent::Original(content.into()); 85 let content = MessageEvent::Local(content.into());
66 86
67 Message::new(content, TEST_USER1.clone(), MSG1_KEY.0) 87 Message::new(content, TEST_USER1.clone(), MSG1_KEY.0)
68} 88}
69 89
70pub fn mock_message2() -> Message { 90pub fn mock_message2() -> Message {
71 let content = RoomMessageEventContent::text_plain("helium"); 91 let content = RoomMessageEventContent::text_plain("helium");
72 let content = MessageContent::Original(content.into());
73 92
74 Message::new(content, TEST_USER2.clone(), MSG2_KEY.0) 93 mock_room1_message(content, TEST_USER2.clone(), MSG2_KEY.clone())
75} 94}
76 95
77pub fn mock_message3() -> Message { 96pub fn mock_message3() -> Message {
78 let content = RoomMessageEventContent::text_plain("this\nis\na\nmultiline\nmessage"); 97 let content = RoomMessageEventContent::text_plain("this\nis\na\nmultiline\nmessage");
79 let content = MessageContent::Original(content.into());
80 98
81 Message::new(content, TEST_USER2.clone(), MSG3_KEY.0) 99 mock_room1_message(content, TEST_USER2.clone(), MSG3_KEY.clone())
82} 100}
83 101
84pub fn mock_message4() -> Message { 102pub fn mock_message4() -> Message {
85 let content = RoomMessageEventContent::text_plain("help"); 103 let content = RoomMessageEventContent::text_plain("help");
86 let content = MessageContent::Original(content.into());
87 104
88 Message::new(content, TEST_USER1.clone(), MSG4_KEY.0) 105 mock_room1_message(content, TEST_USER1.clone(), MSG4_KEY.clone())
89} 106}
90 107
91pub fn mock_message5() -> Message { 108pub fn mock_message5() -> Message {
92 let content = RoomMessageEventContent::text_plain("character"); 109 let content = RoomMessageEventContent::text_plain("character");
93 let content = MessageContent::Original(content.into());
94 110
95 Message::new(content, TEST_USER2.clone(), MSG5_KEY.0) 111 mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
96} 112}
97 113
98pub fn mock_messages() -> Messages { 114pub fn mock_messages() -> Messages {
src/windows/room/chat.rs +85 −13
@@ -8,14 +8,24 @@ use matrix_sdk::{
8 media::{MediaFormat, MediaRequest}, 8 media::{MediaFormat, MediaRequest},
9 room::Room as MatrixRoom, 9 room::Room as MatrixRoom,
10 ruma::{ 10 ruma::{
11 events::room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, 11 events::room::message::{
12 MessageType,
13 OriginalRoomMessageEvent,
14 RoomMessageEventContent,
15 TextMessageEventContent,
16 },
12 OwnedRoomId, 17 OwnedRoomId,
13 RoomId, 18 RoomId,
14 }, 19 },
15}; 20};
16 21
17use modalkit::{ 22use modalkit::{
18 tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget}, 23 tui::{
24 buffer::Buffer,
25 layout::Rect,
26 text::{Span, Spans},
27 widgets::{Paragraph, StatefulWidget, Widget},
28 },
19 widgets::textbox::{TextBox, TextBoxState}, 29 widgets::textbox::{TextBox, TextBoxState},
20 widgets::TerminalCursor, 30 widgets::TerminalCursor,
21 widgets::{PromptActions, WindowOps}, 31 widgets::{PromptActions, WindowOps},
@@ -52,10 +62,11 @@ use crate::base::{
52 ProgramContext, 62 ProgramContext,
53 ProgramStore, 63 ProgramStore,
54 RoomFocus, 64 RoomFocus,
65 RoomInfo,
55 SendAction, 66 SendAction,
56}; 67};
57 68
58use crate::message::{Message, MessageContent, MessageTimeStamp}; 69use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp};
59 70
60use super::scrollback::{Scrollback, ScrollbackState}; 71use super::scrollback::{Scrollback, ScrollbackState};
61 72
@@ -69,6 +80,8 @@ pub struct ChatState {
69 80
70 scrollback: ScrollbackState, 81 scrollback: ScrollbackState,
71 focus: RoomFocus, 82 focus: RoomFocus,
83
84 reply_to: Option<MessageKey>,
72} 85}
73 86
74impl ChatState { 87impl ChatState {
@@ -89,9 +102,27 @@ impl ChatState {
89 102
90 scrollback, 103 scrollback,
91 focus: RoomFocus::MessageBar, 104 focus: RoomFocus::MessageBar,
105
106 reply_to: None,
92 } 107 }
93 } 108 }
94 109
110 fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
111 let key = self.reply_to.as_ref()?;
112 let msg = info.messages.get(key)?;
113
114 if let MessageEvent::Original(ev) = &msg.event {
115 Some(ev)
116 } else {
117 None
118 }
119 }
120
121 fn reset(&mut self) -> EditRope {
122 self.reply_to = None;
123 self.tbox.reset()
124 }
125
95 pub fn refresh_room(&mut self, store: &mut ProgramStore) { 126 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
96 if let Some(room) = store.application.worker.client.get_room(self.id()) { 127 if let Some(room) = store.application.worker.client.get_room(self.id()) {
97 self.room = room; 128 self.room = room;
@@ -112,8 +143,13 @@ impl ChatState {
112 let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?; 143 let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?;
113 144
114 match act { 145 match act {
146 MessageAction::Cancel => {
147 self.reply_to = None;
148
149 Ok(None)
150 },
115 MessageAction::Download(filename, force) => { 151 MessageAction::Download(filename, force) => {
116 if let MessageContent::Original(ev) = &msg.content { 152 if let MessageEvent::Original(ev) = &msg.event {
117 let media = client.media(); 153 let media = client.media();
118 154
119 let mut filename = match filename { 155 let mut filename = match filename {
@@ -121,7 +157,7 @@ impl ChatState {
121 None => settings.dirs.downloads.clone(), 157 None => settings.dirs.downloads.clone(),
122 }; 158 };
123 159
124 let source = match &ev.msgtype { 160 let source = match &ev.content.msgtype {
125 MessageType::Audio(c) => { 161 MessageType::Audio(c) => {
126 if filename.is_dir() { 162 if filename.is_dir() {
127 filename.push(c.body.as_str()); 163 filename.push(c.body.as_str());
@@ -188,6 +224,12 @@ impl ChatState {
188 224
189 Err(IambError::NoAttachment.into()) 225 Err(IambError::NoAttachment.into())
190 }, 226 },
227 MessageAction::Reply => {
228 self.reply_to = self.scrollback.get_key(info);
229 self.focus = RoomFocus::MessageBar;
230
231 Ok(None)
232 },
191 } 233 }
192 } 234 }
193 235
@@ -203,6 +245,7 @@ impl ChatState {
203 .client 245 .client
204 .get_joined_room(self.id()) 246 .get_joined_room(self.id())
205 .ok_or(IambError::NotJoined)?; 247 .ok_or(IambError::NotJoined)?;
248 let info = store.application.rooms.entry(self.id().to_owned()).or_default();
206 249
207 let (event_id, msg) = match act { 250 let (event_id, msg) = match act {
208 SendAction::Submit => { 251 SendAction::Submit => {
@@ -214,15 +257,21 @@ impl ChatState {
214 257
215 let msg = TextMessageEventContent::plain(msg); 258 let msg = TextMessageEventContent::plain(msg);
216 let msg = MessageType::Text(msg); 259 let msg = MessageType::Text(msg);
217 let msg = RoomMessageEventContent::new(msg); 260
261 let mut msg = RoomMessageEventContent::new(msg);
262
263 if let Some(m) = self.get_reply_to(info) {
264 // XXX: Switch to RoomMessageEventContent::reply() once it's stable?
265 msg = msg.make_reply_to(m);
266 }
218 267
219 // XXX: second parameter can be a locally unique transaction id. 268 // XXX: second parameter can be a locally unique transaction id.
220 // Useful for doing retries. 269 // Useful for doing retries.
221 let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?; 270 let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?;
222 let event_id = resp.event_id; 271 let event_id = resp.event_id;
223 272
224 // Clear the TextBoxState contents now that the message is sent. 273 // Reset message bar state now that it's been sent.
225 self.tbox.reset(); 274 self.reset();
226 275
227 (event_id, msg) 276 (event_id, msg)
228 }, 277 },
@@ -252,12 +301,14 @@ impl ChatState {
252 }; 301 };
253 302
254 let user = store.application.settings.profile.user_id.clone(); 303 let user = store.application.settings.profile.user_id.clone();
255 let info = store.application.get_room_info(self.id().to_owned());
256 let key = (MessageTimeStamp::LocalEcho, event_id); 304 let key = (MessageTimeStamp::LocalEcho, event_id);
257 let msg = MessageContent::Original(msg.into()); 305 let msg = MessageEvent::Local(msg.into());
258 let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho); 306 let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
259 info.messages.insert(key, msg); 307 info.messages.insert(key, msg);
260 308
309 // Jump to the end of the scrollback to show the message.
310 self.scrollback.goto_latest();
311
261 Ok(None) 312 Ok(None)
262 } 313 }
263 314
@@ -333,6 +384,8 @@ impl WindowOps<IambInfo> for ChatState {
333 384
334 scrollback: self.scrollback.dup(store), 385 scrollback: self.scrollback.dup(store),
335 focus: self.focus, 386 focus: self.focus,
387
388 reply_to: None,
336 } 389 }
337 } 390 }
338 391
@@ -432,7 +485,7 @@ impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
432 return Ok(vec![]); 485 return Ok(vec![]);
433 } 486 }
434 487
435 let text = self.tbox.reset().trim(); 488 let text = self.reset().trim();
436 489
437 if text.is_empty() { 490 if text.is_empty() {
438 let _ = self.sent.end(); 491 let _ = self.sent.end();
@@ -506,15 +559,34 @@ impl<'a> StatefulWidget for Chat<'a> {
506 let lines = state.tbox.has_lines(5).max(1) as u16; 559 let lines = state.tbox.has_lines(5).max(1) as u16;
507 let drawh = area.height; 560 let drawh = area.height;
508 let texth = lines.min(drawh).clamp(1, 5); 561 let texth = lines.min(drawh).clamp(1, 5);
509 let scrollh = drawh.saturating_sub(texth); 562 let desch = if state.reply_to.is_some() {
563 drawh.saturating_sub(texth).min(1)
564 } else {
565 0
566 };
567 let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
510 568
511 let scrollarea = Rect::new(area.x, area.y, area.width, scrollh); 569 let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
512 let textarea = Rect::new(scrollarea.x, scrollarea.y + scrollh, scrollarea.width, texth); 570 let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
571 let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
513 572
514 let scrollback_focused = state.focus.is_scrollback() && self.focused; 573 let scrollback_focused = state.focus.is_scrollback() && self.focused;
515 let scrollback = Scrollback::new(self.store).focus(scrollback_focused); 574 let scrollback = Scrollback::new(self.store).focus(scrollback_focused);
516 scrollback.render(scrollarea, buf, &mut state.scrollback); 575 scrollback.render(scrollarea, buf, &mut state.scrollback);
517 576
577 let desc_spans = state.reply_to.as_ref().and_then(|k| {
578 let room = self.store.application.rooms.get(state.id())?;
579 let msg = room.messages.get(k)?;
580 let user = self.store.application.settings.get_user_span(msg.sender.as_ref());
581 let spans = Spans(vec![Span::from("Replying to "), user]);
582
583 spans.into()
584 });
585
586 if let Some(desc_spans) = desc_spans {
587 Paragraph::new(desc_spans).render(descarea, buf);
588 }
589
518 let prompt = if self.focused { "> " } else { " " }; 590 let prompt = if self.focused { "> " } else { " " };
519 591
520 let tbox = TextBox::new().prompt(prompt); 592 let tbox = TextBox::new().prompt(prompt);
src/windows/room/scrollback.rs +44 −7
@@ -104,11 +104,26 @@ fn nth_after(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageCursor {
104} 104}
105 105
106pub struct ScrollbackState { 106pub struct ScrollbackState {
107 /// The room identifier.
107 room_id: OwnedRoomId, 108 room_id: OwnedRoomId,
109
110 /// The buffer identifier used for saving marks, etc.
108 id: IambBufferId, 111 id: IambBufferId,
112
113 /// The currently selected message in the scrollback.
109 cursor: MessageCursor, 114 cursor: MessageCursor,
115
116 /// Contextual info about the viewport used during rendering.
110 viewctx: ViewportContext<MessageCursor>, 117 viewctx: ViewportContext<MessageCursor>,
118
119 /// The jumplist of visited messages.
111 jumped: HistoryList<MessageCursor>, 120 jumped: HistoryList<MessageCursor>,
121
122 /// Whether the full message should be drawn during the next render() call.
123 ///
124 /// This is used to ensure that ^E/^Y work nicely when the cursor is currently
125 /// on a multiline message.
126 show_full_on_redraw: bool,
112} 127}
113 128
114impl ScrollbackState { 129impl ScrollbackState {
@@ -117,8 +132,20 @@ impl ScrollbackState {
117 let cursor = MessageCursor::default(); 132 let cursor = MessageCursor::default();
118 let viewctx = ViewportContext::default(); 133 let viewctx = ViewportContext::default();
119 let jumped = HistoryList::default(); 134 let jumped = HistoryList::default();
135 let show_full_on_redraw = false;
120 136
121 ScrollbackState { room_id, id, cursor, viewctx, jumped } 137 ScrollbackState {
138 room_id,
139 id,
140 cursor,
141 viewctx,
142 jumped,
143 show_full_on_redraw,
144 }
145 }
146
147 pub fn goto_latest(&mut self) {
148 self.cursor = MessageCursor::latest();
122 } 149 }
123 150
124 /// Set the dimensions and placement within the terminal window for this list. 151 /// Set the dimensions and placement within the terminal window for this list.
@@ -126,6 +153,13 @@ impl ScrollbackState {
126 self.viewctx.dimensions = (area.width as usize, area.height as usize); 153 self.viewctx.dimensions = (area.width as usize, area.height as usize);
127 } 154 }
128 155
156 pub fn get_key(&self, info: &mut RoomInfo) -> Option<MessageKey> {
157 self.cursor
158 .timestamp
159 .clone()
160 .or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone()))
161 }
162
129 pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> { 163 pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> {
130 if let Some(k) = &self.cursor.timestamp { 164 if let Some(k) = &self.cursor.timestamp {
131 info.messages.get_mut(k) 165 info.messages.get_mut(k)
@@ -397,7 +431,7 @@ impl ScrollbackState {
397 continue; 431 continue;
398 } 432 }
399 433
400 if needle.is_match(msg.content.show().as_ref()) { 434 if needle.is_match(msg.event.show().as_ref()) {
401 mc = MessageCursor::from(key.clone()).into(); 435 mc = MessageCursor::from(key.clone()).into();
402 count -= 1; 436 count -= 1;
403 } 437 }
@@ -421,7 +455,7 @@ impl ScrollbackState {
421 break; 455 break;
422 } 456 }
423 457
424 if needle.is_match(msg.content.show().as_ref()) { 458 if needle.is_match(msg.event.show().as_ref()) {
425 mc = MessageCursor::from(key.clone()).into(); 459 mc = MessageCursor::from(key.clone()).into();
426 count -= 1; 460 count -= 1;
427 } 461 }
@@ -462,6 +496,7 @@ impl WindowOps<IambInfo> for ScrollbackState {
462 cursor: self.cursor.clone(), 496 cursor: self.cursor.clone(),
463 viewctx: self.viewctx.clone(), 497 viewctx: self.viewctx.clone(),
464 jumped: self.jumped.clone(), 498 jumped: self.jumped.clone(),
499 show_full_on_redraw: false,
465 } 500 }
466 } 501 }
467 502
@@ -582,6 +617,8 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
582 self.cursor = pos; 617 self.cursor = pos;
583 } 618 }
584 619
620 self.show_full_on_redraw = true;
621
585 return Ok(None); 622 return Ok(None);
586 }, 623 },
587 EditAction::Yank => { 624 EditAction::Yank => {
@@ -667,7 +704,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
667 let mut yanked = EditRope::from(""); 704 let mut yanked = EditRope::from("");
668 705
669 for (_, msg) in self.messages(range, info) { 706 for (_, msg) in self.messages(range, info) {
670 yanked += EditRope::from(msg.content.show().into_owned()); 707 yanked += EditRope::from(msg.event.show().into_owned());
671 yanked += EditRope::from('\n'); 708 yanked += EditRope::from('\n');
672 } 709 }
673 710
@@ -1173,15 +1210,15 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1173 nth_key_before(cursor_key.clone(), height, info) 1210 nth_key_before(cursor_key.clone(), height, info)
1174 }; 1211 };
1175 1212
1176 let full = cursor.timestamp.is_none(); 1213 let foc = self.focused || cursor.timestamp.is_some();
1177 1214 let full = std::mem::take(&mut state.show_full_on_redraw) || cursor.timestamp.is_none();
1178 let mut lines = vec![]; 1215 let mut lines = vec![];
1179 let mut sawit = false; 1216 let mut sawit = false;
1180 let mut prev = None; 1217 let mut prev = None;
1181 1218
1182 for (key, item) in info.messages.range(&corner_key..) { 1219 for (key, item) in info.messages.range(&corner_key..) {
1183 let sel = key == cursor_key; 1220 let sel = key == cursor_key;
1184 let txt = item.show(prev, self.focused && sel, &state.viewctx, settings); 1221 let txt = item.show(prev, foc && sel, &state.viewctx, settings);
1185 1222
1186 prev = Some(item); 1223 prev = Some(item);
1187 1224