Commit c45881e085

c45881e0857aacab7bafa9d93ea0851db9b9f402

parent: 90108d7b84

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-07-11 20:02 UTC

room_buffer: Add typing notice send support.

Layout: unified · split

Cargo.lock +3 −3
@@ -2203,7 +2203,7 @@ dependencies = [
22032203[[package]]
22042204name = "weechat"
22052205version = "0.1.0"
2206source = "git+https://github.com/poljar/rust-weechat#3d154ed91a70c587011fdeb31c619037dd82e501"
2206source = "git+https://github.com/poljar/rust-weechat#647e9a93560e6febab50b1c9456b30a8d440c22b"
22072207dependencies = [
22082208 "async-task",
22092209 "async-trait",
@@ -2217,7 +2217,7 @@ dependencies = [
22172217[[package]]
22182218name = "weechat-macro"
22192219version = "0.1.0"
2220source = "git+https://github.com/poljar/rust-weechat#3d154ed91a70c587011fdeb31c619037dd82e501"
2220source = "git+https://github.com/poljar/rust-weechat#647e9a93560e6febab50b1c9456b30a8d440c22b"
22212221dependencies = [
22222222 "libc",
22232223 "proc-macro2",
@@ -2248,7 +2248,7 @@ dependencies = [
22482248[[package]]
22492249name = "weechat-sys"
22502250version = "0.1.0"
2251source = "git+https://github.com/poljar/rust-weechat#3d154ed91a70c587011fdeb31c619037dd82e501"
2251source = "git+https://github.com/poljar/rust-weechat#647e9a93560e6febab50b1c9456b30a8d440c22b"
22522252dependencies = [
22532253 "bindgen",
22542254 "libc",
src/lib.rs +36 −2
@@ -16,8 +16,10 @@ use tracing_subscriber;
1616
1717use weechat::{
1818 buffer::{Buffer, BufferHandle},
19 hooks::{BarItemCallback, BarItemHandle},
20 weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin,
19 hooks::{
20 BarItemCallback, BarItemHandle, SignalCallback, SignalData, SignalHook,
21 },
22 weechat_plugin, ArgsWeechat, ReturnCode, Weechat, WeechatPlugin,
2123};
2224
2325use crate::commands::Commands;
@@ -43,6 +45,32 @@ impl Servers {
4345 }
4446}
4547
48impl SignalCallback for Servers {
49 fn callback(
50 &mut self,
51 _: &Weechat,
52 _signal_name: &str,
53 data: Option<SignalData>,
54 ) -> ReturnCode {
55 if let Some(data) = data {
56 if let SignalData::Buffer(buffer) = data {
57 let servers = self.borrow();
58
59 for server in servers.values() {
60 for room_buffer in server.inner().room_buffers.values() {
61 if buffer == room_buffer.weechat_buffer() {
62 room_buffer.update_typing_notice();
63
64 return ReturnCode::Ok;
65 }
66 }
67 }
68 }
69 }
70 ReturnCode::Ok
71 }
72}
73
4674struct Matrix {
4775 servers: Servers,
4876 #[used]
@@ -51,6 +79,8 @@ struct Matrix {
5179 config: ConfigHandle,
5280 #[used]
5381 status_bar: BarItemHandle,
82 #[used]
83 typing_notice_signal: SignalHook,
5484 debug_buffer: RefCell<Option<BufferHandle>>,
5585}
5686
@@ -141,12 +171,16 @@ impl WeechatPlugin for Matrix {
141171 }
142172 }
143173
174 let typing = SignalHook::new("input_text_changed", servers.clone())
175 .expect("Can't create signal hook for the typing notice cb");
176
144177 let plugin = Matrix {
145178 servers: servers.clone(),
146179 commands,
147180 config: config.clone(),
148181 status_bar,
149182 debug_buffer: RefCell::new(None),
183 typing_notice_signal: typing,
150184 };
151185
152186 Weechat::spawn(async move {
src/room_buffer.rs +89 −3
@@ -35,9 +35,11 @@ use url::Url;
3535
3636use async_trait::async_trait;
3737
38use crate::server::Connection;
38use crate::server::{Connection, TYPING_NOTICE_TIMEOUT};
3939use std::cell::{Ref, RefCell, RefMut};
4040use std::rc::Rc;
41use std::sync::atomic::{AtomicBool, Ordering};
42use std::time::Instant;
4143use weechat::buffer::{
4244 Buffer, BufferHandle, BufferInputCallbackAsync, BufferSettingsAsync,
4345 NickSettings,
@@ -45,6 +47,9 @@ use weechat::buffer::{
4547use weechat::Weechat;
4648
4749pub struct RoomBuffer {
50 own_user_id: Rc<UserId>,
51 room_id: Rc<RoomId>,
52 typing_in_flight: Rc<AtomicBool>,
4853 inner: MatrixRoom,
4954 buffer_handle: BufferHandle,
5055}
@@ -56,7 +61,7 @@ pub struct MatrixRoom {
5661 room_id: Rc<RoomId>,
5762 connection: Rc<RefCell<Option<Connection>>>,
5863 prev_batch: Rc<RefCell<Option<String>>>,
59 typing_notice_time: Rc<RefCell<Option<u64>>>,
64 typing_notice_time: Rc<RefCell<Option<Instant>>>,
6065 room: Rc<RefCell<Room>>,
6166 printed_before_ack_queue: Rc<RefCell<Vec<String>>>,
6267}
@@ -120,6 +125,9 @@ impl RoomBuffer {
120125 buffer.enable_nicklist();
121126
122127 RoomBuffer {
128 room_id: Rc::new(room_id),
129 own_user_id: Rc::new(own_user_id.to_owned()),
130 typing_in_flight: Rc::new(AtomicBool::from(false)),
123131 inner: room,
124132 buffer_handle,
125133 }
@@ -196,11 +204,89 @@ impl RoomBuffer {
196204 }
197205 }
198206
199 pub fn update_buffer_name(&mut self) {
207 pub fn update_buffer_name(&self) {
200208 let name = self.calculate_buffer_name();
201209 self.weechat_buffer().set_name(&name)
202210 }
203211
212 /// Send out a typing notice.
213 ///
214 /// This will send out a typing notice or reset one if needed. It will make
215 /// sure that only one typing notice request is in flight at a time.
216 ///
217 /// Typing notices are sent out only if we have more than 4 letters in the
218 /// input and the input isn't a command.
219 ///
220 /// If the input is empty the typing notice is disabled.
221 pub fn update_typing_notice(&self) {
222 // We're in the process of sending out a typing notice, so don't make
223 // the same request twice.
224 if self.typing_in_flight.load(Ordering::Relaxed) {
225 return;
226 }
227
228 let buffer = self.weechat_buffer();
229 let input = buffer.input();
230
231 if input.starts_with("/") && !input.starts_with("//") {
232 // Don't send typing notices for commands.
233 return;
234 }
235
236 let connection = self.inner.connection.clone();
237 let room_id = self.room_id.clone();
238 let user_id = self.own_user_id.clone();
239 let typing_notice_time = self.inner.typing_notice_time.clone();
240 let typing_in_flight = self.typing_in_flight.clone();
241
242 let send = async move |typing: bool| {
243 let typing_time = typing_notice_time;
244
245 if let Some(connection) = &*connection.borrow() {
246 let response = connection
247 .send_typing_notice(&*room_id, &*user_id, typing)
248 .await;
249
250 // If we got a successfull response mark when we sent out the
251 // notice so we don't send out another one while this one is
252 // active, or if we disabled the notice mark that no notice is
253 // active.
254 if response.is_ok() {
255 if typing {
256 *typing_time.borrow_mut() = Some(Instant::now());
257 } else {
258 *typing_time.borrow_mut() = None;
259 }
260 }
261 };
262
263 typing_in_flight.store(false, Ordering::Relaxed);
264 };
265
266 let typing_time = self.inner.typing_notice_time.borrow_mut();
267
268 if input.len() < 4 && typing_time.is_some() {
269 // If we have an active typing notice and our input is short, e.g.
270 // we removed the input set the typing notice to false.
271 self.typing_in_flight.store(true, Ordering::Release);
272 Weechat::spawn(send(false));
273 } else if input.len() >= 4 {
274 if let Some(typing_time) = &*typing_time {
275 // If we have some valid input, check if the typing notice
276 // expired and send one out if it indeed expired.
277 if typing_time.elapsed() > TYPING_NOTICE_TIMEOUT {
278 self.typing_in_flight.store(true, Ordering::Release);
279 Weechat::spawn(send(true));
280 }
281 } else {
282 // If we have some valid input and no active typing notice send
283 // one out.
284 self.typing_in_flight.store(true, Ordering::Release);
285 Weechat::spawn(send(true));
286 }
287 }
288 }
289
204290 pub fn handle_membership_event(
205291 &mut self,
206292 event: &MemberEvent,
src/server.rs +37 −2
@@ -69,7 +69,10 @@ use matrix_sdk::api::r0::session::login::Response as LoginResponse;
6969
7070use matrix_sdk::{
7171 self,
72 api::r0::message::create_message_event::Response as RoomSendResponse,
72 api::r0::{
73 message::create_message_event::Response as RoomSendResponse,
74 typing::create_typing_event::Response as TypingResponse,
75 },
7376 events::{
7477 collections::all::{RoomEvent, StateEvent},
7578 room::message::{MessageEventContent, TextMessageEventContent},
@@ -90,6 +93,7 @@ use crate::PLUGIN_NAME;
9093use crate::{config::Config, ConfigHandle};
9194
9295const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
96pub const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
9397
9498pub enum ClientMessage {
9599 LoginMessage(LoginResponse),
@@ -162,6 +166,37 @@ impl Connection {
162166 Err(e) => panic!("Tokio error while sending a message {:?}", e),
163167 }
164168 }
169 pub async fn send_typing_notice(
170 &self,
171 room_id: &RoomId,
172 user_id: &UserId,
173 typing: bool,
174 ) -> MatrixResult<TypingResponse> {
175 let room_id = room_id.to_owned();
176 let user_id = user_id.to_owned();
177 let client = self.client.clone();
178
179 let handle = self
180 .runtime
181 .spawn(async move {
182 let timeout = if typing {
183 Some(TYPING_NOTICE_TIMEOUT)
184 } else {
185 None
186 };
187
188 let ret = client
189 .typing_notice(&room_id, &user_id, typing, timeout)
190 .await;
191 ret
192 })
193 .await;
194
195 match handle {
196 Ok(response) => response,
197 Err(e) => panic!("Tokio error while sending a message {:?}", e),
198 }
199 }
165200}
166201
167202#[derive(Clone)]
@@ -179,7 +214,7 @@ impl std::fmt::Debug for MatrixServer {
179214
180215pub(crate) struct InnerServer {
181216 server_name: Rc<String>,
182 room_buffers: HashMap<RoomId, RoomBuffer>,
217 pub room_buffers: HashMap<RoomId, RoomBuffer>,
183218 settings: ServerSettings,
184219 config: ConfigHandle,
185220 client: Option<Client>,