chatedit.rs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_lock::Mutex as AsyncMutex;
  19. use async_trait::async_trait;
  20. use darkfi::system::msleep;
  21. use darkfi_serial::Decodable;
  22. use miniquad::{KeyCode, KeyMods, MouseButton, TouchPhase};
  23. use parking_lot::Mutex as SyncMutex;
  24. use rand::{rngs::OsRng, Rng};
  25. use std::{
  26. io::Cursor,
  27. ops::{Deref, DerefMut},
  28. sync::{
  29. atomic::{AtomicBool, Ordering},
  30. Arc, Weak,
  31. },
  32. };
  33. #[cfg(target_os = "android")]
  34. use crate::AndroidSuggestEvent;
  35. use crate::{
  36. gfx::{
  37. gfxtag, GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, Point, Rectangle, RenderApi, Vertex,
  38. },
  39. mesh::MeshBuilder,
  40. prop::{
  41. BatchGuardId, BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor,
  42. PropertyFloat32, PropertyPtr, PropertyRect, PropertyStr, PropertyUint32, Role,
  43. },
  44. scene::{MethodCallSub, Pimpl, SceneNodePtr, SceneNodeWeak},
  45. text2::{self, Editor},
  46. util::unixtime,
  47. ExecutorPtr,
  48. };
  49. use super::{
  50. baseedit::{
  51. repeat::{PressedKey, PressedKeysSmoothRepeat},
  52. ALLOWED_KEYCODES, DISALLOWED_CHARS,
  53. },
  54. DrawUpdate, OnModify, UIObject,
  55. };
  56. /// The travel threshold on long hold select before activating select.
  57. const HOLD_TRAVEL_THRESHOLD_SQ: f32 = 100.;
  58. /// How long to hold before select is enabled in ms.
  59. const HOLD_ENABLE_TIME: u128 = 500;
  60. /// Minimum dist to update scroll when finger scrolling.
  61. /// Avoid updating too much makes scrolling smoother.
  62. const VERT_SCROLL_UPDATE_INC: f32 = 1.;
  63. macro_rules! d { ($($arg:tt)*) => { debug!(target: "ui::chatedit", $($arg)*); } }
  64. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::chatedit", $($arg)*); } }
  65. #[derive(Clone)]
  66. enum TouchStateAction {
  67. Inactive,
  68. Started { pos: Point, instant: std::time::Instant },
  69. StartSelect,
  70. Select,
  71. DragSelectHandle { side: isize },
  72. ScrollVert { start_pos: Point, scroll_start: f32 },
  73. SetCursorPos,
  74. }
  75. struct TouchInfo {
  76. state: TouchStateAction,
  77. scroll: PropertyFloat32,
  78. }
  79. impl TouchInfo {
  80. fn new(scroll: PropertyFloat32) -> Self {
  81. Self { state: TouchStateAction::Inactive, scroll }
  82. }
  83. fn start(&mut self, pos: Point) {
  84. debug!(target: "ui::chatedit::touch", "start touch: Started state");
  85. self.state = TouchStateAction::Started { pos, instant: std::time::Instant::now() };
  86. }
  87. fn stop(&mut self) -> TouchStateAction {
  88. debug!(target: "ui::chatedit::touch", "stop touch: Inactive state");
  89. std::mem::replace(&mut self.state, TouchStateAction::Inactive)
  90. }
  91. fn update(&mut self, pos: &Point) {
  92. match &self.state {
  93. TouchStateAction::Started { pos: start_pos, instant } => {
  94. let travel_dist_sq = pos.dist_sq(*start_pos);
  95. let grad = (pos.y - start_pos.y) / (pos.x - start_pos.x);
  96. let elapsed = instant.elapsed().as_millis();
  97. //debug!(target: "ui::chatedit::touch", "TouchInfo::update() [travel_dist_sq={travel_dist_sq}, grad={grad}]");
  98. if travel_dist_sq < HOLD_TRAVEL_THRESHOLD_SQ {
  99. if elapsed > HOLD_ENABLE_TIME {
  100. debug!(target: "ui::chatedit::touch", "update touch state: Started -> StartSelect");
  101. self.state = TouchStateAction::StartSelect;
  102. }
  103. } else if grad.abs() > 0.5 {
  104. // Vertical movement
  105. debug!(target: "ui::chatedit::touch", "update touch state: Started -> ScrollVert");
  106. let scroll_start = self.scroll.get();
  107. self.state =
  108. TouchStateAction::ScrollVert { start_pos: *start_pos, scroll_start };
  109. } else {
  110. // Horizontal movement
  111. debug!(target: "ui::chatedit::touch", "update touch state: Started -> SetCursorPos");
  112. self.state = TouchStateAction::SetCursorPos;
  113. }
  114. }
  115. _ => {}
  116. }
  117. }
  118. }
  119. /*
  120. impl std::fmt::Debug for Editor {
  121. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  122. let mut changes = vec![];
  123. let sel = self.editor.raw_selection();
  124. if sel.is_collapsed() {
  125. let cursor = sel.focus().index();
  126. changes.push((cursor, '|'));
  127. } else {
  128. let sel = sel.text_range();
  129. changes.push((sel.start, '{'));
  130. changes.push((sel.end, '}'));
  131. }
  132. if let Some(compose) = self.editor.compose() {
  133. changes.push((compose.start, '['));
  134. changes.push((compose.end, ']'));
  135. }
  136. changes.sort_by(|a, b| b.0.cmp(&a.0));
  137. write!(f, "'")?;
  138. let mut buffer = self.editor.raw_text();
  139. for (byte_idx, c) in buffer.char_indices() {
  140. while let Some((idx, d)) = changes.last() {
  141. if *idx > byte_idx {
  142. break
  143. }
  144. write!(f, "{}", d)?;
  145. let _ = changes.pop();
  146. }
  147. write!(f, "{}", c)?;
  148. }
  149. write!(f, "'")
  150. }
  151. }
  152. */
  153. struct EditorHandle<'a> {
  154. guard: async_lock::MutexGuard<'a, Option<Editor>>,
  155. }
  156. impl<'a> Deref for EditorHandle<'a> {
  157. type Target = Editor;
  158. fn deref(&self) -> &Self::Target {
  159. self.guard.as_ref().unwrap()
  160. }
  161. }
  162. impl<'a> DerefMut for EditorHandle<'a> {
  163. fn deref_mut(&mut self) -> &mut Self::Target {
  164. self.guard.as_mut().unwrap()
  165. }
  166. }
  167. pub type ChatEditPtr = Arc<ChatEdit>;
  168. pub struct ChatEdit {
  169. node: SceneNodeWeak,
  170. tasks: SyncMutex<Vec<smol::Task<()>>>,
  171. render_api: RenderApi,
  172. key_repeat: SyncMutex<PressedKeysSmoothRepeat>,
  173. // Moves the draw cursor and applies scroll
  174. root_dc_key: u64,
  175. phone_select_handle_dc_key: u64,
  176. // Applies the clipping view
  177. content_dc_key: u64,
  178. select_dc_key: u64,
  179. text_dc_key: u64,
  180. cursor_dc_key: u64,
  181. cursor_mesh: SyncMutex<Option<GfxDrawMesh>>,
  182. is_active: PropertyBool,
  183. is_focused: PropertyBool,
  184. min_height: PropertyFloat32,
  185. max_height: PropertyFloat32,
  186. content_height: PropertyFloat32,
  187. rect: PropertyRect,
  188. baseline: PropertyFloat32,
  189. lineheight: PropertyFloat32,
  190. scroll: PropertyFloat32,
  191. scroll_speed: PropertyFloat32,
  192. padding: PropertyPtr,
  193. font_size: PropertyFloat32,
  194. text: PropertyStr,
  195. text_color: PropertyColor,
  196. text_hi_color: PropertyColor,
  197. //text_cmd_color: PropertyColor,
  198. cursor_color: PropertyColor,
  199. cursor_width: PropertyFloat32,
  200. cursor_ascent: PropertyFloat32,
  201. cursor_descent: PropertyFloat32,
  202. cursor_blink_time: PropertyUint32,
  203. cursor_idle_time: PropertyUint32,
  204. hi_bg_color: PropertyColor,
  205. //cmd_bg_color: PropertyColor,
  206. select_ascent: PropertyFloat32,
  207. select_descent: PropertyFloat32,
  208. handle_descent: PropertyFloat32,
  209. select_text: PropertyPtr,
  210. z_index: PropertyUint32,
  211. priority: PropertyUint32,
  212. debug: PropertyBool,
  213. mouse_btn_held: AtomicBool,
  214. cursor_is_visible: AtomicBool,
  215. blink_is_paused: AtomicBool,
  216. /// Used to explicitly hide the cursor. Must be manually re-enabled.
  217. hide_cursor: AtomicBool,
  218. touch_info: SyncMutex<TouchInfo>,
  219. is_phone_select: AtomicBool,
  220. window_scale: PropertyFloat32,
  221. parent_rect: SyncMutex<Option<Rectangle>>,
  222. is_mouse_hover: AtomicBool,
  223. editor: AsyncMutex<Option<Editor>>,
  224. }
  225. impl ChatEdit {
  226. pub async fn new(
  227. node: SceneNodeWeak,
  228. window_scale: PropertyFloat32,
  229. render_api: RenderApi,
  230. ) -> Pimpl {
  231. t!("ChatEdit::new()");
  232. let node_ref = &node.upgrade().unwrap();
  233. let is_active = PropertyBool::wrap(node_ref, Role::Internal, "is_active", 0).unwrap();
  234. let is_focused = PropertyBool::wrap(node_ref, Role::Internal, "is_focused", 0).unwrap();
  235. let min_height =
  236. PropertyFloat32::wrap(node_ref, Role::Internal, "height_range", 0).unwrap();
  237. let max_height =
  238. PropertyFloat32::wrap(node_ref, Role::Internal, "height_range", 1).unwrap();
  239. let content_height =
  240. PropertyFloat32::wrap(node_ref, Role::Internal, "content_height", 0).unwrap();
  241. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  242. let baseline = PropertyFloat32::wrap(node_ref, Role::Internal, "baseline", 0).unwrap();
  243. let lineheight = PropertyFloat32::wrap(node_ref, Role::Internal, "lineheight", 0).unwrap();
  244. let scroll = PropertyFloat32::wrap(node_ref, Role::Internal, "scroll", 0).unwrap();
  245. let scroll_speed =
  246. PropertyFloat32::wrap(node_ref, Role::Internal, "scroll_speed", 0).unwrap();
  247. let padding = node_ref.get_property("padding").unwrap();
  248. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  249. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  250. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  251. let text_hi_color = PropertyColor::wrap(node_ref, Role::Internal, "text_hi_color").unwrap();
  252. //let text_cmd_color =
  253. // PropertyColor::wrap(node_ref, Role::Internal, "text_cmd_color").unwrap();
  254. let cursor_color = PropertyColor::wrap(node_ref, Role::Internal, "cursor_color").unwrap();
  255. let cursor_width =
  256. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_width", 0).unwrap();
  257. let cursor_ascent =
  258. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_ascent", 0).unwrap();
  259. let cursor_descent =
  260. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_descent", 0).unwrap();
  261. let hi_bg_color = PropertyColor::wrap(node_ref, Role::Internal, "hi_bg_color").unwrap();
  262. //let cmd_bg_color = PropertyColor::wrap(node_ref, Role::Internal, "cmd_bg_color").unwrap();
  263. let select_ascent =
  264. PropertyFloat32::wrap(node_ref, Role::Internal, "select_ascent", 0).unwrap();
  265. let select_descent =
  266. PropertyFloat32::wrap(node_ref, Role::Internal, "select_descent", 0).unwrap();
  267. let handle_descent =
  268. PropertyFloat32::wrap(node_ref, Role::Internal, "handle_descent", 0).unwrap();
  269. let select_text = node_ref.get_property("select_text").unwrap();
  270. let cursor_blink_time =
  271. PropertyUint32::wrap(node_ref, Role::Internal, "cursor_blink_time", 0).unwrap();
  272. let cursor_idle_time =
  273. PropertyUint32::wrap(node_ref, Role::Internal, "cursor_idle_time", 0).unwrap();
  274. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  275. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  276. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  277. let self_ = Arc::new(Self {
  278. node,
  279. tasks: SyncMutex::new(vec![]),
  280. render_api,
  281. key_repeat: SyncMutex::new(PressedKeysSmoothRepeat::new(400, 50)),
  282. root_dc_key: OsRng.gen(),
  283. phone_select_handle_dc_key: OsRng.gen(),
  284. content_dc_key: OsRng.gen(),
  285. select_dc_key: OsRng.gen(),
  286. text_dc_key: OsRng.gen(),
  287. cursor_dc_key: OsRng.gen(),
  288. cursor_mesh: SyncMutex::new(None),
  289. is_active,
  290. is_focused,
  291. min_height,
  292. max_height,
  293. content_height,
  294. rect,
  295. baseline,
  296. lineheight: lineheight.clone(),
  297. scroll: scroll.clone(),
  298. scroll_speed,
  299. padding,
  300. font_size: font_size.clone(),
  301. text: text.clone(),
  302. text_color: text_color.clone(),
  303. text_hi_color,
  304. //text_cmd_color,
  305. cursor_color,
  306. cursor_width,
  307. cursor_ascent,
  308. cursor_descent,
  309. cursor_blink_time,
  310. cursor_idle_time,
  311. hi_bg_color,
  312. //cmd_bg_color,
  313. select_ascent,
  314. select_descent,
  315. handle_descent,
  316. select_text,
  317. z_index,
  318. priority,
  319. debug,
  320. mouse_btn_held: AtomicBool::new(false),
  321. cursor_is_visible: AtomicBool::new(true),
  322. blink_is_paused: AtomicBool::new(false),
  323. hide_cursor: AtomicBool::new(false),
  324. touch_info: SyncMutex::new(TouchInfo::new(scroll)),
  325. is_phone_select: AtomicBool::new(false),
  326. window_scale: window_scale.clone(),
  327. parent_rect: SyncMutex::new(None),
  328. is_mouse_hover: AtomicBool::new(false),
  329. editor: AsyncMutex::new(None),
  330. });
  331. Pimpl::ChatEdit(self_)
  332. }
  333. fn node(&self) -> SceneNodePtr {
  334. self.node.upgrade().unwrap()
  335. }
  336. fn padding_top(&self) -> f32 {
  337. self.padding.get_f32(0).unwrap()
  338. }
  339. fn padding_bottom(&self) -> f32 {
  340. self.padding.get_f32(1).unwrap()
  341. }
  342. fn abs_to_local(&self, point: &mut Point) {
  343. let rect = self.rect.get();
  344. *point -= rect.pos();
  345. *point -= self.inner_pos();
  346. point.y += self.scroll.get();
  347. }
  348. /// Inner position used for rendering
  349. fn inner_pos(&self) -> Point {
  350. let pad_top = self.padding_top();
  351. let pad_bot = self.padding_bottom();
  352. let content_height = self.content_height.get();
  353. let outer_height = content_height + pad_top + pad_bot;
  354. let rect_h = self.rect.get_height();
  355. let mut inner_pos = Point::zero();
  356. if outer_height < rect_h {
  357. // Min was applied to clip. Center content inside the rect.
  358. inner_pos.y = (rect_h - content_height) / 2.;
  359. } else {
  360. inner_pos.y = pad_top;
  361. }
  362. inner_pos
  363. }
  364. /// Maximum allowed scroll value
  365. /// * `content_height` measures the height of the actual content.
  366. /// * `outer_height` applies the inner padding.
  367. /// * `rect_h` then clips the `outer_height` to min/max values.
  368. /// We only allow scrolling when max clipping has been applied.
  369. fn max_scroll(&self) -> f32 {
  370. let content_height = self.content_height.get();
  371. let outer_height = content_height + self.padding_top() + self.padding_bottom();
  372. let rect_h = self.rect.get_height();
  373. //t!("max_scroll content_height={content_height}, rect_h={rect_h}");
  374. (outer_height - rect_h).max(0.)
  375. }
  376. /// Gets the real cursor pos within the rect.
  377. async fn get_cursor_pos(&self) -> Point {
  378. // This is the position within the content.
  379. let cursor_pos = self.lock_editor().await.get_cursor_pos();
  380. // Apply the inner padding
  381. cursor_pos + self.inner_pos()
  382. }
  383. /// Lazy-initializes the editor and returns a handle to it
  384. async fn lock_editor<'a>(&'a self) -> EditorHandle<'a> {
  385. EditorHandle { guard: self.editor.lock().await }
  386. }
  387. fn regen_cursor_mesh(&self) -> GfxDrawMesh {
  388. let cursor_width = self.cursor_width.get();
  389. let cursor_ascent = self.cursor_ascent.get();
  390. let cursor_descent = self.cursor_descent.get();
  391. let baseline = self.baseline.get();
  392. let cursor_rect = Rectangle {
  393. x: 0.,
  394. y: baseline - cursor_ascent,
  395. w: cursor_width,
  396. h: cursor_ascent + cursor_descent,
  397. };
  398. let cursor_color = self.cursor_color.get();
  399. let mut mesh = MeshBuilder::new(gfxtag!("chatedit_cursor"));
  400. mesh.draw_filled_box(&cursor_rect, cursor_color);
  401. mesh.alloc(&self.render_api).draw_untextured()
  402. }
  403. fn draw_phone_select_handle(&self, mesh: &mut MeshBuilder, pos: Point, side: f32) {
  404. let scroll = self.scroll.get();
  405. let baseline = self.baseline.get();
  406. let select_ascent = self.select_ascent.get();
  407. let handle_descent = self.handle_descent.get();
  408. let color = self.text_hi_color.get();
  409. // Transparent for fade
  410. let mut color_trans = color.clone();
  411. color_trans[3] = 0.;
  412. let x = pos.x;
  413. let mut y = pos.y + baseline;
  414. if y - scroll < 0. {
  415. return
  416. }
  417. // Vertical line downwards. We use this instead of draw_box() so we have a fade.
  418. let verts = vec![
  419. Vertex { pos: [x - side * 1., y - select_ascent], color: color_trans, uv: [0., 0.] },
  420. Vertex { pos: [x + side * 4., y - select_ascent], color: color_trans, uv: [0., 0.] },
  421. Vertex { pos: [x - side * 1., y + handle_descent + 5.], color, uv: [0., 0.] },
  422. Vertex { pos: [x + side * 4., y + handle_descent + 5.], color, uv: [0., 0.] },
  423. ];
  424. let indices = vec![0, 2, 1, 1, 2, 3];
  425. mesh.append(verts, indices);
  426. y += handle_descent;
  427. // The arrow itself.
  428. // Go anti-clockwise
  429. let verts = vec![
  430. Vertex { pos: [x, y], color, uv: [0., 0.] },
  431. Vertex { pos: [x, y + 50.], color, uv: [0., 0.] },
  432. Vertex { pos: [x + side * 30., y + 50.], color, uv: [0., 0.] },
  433. Vertex { pos: [x + side * 50., y + 25.], color, uv: [0., 0.] },
  434. ];
  435. let indices = vec![0, 1, 2, 0, 2, 3];
  436. mesh.append(verts, indices);
  437. }
  438. async fn change_focus(self: Arc<Self>, batch: BatchGuardPtr) {
  439. if !self.is_active.get() {
  440. return
  441. }
  442. t!("Focus changed");
  443. let atom = &mut batch.spawn();
  444. // Cursor visibility will change so just redraw everything lol
  445. self.redraw(atom).await;
  446. }
  447. async fn handle_shortcut(
  448. &self,
  449. key: char,
  450. mods: &KeyMods,
  451. atom: &mut PropertyAtomicGuard,
  452. ) -> bool {
  453. t!("handle_shortcut({:?}, {:?})", key, mods);
  454. #[cfg(not(target_os = "macos"))]
  455. let action_mod = mods.ctrl;
  456. #[cfg(target_os = "macos")]
  457. let action_mod = mods.logo;
  458. match key {
  459. 'a' => {
  460. if action_mod {
  461. let mut txt_ctx = text2::TEXT_CTX.get().await;
  462. let mut editor = self.lock_editor().await;
  463. let mut drv = editor.driver(&mut txt_ctx).unwrap();
  464. drv.select_all();
  465. if let Some(seltext) = editor.selected_text() {
  466. self.select_text.clone().set_str(atom, Role::Internal, 0, seltext).unwrap();
  467. }
  468. }
  469. }
  470. 'c' => {
  471. if action_mod {
  472. let editor = self.lock_editor().await;
  473. if let Some(txt) = editor.selected_text() {
  474. miniquad::window::clipboard_set(&txt);
  475. }
  476. }
  477. }
  478. 'v' => {
  479. if action_mod {
  480. if let Some(txt) = miniquad::window::clipboard_get() {
  481. self.insert(&txt, atom).await;
  482. // Maybe insert should call this?
  483. self.apply_cursor_scrolling(atom).await;
  484. }
  485. }
  486. }
  487. _ => return false,
  488. }
  489. self.redraw(atom).await;
  490. true
  491. }
  492. async fn handle_key(
  493. &self,
  494. key: &KeyCode,
  495. mods: &KeyMods,
  496. atom: &mut PropertyAtomicGuard,
  497. ) -> bool {
  498. #[cfg(not(target_os = "macos"))]
  499. let action_mod = mods.ctrl;
  500. #[cfg(target_os = "macos")]
  501. let action_mod = mods.logo;
  502. t!("handle_key({:?}, {:?}) action_mod={action_mod}", key, mods);
  503. let mut txt_ctx = text2::TEXT_CTX.get().await;
  504. let mut editor = self.lock_editor().await;
  505. let mut drv = editor.driver(&mut txt_ctx).unwrap();
  506. match key {
  507. KeyCode::Left => {
  508. if action_mod {
  509. if mods.shift {
  510. drv.select_word_left();
  511. } else {
  512. drv.move_word_left();
  513. }
  514. } else if mods.shift {
  515. drv.select_left();
  516. } else {
  517. drv.move_left();
  518. }
  519. }
  520. KeyCode::Right => {
  521. if action_mod {
  522. if mods.shift {
  523. drv.select_word_right();
  524. } else {
  525. drv.move_word_right();
  526. }
  527. } else if mods.shift {
  528. drv.select_right();
  529. } else {
  530. drv.move_right();
  531. }
  532. }
  533. KeyCode::Up => {
  534. if mods.shift {
  535. drv.select_up();
  536. } else {
  537. drv.move_up();
  538. }
  539. }
  540. KeyCode::Down => {
  541. if mods.shift {
  542. drv.select_down();
  543. } else {
  544. drv.move_down();
  545. }
  546. }
  547. KeyCode::Enter | KeyCode::KpEnter => {
  548. if mods.shift {
  549. drv.insert_or_replace_selection("\n");
  550. editor.on_buffer_changed(atom).await;
  551. } else {
  552. //let node = self.node.upgrade().unwrap();
  553. //node.trigger("enter_pressed", vec![]).await.unwrap();
  554. return false;
  555. }
  556. }
  557. KeyCode::Delete => {
  558. if action_mod {
  559. drv.delete_word();
  560. } else {
  561. drv.delete();
  562. }
  563. editor.on_buffer_changed(atom).await;
  564. }
  565. KeyCode::Backspace => {
  566. if action_mod {
  567. drv.backdelete_word();
  568. } else {
  569. drv.backdelete();
  570. }
  571. editor.on_buffer_changed(atom).await;
  572. }
  573. KeyCode::Home => {
  574. if action_mod {
  575. if mods.shift {
  576. drv.select_to_text_start();
  577. } else {
  578. drv.move_to_text_start();
  579. }
  580. } else if mods.shift {
  581. drv.select_to_line_start();
  582. } else {
  583. drv.move_to_line_start();
  584. }
  585. }
  586. KeyCode::End => {
  587. if action_mod {
  588. if mods.shift {
  589. drv.select_to_text_end();
  590. } else {
  591. drv.move_to_text_end();
  592. }
  593. } else if mods.shift {
  594. drv.select_to_line_end();
  595. } else {
  596. drv.move_to_line_end();
  597. }
  598. }
  599. _ => return false,
  600. }
  601. if let Some(seltext) = editor.selected_text() {
  602. self.select_text.clone().set_str(atom, Role::Internal, 0, seltext).unwrap();
  603. } else {
  604. self.select_text.clone().set_null(atom, Role::Internal, 0).unwrap();
  605. }
  606. drop(editor);
  607. drop(txt_ctx);
  608. self.apply_cursor_scrolling(atom).await;
  609. self.pause_blinking();
  610. self.redraw(atom).await;
  611. return true
  612. }
  613. /// This will select the entire word rather than move the cursor to that location
  614. async fn start_touch_select(&self, touch_pos: Point, atom: &mut PropertyAtomicGuard) {
  615. t!("start_touch_select({touch_pos:?})");
  616. let mut editor = self.lock_editor().await;
  617. editor.select_word_at_point(touch_pos);
  618. editor.refresh().await;
  619. let seltext = editor.selected_text().unwrap();
  620. d!("Selected {seltext:?} from {touch_pos:?}");
  621. self.select_text.clone().set_str(atom, Role::Internal, 0, seltext).unwrap();
  622. drop(editor);
  623. // if start != end {
  624. self.is_phone_select.store(true, Ordering::Relaxed);
  625. self.hide_cursor.store(true, Ordering::Relaxed);
  626. // }
  627. }
  628. async fn handle_touch_start(&self, touch_pos: Point) -> bool {
  629. t!("handle_touch_start({touch_pos:?})");
  630. let rect = self.rect.get();
  631. if !rect.contains(touch_pos) {
  632. t!("rect!cont rect={rect:?}, touch_pos={touch_pos:?}");
  633. return false
  634. }
  635. if self.try_handle_drag(touch_pos).await {
  636. return true
  637. }
  638. let mut touch_info = self.touch_info.lock();
  639. touch_info.start(touch_pos);
  640. true
  641. }
  642. async fn get_select_handles(&self) -> Option<(Point, Point)> {
  643. let editor = self.lock_editor().await;
  644. let layout = editor.layout();
  645. let sel = editor.selection();
  646. if sel.is_collapsed() {
  647. assert!(!self.is_phone_select.load(Ordering::Relaxed));
  648. return None
  649. }
  650. let first = Rectangle::from(sel.anchor().geometry(layout, 0.)).pos();
  651. let last = Rectangle::from(sel.focus().geometry(layout, 0.)).pos();
  652. Some((first, last))
  653. }
  654. async fn try_handle_drag(&self, mut touch_pos: Point) -> bool {
  655. let Some((mut first, mut last)) = self.get_select_handles().await else { return false };
  656. self.abs_to_local(&mut touch_pos);
  657. t!("localize touch_pos = {touch_pos:?}");
  658. let baseline = self.baseline.get();
  659. let handle_off_y = self.handle_descent.get();
  660. first.y += baseline + handle_off_y;
  661. last.y += baseline + handle_off_y;
  662. // Are we within range of either one?
  663. t!("handle center points = ({first:?}, {last:?})");
  664. const TOUCH_RADIUS_SQ: f32 = 10_000.;
  665. let first_dist_sq = first.dist_sq(touch_pos);
  666. let last_dist_sq = last.dist_sq(touch_pos);
  667. let is_first = first_dist_sq <= TOUCH_RADIUS_SQ;
  668. let is_last = last_dist_sq <= TOUCH_RADIUS_SQ;
  669. let mut side = 0;
  670. if is_first && is_last {
  671. // Are we closer to the first or last?
  672. // Break the tie
  673. if first_dist_sq < last_dist_sq {
  674. side = -1;
  675. } else {
  676. side = 1;
  677. }
  678. } else if is_first {
  679. side = -1;
  680. } else if is_last {
  681. side = 1;
  682. }
  683. if side != 0 {
  684. d!("start touch: DragSelectHandle state [side={side}]");
  685. // Set touch_state status to enable begin dragging them
  686. let mut touch_info = self.touch_info.lock();
  687. touch_info.state = TouchStateAction::DragSelectHandle { side };
  688. return true
  689. }
  690. false
  691. }
  692. async fn handle_touch_move(&self, mut touch_pos: Point) -> bool {
  693. //t!("handle_touch_move({touch_pos:?})");
  694. let atom = &mut self.render_api.make_guard();
  695. // We must update with non relative touch_pos bcos when doing vertical scrolling
  696. // we will modify the scroll, which is used by abs_to_local(), which is used
  697. // to then calculate the max scroll. So it ends up jumping around.
  698. // We use the abs touch_pos without scroll adjust applied for vert scrolling.
  699. let touch_state = {
  700. let mut touch_info = self.touch_info.lock();
  701. touch_info.update(&touch_pos);
  702. touch_info.state.clone()
  703. };
  704. match &touch_state {
  705. TouchStateAction::Inactive => return false,
  706. TouchStateAction::StartSelect => {
  707. if self.text.get().is_empty() {
  708. self.node().trigger("paste_request", vec![]).await.unwrap();
  709. } else {
  710. self.abs_to_local(&mut touch_pos);
  711. self.start_touch_select(touch_pos, atom).await;
  712. self.redraw_select(atom.batch_id).await;
  713. }
  714. d!("touch state: StartSelect -> Select");
  715. self.touch_info.lock().state = TouchStateAction::Select;
  716. }
  717. TouchStateAction::DragSelectHandle { side } => {
  718. let handle_descent = self.handle_descent.get();
  719. self.abs_to_local(&mut touch_pos);
  720. let editor = self.lock_editor().await;
  721. let sel = editor.selection();
  722. assert!(*side == -1 || *side == 1);
  723. assert!(self.is_phone_select.load(Ordering::Relaxed));
  724. assert!(!sel.is_collapsed());
  725. let mut pos = touch_pos;
  726. // Only allow selecting text that is visible in the box
  727. // We do our calcs relative to (0, 0) so bhs = rect_h
  728. pos.y -= handle_descent + 25.;
  729. //let bhs = wrapped_lines.height();
  730. //pos.y = min_f32(pos.y, bhs);
  731. let mut select = sel.text_range();
  732. let layout = editor.layout();
  733. t!("select (pre): {:?}", sel.text_range());
  734. let cursor = parley::Cursor::from_point(layout, pos.x, pos.y).index();
  735. t!("cursor: {cursor}");
  736. // The selection is NOT allowed to cross over itself.
  737. if *side == -1 {
  738. let max_start = sel.focus().previous_visual(layout).index();
  739. t!("side == -1 max={max_start}");
  740. select.start = std::cmp::min(cursor, max_start);
  741. } else {
  742. assert_eq!(*side, 1);
  743. let min_end = sel.anchor().next_visual(layout).index();
  744. t!("side == +1 min={min_end}");
  745. select.end = std::cmp::max(cursor, min_end);
  746. };
  747. t!("set_select({select:?})");
  748. editor.set_selection(select.start, select.end);
  749. drop(editor);
  750. self.redraw_select(atom.batch_id).await;
  751. }
  752. TouchStateAction::ScrollVert { start_pos, scroll_start } => {
  753. let y_dist = start_pos.y - touch_pos.y;
  754. let mut scroll = scroll_start + y_dist;
  755. scroll = scroll.clamp(0., self.max_scroll());
  756. if (self.scroll.get() - scroll).abs() < VERT_SCROLL_UPDATE_INC {
  757. return true
  758. }
  759. self.scroll.set(atom, scroll);
  760. self.redraw_scroll(atom.batch_id).await;
  761. }
  762. TouchStateAction::SetCursorPos => {
  763. // TBH I can't even see the cursor under my thumb so I'll just
  764. // comment this for now.
  765. }
  766. _ => {}
  767. }
  768. true
  769. }
  770. async fn handle_touch_end(&self, atom: &mut PropertyAtomicGuard, mut touch_pos: Point) -> bool {
  771. //t!("handle_touch_end({touch_pos:?})");
  772. self.abs_to_local(&mut touch_pos);
  773. let state = self.touch_info.lock().stop();
  774. match state {
  775. TouchStateAction::Inactive => return false,
  776. TouchStateAction::Started { pos: _, instant: _ } | TouchStateAction::SetCursorPos => {
  777. self.touch_set_cursor_pos(atom, touch_pos).await;
  778. self.redraw(atom).await;
  779. }
  780. _ => {}
  781. }
  782. self.node().trigger("focus_request", vec![]).await.unwrap();
  783. true
  784. }
  785. async fn touch_set_cursor_pos(&self, atom: &mut PropertyAtomicGuard, touch_pos: Point) {
  786. t!("touch_set_cursor_pos({touch_pos:?})");
  787. let mut editor = self.lock_editor().await;
  788. editor.move_to_pos(touch_pos);
  789. editor.refresh().await;
  790. drop(editor);
  791. self.pause_blinking();
  792. self.finish_select(atom);
  793. }
  794. fn finish_select(&self, atom: &mut PropertyAtomicGuard) {
  795. self.is_phone_select.store(false, Ordering::Relaxed);
  796. self.hide_cursor.store(false, Ordering::Relaxed);
  797. self.select_text.clone().set_null(atom, Role::Internal, 0).unwrap();
  798. }
  799. /// Whenever the cursor is modified this MUST be called
  800. /// to recalculate the scroll y property.
  801. async fn apply_cursor_scrolling(&self, atom: &mut PropertyAtomicGuard) {
  802. let mut scroll = self.scroll.get();
  803. let rect_h = self.rect.get_height();
  804. let cursor_y0 = self.get_cursor_pos().await.y;
  805. let cursor_h = self.baseline.get() + self.cursor_descent.get();
  806. // The bottom
  807. let cursor_y1 = cursor_y0 + cursor_h;
  808. //t!("apply_cursor_scrolling() cursor = [{cursor_y0}, {cursor_y1}] rect_h={rect_h} scroll={scroll}");
  809. if cursor_y1 > rect_h + scroll {
  810. //t!(" cursor bottom below rect");
  811. // We want cursor_y1 = rect_h + scroll by adjusting scroll
  812. scroll = cursor_y1 - rect_h;
  813. self.scroll.set(atom, scroll);
  814. } else if cursor_y0 < scroll {
  815. //t!(" cursor top above rect");
  816. scroll = cursor_y0;
  817. self.scroll.set(atom, scroll);
  818. }
  819. }
  820. fn pause_blinking(&self) {
  821. self.blink_is_paused.store(true, Ordering::Relaxed);
  822. self.cursor_is_visible.store(true, Ordering::Relaxed);
  823. }
  824. async fn redraw(&self, atom: &mut PropertyAtomicGuard) {
  825. let trace_id = rand::random();
  826. let timest = unixtime();
  827. let draw_update = self.make_draw_calls(trace_id, atom).await;
  828. self.render_api.replace_draw_calls(atom.batch_id, timest, draw_update.draw_calls);
  829. }
  830. /// Called when scroll changes. Moves content up or down. Nothing more.
  831. async fn redraw_scroll(&self, batch_id: BatchGuardId) {
  832. let timest = unixtime();
  833. let rect = self.rect.get();
  834. let scroll = self.scroll.get();
  835. let phone_sel_instrs = self.regen_phone_select_handle_mesh().await;
  836. let mut content_instrs = vec![
  837. GfxDrawInstruction::ApplyView(rect.with_zero_pos()),
  838. GfxDrawInstruction::Move(Point::new(0., -scroll)),
  839. ];
  840. let mut bg_instrs = self.regen_bg_mesh();
  841. content_instrs.append(&mut bg_instrs);
  842. let draw_main = vec![
  843. (
  844. self.content_dc_key,
  845. GfxDrawCall::new(
  846. content_instrs,
  847. vec![self.text_dc_key, self.cursor_dc_key, self.select_dc_key],
  848. 0,
  849. "chatedit_content",
  850. ),
  851. ),
  852. (
  853. self.phone_select_handle_dc_key,
  854. GfxDrawCall::new(phone_sel_instrs, vec![], 1, "chatedit_phone_sel_scroll"),
  855. ),
  856. ];
  857. self.render_api.replace_draw_calls(batch_id, timest, draw_main);
  858. }
  859. async fn redraw_cursor(&self, batch_id: BatchGuardId) {
  860. let timest = unixtime();
  861. let instrs = self.get_cursor_instrs().await;
  862. let draw_calls =
  863. vec![(self.cursor_dc_key, GfxDrawCall::new(instrs, vec![], 2, "curs_redr"))];
  864. self.render_api.replace_draw_calls(batch_id, timest, draw_calls);
  865. }
  866. async fn redraw_select(&self, batch_id: BatchGuardId) {
  867. let timest = unixtime();
  868. let sel_instrs = self.regen_select_mesh().await;
  869. let phone_sel_instrs = self.regen_phone_select_handle_mesh().await;
  870. let draw_calls = vec![
  871. (self.select_dc_key, GfxDrawCall::new(sel_instrs, vec![], 0, "chatedit_sel")),
  872. (
  873. self.phone_select_handle_dc_key,
  874. GfxDrawCall::new(phone_sel_instrs, vec![], 1, "chatedit_phone_sel_redraw_sel"),
  875. ),
  876. ];
  877. self.render_api.replace_draw_calls(batch_id, timest, draw_calls);
  878. }
  879. async fn get_cursor_instrs(&self) -> Vec<GfxDrawInstruction> {
  880. if !self.is_focused.get() ||
  881. !self.cursor_is_visible.load(Ordering::Relaxed) ||
  882. self.hide_cursor.load(Ordering::Relaxed)
  883. {
  884. return vec![]
  885. }
  886. let cursor_mesh =
  887. self.cursor_mesh.lock().get_or_insert_with(|| self.regen_cursor_mesh()).clone();
  888. vec![
  889. GfxDrawInstruction::Move(self.get_cursor_pos().await),
  890. GfxDrawInstruction::Draw(cursor_mesh),
  891. ]
  892. }
  893. fn regen_bg_mesh(&self) -> Vec<GfxDrawInstruction> {
  894. if !self.debug.get() {
  895. return vec![]
  896. }
  897. let padding_top = self.padding_top();
  898. let padding_bottom = self.padding_bottom();
  899. let mut rect = self.rect.get().with_zero_pos();
  900. let mut mesh = MeshBuilder::new(gfxtag!("chatedit_bg"));
  901. mesh.draw_outline(&rect, [0., 1., 0., 1.], 1.);
  902. rect.y = padding_top;
  903. rect.h -= padding_top + padding_bottom;
  904. mesh.draw_outline(&rect, [0., 1., 0., 0.5], 1.);
  905. vec![GfxDrawInstruction::Draw(mesh.alloc(&self.render_api).draw_untextured())]
  906. }
  907. async fn regen_txt_mesh(&self) -> Vec<GfxDrawInstruction> {
  908. let mut instrs = vec![GfxDrawInstruction::Move(self.inner_pos())];
  909. let editor = self.lock_editor().await;
  910. let layout = editor.layout();
  911. let mut render_instrs =
  912. text2::render_layout(layout, &self.render_api, gfxtag!("chatedit_txt_mesh"));
  913. instrs.append(&mut render_instrs);
  914. instrs
  915. }
  916. async fn regen_select_mesh(&self) -> Vec<GfxDrawInstruction> {
  917. let mut instrs = vec![GfxDrawInstruction::Move(self.inner_pos())];
  918. let editor = self.lock_editor().await;
  919. let layout = editor.layout();
  920. let sel = editor.selection();
  921. let sel_color = self.hi_bg_color.get();
  922. if !sel.is_collapsed() {
  923. let mut mesh = MeshBuilder::new(gfxtag!("chatedit_select_mesh"));
  924. sel.geometry_with(layout, |rect: parley::Rect, _| {
  925. mesh.draw_filled_box(&rect.into(), sel_color);
  926. });
  927. instrs.push(GfxDrawInstruction::Draw(mesh.alloc(&self.render_api).draw_untextured()));
  928. }
  929. instrs
  930. }
  931. async fn regen_phone_select_handle_mesh(&self) -> Vec<GfxDrawInstruction> {
  932. if !self.is_phone_select.load(Ordering::Relaxed) {
  933. return vec![]
  934. }
  935. //t!("regen_phone_select_handle_mesh()");
  936. let (first, last) = self.get_select_handles().await.unwrap();
  937. let scroll = self.scroll.get();
  938. let editor = self.lock_editor().await;
  939. let sel = editor.selection();
  940. assert!(!sel.is_collapsed());
  941. let pos = self.inner_pos() + Point::new(0., -scroll);
  942. // We could cache this and use Move instead but why bother?
  943. let mut mesh = MeshBuilder::new(gfxtag!("chatedit_phone_select_handle"));
  944. self.draw_phone_select_handle(&mut mesh, first, -1.);
  945. self.draw_phone_select_handle(&mut mesh, last, 1.);
  946. vec![
  947. GfxDrawInstruction::Move(pos),
  948. GfxDrawInstruction::Draw(mesh.alloc(&self.render_api).draw_untextured()),
  949. ]
  950. }
  951. fn bounded_height(&self, height: f32) -> f32 {
  952. height.clamp(self.min_height.get(), self.max_height.get())
  953. }
  954. async fn eval_rect(&self, atom: &mut PropertyAtomicGuard) {
  955. let parent_rect = self.parent_rect.lock().clone().unwrap();
  956. // First we evaluate the width based off the parent dimensions
  957. self.rect
  958. .eval_with(
  959. atom,
  960. vec![2],
  961. vec![
  962. ("parent_w".to_string(), parent_rect.w),
  963. ("parent_h".to_string(), parent_rect.h),
  964. ],
  965. )
  966. .unwrap();
  967. // Use the width to adjust the height calcs
  968. let rect_w = self.rect.get_width();
  969. let content_height = {
  970. let mut editor = self.lock_editor().await;
  971. editor.set_width(rect_w);
  972. editor.refresh().await;
  973. editor.height()
  974. };
  975. self.content_height.set(atom, content_height);
  976. let outer_height = content_height + self.padding_top() + self.padding_bottom();
  977. let rect_h = self.bounded_height(outer_height);
  978. self.rect.prop().set_f32(atom, Role::Internal, 3, rect_h).unwrap();
  979. // Finally calculate the position
  980. self.rect
  981. .eval_with(
  982. atom,
  983. vec![0, 1],
  984. vec![
  985. ("parent_w".to_string(), parent_rect.w),
  986. ("parent_h".to_string(), parent_rect.h),
  987. ("rect_w".to_string(), rect_w),
  988. ("rect_h".to_string(), rect_h),
  989. ],
  990. )
  991. .unwrap();
  992. }
  993. async fn make_draw_calls(&self, _trace_id: u32, atom: &mut PropertyAtomicGuard) -> DrawUpdate {
  994. self.eval_rect(atom).await;
  995. let rect = self.rect.get();
  996. let max_scroll = self.max_scroll();
  997. let mut scroll = self.scroll.get();
  998. if scroll > max_scroll {
  999. scroll = max_scroll;
  1000. self.scroll.set(atom, scroll);
  1001. }
  1002. let cursor_instrs = self.get_cursor_instrs().await;
  1003. let txt_instrs = self.regen_txt_mesh().await;
  1004. let sel_instrs = self.regen_select_mesh().await;
  1005. let phone_sel_instrs = self.regen_phone_select_handle_mesh().await;
  1006. let mut content_instrs = vec![
  1007. GfxDrawInstruction::ApplyView(rect.with_zero_pos()),
  1008. GfxDrawInstruction::Move(Point::new(0., -scroll)),
  1009. ];
  1010. let mut bg_instrs = self.regen_bg_mesh();
  1011. content_instrs.append(&mut bg_instrs);
  1012. // + root (move)
  1013. // -+ content (apply view)
  1014. // └╴select
  1015. // └╴text
  1016. // └╴cursor
  1017. // - phone_handle
  1018. // Why do we have such a complicated layout?
  1019. // Firstly phone select handles should never be clipped. So we must draw them outside
  1020. // of ApplyView.
  1021. // Then when adjusting selection, it's slow to redraw everything, so the selection
  1022. // must be drawn separately.
  1023. // Lastly the cursor is blinking and that's on top but with clipping.
  1024. DrawUpdate {
  1025. key: self.root_dc_key,
  1026. draw_calls: vec![
  1027. (
  1028. self.root_dc_key,
  1029. GfxDrawCall::new(
  1030. vec![GfxDrawInstruction::Move(rect.pos())],
  1031. vec![self.content_dc_key, self.phone_select_handle_dc_key],
  1032. self.z_index.get(),
  1033. "chatedit_root",
  1034. ),
  1035. ),
  1036. (
  1037. self.content_dc_key,
  1038. GfxDrawCall::new(
  1039. content_instrs,
  1040. vec![self.text_dc_key, self.cursor_dc_key, self.select_dc_key],
  1041. 0,
  1042. "chatedit_content",
  1043. ),
  1044. ),
  1045. (self.select_dc_key, GfxDrawCall::new(sel_instrs, vec![], 0, "chatedit_sel")),
  1046. (self.text_dc_key, GfxDrawCall::new(txt_instrs, vec![], 1, "chatedit_text")),
  1047. (self.cursor_dc_key, GfxDrawCall::new(cursor_instrs, vec![], 2, "chatedit_curs")),
  1048. (
  1049. self.phone_select_handle_dc_key,
  1050. GfxDrawCall::new(phone_sel_instrs, vec![], 1, "chatedit_phone_sel"),
  1051. ),
  1052. ],
  1053. }
  1054. }
  1055. async fn insert(&self, txt: &str, atom: &mut PropertyAtomicGuard) {
  1056. let mut editor = self.lock_editor().await;
  1057. editor.insert(txt, atom).await;
  1058. }
  1059. async fn process_insert_text_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  1060. let Ok(method_call) = sub.receive().await else {
  1061. debug!(target: "ui::chatedit", "Event relayer closed");
  1062. return false
  1063. };
  1064. t!("method called: insert_line({method_call:?})");
  1065. assert!(method_call.send_res.is_none());
  1066. fn decode_data(data: &[u8]) -> std::io::Result<String> {
  1067. let mut cur = Cursor::new(&data);
  1068. let text = String::decode(&mut cur)?;
  1069. Ok(text)
  1070. }
  1071. let Ok(text) = decode_data(&method_call.data) else {
  1072. error!(target: "ui::chatedit", "insert_text() method invalid arg data");
  1073. return true
  1074. };
  1075. let Some(self_) = me.upgrade() else {
  1076. // Should not happen
  1077. panic!("self destroyed before insert_text_method_task was stopped!");
  1078. };
  1079. let atom = &mut self_.render_api.make_guard();
  1080. self_.insert(&text, atom).await;
  1081. self_.redraw(atom).await;
  1082. true
  1083. }
  1084. async fn process_focus_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  1085. let Ok(method_call) = sub.receive().await else {
  1086. debug!(target: "ui::chatedit", "Event relayer closed");
  1087. return false
  1088. };
  1089. t!("method called: focus({method_call:?})");
  1090. assert!(method_call.send_res.is_none());
  1091. assert!(method_call.data.is_empty());
  1092. let Some(self_) = me.upgrade() else {
  1093. // Should not happen
  1094. panic!("self destroyed before insert_text_method_task was stopped!");
  1095. };
  1096. let editor = self_.lock_editor().await;
  1097. editor.focus();
  1098. true
  1099. }
  1100. async fn process_unfocus_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  1101. let Ok(method_call) = sub.receive().await else {
  1102. debug!(target: "ui::chatedit", "Event relayer closed");
  1103. return false
  1104. };
  1105. t!("method called: focus({method_call:?})");
  1106. assert!(method_call.send_res.is_none());
  1107. assert!(method_call.data.is_empty());
  1108. let Some(self_) = me.upgrade() else {
  1109. // Should not happen
  1110. panic!("self destroyed before insert_text_method_task was stopped!");
  1111. };
  1112. let editor = self_.lock_editor().await;
  1113. editor.unfocus();
  1114. true
  1115. }
  1116. #[cfg(target_os = "android")]
  1117. async fn handle_android_event(&self, ev: AndroidSuggestEvent) {
  1118. t!("handle_android_event({ev:?})");
  1119. if !self.is_active.get() {
  1120. return
  1121. }
  1122. match ev {
  1123. AndroidSuggestEvent::Init => {
  1124. let mut editor = self.lock_editor().await;
  1125. editor.init();
  1126. // For debugging select, enable these and set a selection in the editor.
  1127. //self.is_phone_select.store(true, Ordering::Relaxed);
  1128. //self.hide_cursor.store(true, Ordering::Relaxed);
  1129. // Debug code if we set text in editor.init()
  1130. //let atom = &mut PropertyAtomicGuard::new();
  1131. //editor.on_buffer_changed(atom).await;
  1132. return
  1133. }
  1134. AndroidSuggestEvent::CreateInputConnect => {
  1135. let mut editor = self.lock_editor().await;
  1136. editor.setup();
  1137. }
  1138. // Destructive text edits
  1139. AndroidSuggestEvent::ComposeRegion { .. } |
  1140. AndroidSuggestEvent::FinishCompose |
  1141. AndroidSuggestEvent::Compose { .. } |
  1142. AndroidSuggestEvent::DeleteSurroundingText { .. } => {
  1143. // Any editing will collapse selections
  1144. self.is_phone_select.store(false, Ordering::Relaxed);
  1145. self.hide_cursor.store(false, Ordering::Relaxed);
  1146. let atom = &mut PropertyAtomicGuard::new();
  1147. self.finish_select(atom);
  1148. let mut editor = self.lock_editor().await;
  1149. editor.on_buffer_changed(atom).await;
  1150. drop(editor);
  1151. self.apply_cursor_scrolling(atom).await;
  1152. }
  1153. }
  1154. // Only redraw once we have the parent_rect
  1155. // Can happen when we receive an Android event before the canvas is ready
  1156. if self.parent_rect.lock().is_some() {
  1157. self.redraw().await;
  1158. }
  1159. }
  1160. }
  1161. impl Drop for ChatEdit {
  1162. fn drop(&mut self) {
  1163. let atom = self.render_api.make_guard();
  1164. self.render_api.replace_draw_calls(
  1165. atom.batch_id,
  1166. unixtime(),
  1167. vec![(self.text_dc_key, Default::default())],
  1168. );
  1169. }
  1170. }
  1171. #[async_trait]
  1172. impl UIObject for ChatEdit {
  1173. fn priority(&self) -> u32 {
  1174. self.priority.get()
  1175. }
  1176. fn init(&self) {
  1177. let mut guard = self.editor.lock_blocking();
  1178. assert!(guard.is_none());
  1179. *guard = Some(Editor::new(
  1180. self.text.clone(),
  1181. self.font_size.clone(),
  1182. self.text_color.clone(),
  1183. self.window_scale.clone(),
  1184. self.lineheight.clone(),
  1185. ));
  1186. }
  1187. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  1188. let me = Arc::downgrade(&self);
  1189. let node_ref = &self.node.upgrade().unwrap();
  1190. let method_sub = node_ref.subscribe_method_call("insert_text").unwrap();
  1191. let me2 = me.clone();
  1192. let insert_text_task =
  1193. ex.spawn(
  1194. async move { while Self::process_insert_text_method(&me2, &method_sub).await {} },
  1195. );
  1196. let method_sub = node_ref.subscribe_method_call("focus").unwrap();
  1197. let me2 = me.clone();
  1198. let focus_task =
  1199. ex.spawn(async move { while Self::process_focus_method(&me2, &method_sub).await {} });
  1200. let method_sub = node_ref.subscribe_method_call("unfocus").unwrap();
  1201. let me2 = me.clone();
  1202. let unfocus_task =
  1203. ex.spawn(async move { while Self::process_unfocus_method(&me2, &method_sub).await {} });
  1204. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  1205. on_modify.when_change(self.is_focused.prop(), Self::change_focus);
  1206. // When text has been changed.
  1207. // Cursor and selection might be invalidated.
  1208. async fn reset(self_: Arc<ChatEdit>, batch: BatchGuardPtr) {
  1209. let atom = &mut batch.spawn();
  1210. //self_.select_text.set_null(Role::Internal, 0).unwrap();
  1211. self_.scroll.set(atom, 0.);
  1212. self_.redraw(atom).await;
  1213. }
  1214. async fn redraw(self_: Arc<ChatEdit>, batch: BatchGuardPtr) {
  1215. let atom = &mut batch.spawn();
  1216. self_.redraw(atom).await;
  1217. }
  1218. async fn set_text(self_: Arc<ChatEdit>, batch: BatchGuardPtr) {
  1219. self_.lock_editor().await.on_text_prop_changed().await;
  1220. let atom = &mut batch.spawn();
  1221. self_.redraw(atom).await;
  1222. }
  1223. on_modify.when_change(self.rect.prop(), redraw);
  1224. on_modify.when_change(self.baseline.prop(), redraw);
  1225. on_modify.when_change(self.lineheight.prop(), redraw);
  1226. on_modify.when_change(self.select_ascent.prop(), redraw);
  1227. on_modify.when_change(self.select_descent.prop(), redraw);
  1228. on_modify.when_change(self.handle_descent.prop(), redraw);
  1229. on_modify.when_change(self.padding.clone(), redraw);
  1230. on_modify.when_change(self.text.prop(), set_text);
  1231. // The commented properties are modified on input events
  1232. // So then redraw() will get repeatedly triggered when these properties
  1233. // are changed. We should find a solution. For now the hooks are disabled.
  1234. //on_modify.when_change(scroll.prop(), redraw);
  1235. //on_modify.when_change(cursor_pos.prop(), redraw);
  1236. on_modify.when_change(self.font_size.prop(), redraw);
  1237. // We must also reshape text
  1238. on_modify.when_change(self.text.prop(), reset);
  1239. on_modify.when_change(self.text_color.prop(), redraw);
  1240. on_modify.when_change(self.hi_bg_color.prop(), redraw);
  1241. //on_modify.when_change(selected.clone(), redraw);
  1242. on_modify.when_change(self.z_index.prop(), redraw);
  1243. on_modify.when_change(self.debug.prop(), redraw);
  1244. async fn regen_cursor(self_: Arc<ChatEdit>, _batch: BatchGuardPtr) {
  1245. // Free the cache
  1246. *self_.cursor_mesh.lock() = None;
  1247. }
  1248. on_modify.when_change(self.cursor_color.prop(), regen_cursor);
  1249. on_modify.when_change(self.cursor_ascent.prop(), regen_cursor);
  1250. on_modify.when_change(self.cursor_descent.prop(), regen_cursor);
  1251. on_modify.when_change(self.cursor_width.prop(), regen_cursor);
  1252. let me2 = me.clone();
  1253. let cursor_blink_time = self.cursor_blink_time.clone();
  1254. let cursor_idle_time = self.cursor_idle_time.clone();
  1255. let blinking_cursor_task = ex.spawn(async move {
  1256. loop {
  1257. msleep(cursor_blink_time.get() as u64).await;
  1258. let self_ = me2.upgrade().unwrap();
  1259. if self_.blink_is_paused.swap(false, Ordering::Relaxed) {
  1260. msleep(cursor_idle_time.get() as u64).await;
  1261. continue
  1262. }
  1263. if !self_.rect.has_cached() {
  1264. continue
  1265. }
  1266. // Invert the bool
  1267. self_.cursor_is_visible.fetch_not(Ordering::Relaxed);
  1268. let atom = &mut self_.render_api.make_guard();
  1269. self_.redraw_cursor(atom.batch_id).await;
  1270. }
  1271. });
  1272. let mut tasks = vec![insert_text_task, focus_task, unfocus_task, blinking_cursor_task];
  1273. tasks.append(&mut on_modify.tasks);
  1274. #[cfg(target_os = "android")]
  1275. {
  1276. let recvr = self.lock_editor().await.recvr.clone();
  1277. let me2 = me.clone();
  1278. let autosuggest_task = ex.spawn(async move {
  1279. loop {
  1280. let Ok(ev) = recvr.recv().await else {
  1281. t!("Event relayer closed");
  1282. break
  1283. };
  1284. let Some(self_) = me2.upgrade() else {
  1285. // Should not happen
  1286. panic!("self destroyed before autosuggest_task was stopped!");
  1287. };
  1288. self_.handle_android_event(ev).await;
  1289. }
  1290. });
  1291. tasks.push(autosuggest_task);
  1292. }
  1293. *self.tasks.lock() = tasks;
  1294. }
  1295. fn stop(&self) {
  1296. self.tasks.lock().clear();
  1297. *self.parent_rect.lock() = None;
  1298. self.key_repeat.lock().clear();
  1299. *self.cursor_mesh.lock() = None;
  1300. *self.editor.lock_blocking() = None;
  1301. }
  1302. async fn draw(
  1303. &self,
  1304. parent_rect: Rectangle,
  1305. trace_id: u32,
  1306. atom: &mut PropertyAtomicGuard,
  1307. ) -> Option<DrawUpdate> {
  1308. t!("ChatEdit::draw({:?}, {trace_id})", self.node());
  1309. *self.parent_rect.lock() = Some(parent_rect);
  1310. Some(self.make_draw_calls(trace_id, atom).await)
  1311. }
  1312. async fn handle_char(&self, key: char, mods: KeyMods, repeat: bool) -> bool {
  1313. t!("handle_char({key}, {mods:?}, {repeat})");
  1314. // First filter for only single digit keys
  1315. if DISALLOWED_CHARS.contains(&key) {
  1316. return false
  1317. }
  1318. if !self.is_focused.get() {
  1319. return false
  1320. }
  1321. // Must be updated before checking the mods. You can press ctrl+a, then release ctrl
  1322. // before a is released. Then the repeater never gets reset, and uses any old value
  1323. // it has from before for a.
  1324. let actions = {
  1325. let mut repeater = self.key_repeat.lock();
  1326. repeater.key_down(PressedKey::Char(key), repeat)
  1327. };
  1328. let atom = &mut self.render_api.make_guard();
  1329. if mods.ctrl || mods.alt || mods.logo {
  1330. if repeat {
  1331. return false
  1332. }
  1333. return self.handle_shortcut(key, &mods, atom).await
  1334. }
  1335. // Do nothing
  1336. if actions == 0 {
  1337. return true
  1338. }
  1339. t!("Key {:?} has {} actions", key, actions);
  1340. let key_str = key.to_string().repeat(actions as usize);
  1341. self.insert(&key_str, atom).await;
  1342. self.redraw(atom).await;
  1343. true
  1344. }
  1345. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  1346. t!("handle_key_down({key:?}, {mods:?}, {repeat})");
  1347. // First filter for only single digit keys
  1348. // Avoid processing events handled by handle_char()
  1349. if !ALLOWED_KEYCODES.contains(&key) {
  1350. return false
  1351. }
  1352. if !self.is_focused.get() {
  1353. return false
  1354. }
  1355. let actions = {
  1356. let mut repeater = self.key_repeat.lock();
  1357. repeater.key_down(PressedKey::Key(key), repeat)
  1358. };
  1359. // Suppress noisy message
  1360. if actions > 0 {
  1361. t!("Key {:?} has {} actions", key, actions);
  1362. }
  1363. let atom = &mut self.render_api.make_guard();
  1364. let mut is_handled = false;
  1365. for _ in 0..actions {
  1366. if self.handle_key(&key, &mods, atom).await {
  1367. is_handled = true;
  1368. }
  1369. }
  1370. is_handled
  1371. }
  1372. async fn handle_mouse_btn_down(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  1373. if !self.is_active.get() {
  1374. return false
  1375. }
  1376. let rect = self.rect.get();
  1377. if btn != MouseButton::Left {
  1378. if btn == MouseButton::Right && rect.contains(mouse_pos) {
  1379. if self.text.get().is_empty() {
  1380. self.node().trigger("paste_request", vec![]).await.unwrap();
  1381. }
  1382. return true
  1383. }
  1384. return false
  1385. }
  1386. if !rect.contains(mouse_pos) {
  1387. return false
  1388. }
  1389. let atom = &mut self.render_api.make_guard();
  1390. // clicking inside box will:
  1391. // 1. make it active
  1392. // 2. begin selection
  1393. if self.is_focused.get() {
  1394. d!("ChatEdit clicked");
  1395. } else {
  1396. d!("ChatEdit focused");
  1397. self.is_focused.set(atom, true);
  1398. }
  1399. // Move mouse pos within this widget
  1400. self.abs_to_local(&mut mouse_pos);
  1401. {
  1402. let mut txt_ctx = text2::TEXT_CTX.get().await;
  1403. let mut editor = self.lock_editor().await;
  1404. let mut drv = editor.driver(&mut txt_ctx).unwrap();
  1405. drv.move_to_point(mouse_pos.x, mouse_pos.y);
  1406. }
  1407. if !self.select_text.is_null(0).unwrap() {
  1408. self.select_text.clone().set_null(atom, Role::Internal, 0).unwrap();
  1409. }
  1410. self.mouse_btn_held.store(true, Ordering::Relaxed);
  1411. self.pause_blinking();
  1412. self.redraw(atom).await;
  1413. true
  1414. }
  1415. async fn handle_mouse_btn_up(&self, _btn: MouseButton, _mouse_pos: Point) -> bool {
  1416. if !self.is_active.get() {
  1417. return false
  1418. }
  1419. // releasing mouse button will end selection
  1420. self.mouse_btn_held.store(false, Ordering::Relaxed);
  1421. false
  1422. }
  1423. async fn handle_mouse_move(&self, mut mouse_pos: Point) -> bool {
  1424. if !self.is_active.get() {
  1425. return false
  1426. }
  1427. let rect = self.rect.get();
  1428. self.is_mouse_hover.store(rect.contains(mouse_pos), Ordering::Relaxed);
  1429. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  1430. return false
  1431. }
  1432. let atom = &mut self.render_api.make_guard();
  1433. // if active and selection_active, then use x to modify the selection.
  1434. // also implement scrolling when cursor is to the left or right
  1435. // just scroll to the end
  1436. // also set cursor_pos too
  1437. // Move mouse pos within this widget
  1438. self.abs_to_local(&mut mouse_pos);
  1439. let seltext = {
  1440. let mut txt_ctx = text2::TEXT_CTX.get().await;
  1441. let mut editor = self.lock_editor().await;
  1442. let mut drv = editor.driver(&mut txt_ctx).unwrap();
  1443. drv.extend_selection_to_point(mouse_pos.x, mouse_pos.y);
  1444. editor.selected_text()
  1445. };
  1446. d!("Select {seltext:?} from {mouse_pos:?}");
  1447. // Will be None when drag select just started
  1448. if let Some(seltext) = seltext {
  1449. self.select_text.clone().set_str(atom, Role::Internal, 0, seltext).unwrap();
  1450. }
  1451. self.pause_blinking();
  1452. self.apply_cursor_scrolling(atom).await;
  1453. self.redraw_scroll(atom.batch_id).await;
  1454. self.redraw_cursor(atom.batch_id).await;
  1455. self.redraw_select(atom.batch_id).await;
  1456. true
  1457. }
  1458. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  1459. if !self.is_mouse_hover.load(Ordering::Relaxed) {
  1460. return false
  1461. }
  1462. let atom = &mut self.render_api.make_guard();
  1463. let mut scroll = self.scroll.get() - wheel_pos.y * self.scroll_speed.get();
  1464. scroll = scroll.clamp(0., self.max_scroll());
  1465. t!("handle_mouse_wheel({wheel_pos:?}) [scroll={scroll}]");
  1466. self.scroll.set(atom, scroll);
  1467. self.redraw_scroll(atom.batch_id).await;
  1468. true
  1469. }
  1470. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  1471. if !self.is_active.get() {
  1472. return false
  1473. }
  1474. // Ignore multi-touch
  1475. if id != 0 {
  1476. return false
  1477. }
  1478. let atom = &mut self.render_api.make_guard();
  1479. match phase {
  1480. TouchPhase::Started => self.handle_touch_start(touch_pos).await,
  1481. TouchPhase::Moved => self.handle_touch_move(touch_pos).await,
  1482. TouchPhase::Ended => self.handle_touch_end(atom, touch_pos).await,
  1483. TouchPhase::Cancelled => false,
  1484. }
  1485. }
  1486. }