mod.rs 61 KB

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