mod.rs 64 KB

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