chatedit.rs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 miniquad::{window, KeyCode, KeyMods, MouseButton, TouchPhase};
  23. use parking_lot::Mutex as SyncMutex;
  24. use rand::{rngs::OsRng, Rng};
  25. use std::{
  26. collections::HashMap,
  27. sync::{
  28. atomic::{AtomicBool, Ordering},
  29. Arc, OnceLock, Weak,
  30. },
  31. time::Instant,
  32. };
  33. use crate::{
  34. error::Result,
  35. gfx::{
  36. GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, GfxTextureId, GraphicsEventPublisherPtr,
  37. Point, Rectangle, RenderApi, Vertex,
  38. },
  39. mesh::{MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_RED, COLOR_WHITE},
  40. prop::{
  41. PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr, PropertyRect, PropertyStr,
  42. PropertyUint32, Role,
  43. },
  44. pubsub::Subscription,
  45. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  46. text::{self, Glyph, GlyphPositionIter, TextShaperPtr},
  47. util::{enumerate_ref, is_whitespace, min_f32, zip3},
  48. ExecutorPtr,
  49. };
  50. use super::{
  51. editbox::{
  52. editable::{Editable, RenderedEditable, Selection, TextIdx, TextPos},
  53. eol_nudge,
  54. repeat::{PressedKey, PressedKeysSmoothRepeat},
  55. ALLOWED_KEYCODES, DISALLOWED_CHARS,
  56. },
  57. DrawUpdate, OnModify, UIObject,
  58. };
  59. // Minimum dist to update scroll when finger scrolling.
  60. // Avoid updating too much makes scrolling smoother.
  61. const VERT_SCROLL_UPDATE_INC: f32 = 1.;
  62. fn is_all_whitespace(glyphs: &[Glyph]) -> bool {
  63. for glyph in glyphs {
  64. if !is_whitespace(&glyph.substr) {
  65. return false
  66. }
  67. }
  68. true
  69. }
  70. struct TextWrap {
  71. editable: Editable,
  72. select: Vec<Selection>,
  73. rendered: Option<RenderedEditable>,
  74. font_size: PropertyFloat32,
  75. window_scale: PropertyFloat32,
  76. baseline: PropertyFloat32,
  77. linespacing: PropertyFloat32,
  78. }
  79. impl TextWrap {
  80. fn new(
  81. text_shaper: TextShaperPtr,
  82. font_size: PropertyFloat32,
  83. window_scale: PropertyFloat32,
  84. baseline: PropertyFloat32,
  85. linespacing: PropertyFloat32,
  86. ) -> Self {
  87. Self {
  88. editable: Editable::new(
  89. text_shaper,
  90. font_size.clone(),
  91. window_scale.clone(),
  92. baseline.clone(),
  93. ),
  94. select: vec![],
  95. rendered: None,
  96. font_size,
  97. window_scale,
  98. baseline,
  99. linespacing,
  100. }
  101. }
  102. fn clear_cache(&mut self) {
  103. self.rendered = None;
  104. }
  105. fn get_render(&mut self) -> &RenderedEditable {
  106. if self.rendered.is_none() {
  107. self.rendered = Some(self.editable.render());
  108. }
  109. self.rendered.as_ref().unwrap()
  110. }
  111. fn wrap(&mut self, width: f32) -> WrappedLines {
  112. let font_size = self.font_size.get();
  113. let window_scale = self.window_scale.get();
  114. let baseline = self.baseline.get();
  115. let linespacing = self.linespacing.get();
  116. let rendered = self.get_render();
  117. let wrapped_glyphs = text::wrap(width, font_size, window_scale, &rendered.glyphs);
  118. let mut curr_pos = 0;
  119. let mut lines: Vec<_> = wrapped_glyphs
  120. .into_iter()
  121. .map(|glyphs| {
  122. let off_pos = curr_pos;
  123. curr_pos += glyphs.len();
  124. WrappedLine::new(glyphs, off_pos, font_size, window_scale, baseline)
  125. })
  126. .collect();
  127. if let Some(last) = lines.last_mut() {
  128. assert_eq!(last.last_pos(), rendered.glyphs.len());
  129. last.is_last = true;
  130. }
  131. WrappedLines::new(lines, font_size, linespacing)
  132. }
  133. fn cursor_pos(&mut self) -> TextPos {
  134. let rendered = self.get_render().clone();
  135. self.editable.get_cursor_pos(&rendered)
  136. }
  137. fn set_cursor_with_point(&mut self, point: Point, width: f32) -> TextPos {
  138. let wrapped_lines = self.wrap(width);
  139. let cursor_pos = wrapped_lines.point_to_pos(point);
  140. let rendered = self.get_render();
  141. let glyphs_len = rendered.glyphs.len();
  142. let cidx = rendered.pos_to_idx(cursor_pos);
  143. self.editable.set_cursor_idx(cidx);
  144. debug!(target: "ui::chatedit::text_wrap", "set_cursor_with_point() -> {cursor_pos} / {glyphs_len}");
  145. cursor_pos
  146. }
  147. fn get_word_boundary(&mut self, pos: TextPos) -> (TextPos, TextPos) {
  148. let rendered = self.get_render();
  149. // Find word start
  150. let mut pos_start = pos;
  151. while pos_start > 0 {
  152. // Is the glyph before this pos just whitespace?
  153. let glyph_str = &rendered.glyphs[pos_start - 1].substr;
  154. if is_whitespace(glyph_str) {
  155. break
  156. }
  157. pos_start -= 1;
  158. }
  159. // Find word end
  160. let mut pos_end = pos + 1;
  161. while pos_end < rendered.glyphs.len() {
  162. let glyph_str = &rendered.glyphs[pos_end].substr;
  163. if is_whitespace(glyph_str) {
  164. break
  165. }
  166. pos_end += 1;
  167. }
  168. (pos_start, pos_end)
  169. }
  170. fn delete_selected(&mut self) {
  171. let selection = std::mem::take(&mut self.select);
  172. let sel = selection.first().unwrap();
  173. let cursor_pos = std::cmp::min(sel.start, sel.end);
  174. let render = self.get_render();
  175. let mut before_text = String::new();
  176. let mut after_text = String::new();
  177. 'next: for (pos, glyph) in render.glyphs.iter().enumerate() {
  178. for select in &selection {
  179. let start = std::cmp::min(select.start, select.end);
  180. let end = std::cmp::max(select.start, select.end);
  181. if start <= pos && pos < end {
  182. continue 'next
  183. }
  184. }
  185. if pos <= cursor_pos {
  186. before_text += &glyph.substr;
  187. } else {
  188. after_text += &glyph.substr;
  189. }
  190. }
  191. self.editable.set_text(before_text, after_text);
  192. self.clear_cache();
  193. }
  194. }
  195. struct WrappedLine {
  196. glyphs: Vec<Glyph>,
  197. off_pos: TextPos,
  198. font_size: f32,
  199. window_scale: f32,
  200. baseline: f32,
  201. /// Last line in this paragraph?
  202. /// In which case the cursor does not wrap
  203. is_last: bool,
  204. }
  205. impl WrappedLine {
  206. fn new(
  207. glyphs: Vec<Glyph>,
  208. off_pos: TextPos,
  209. font_size: f32,
  210. window_scale: f32,
  211. baseline: f32,
  212. ) -> Self {
  213. Self { glyphs, off_pos, font_size, window_scale, baseline, is_last: false }
  214. }
  215. fn len(&self) -> usize {
  216. self.glyphs.len()
  217. }
  218. fn first_pos(&self) -> TextPos {
  219. self.off_pos
  220. }
  221. fn last_pos(&self) -> TextPos {
  222. self.off_pos + self.len()
  223. }
  224. fn pos_iter(&self) -> GlyphPositionIter {
  225. GlyphPositionIter::new(self.font_size, self.window_scale, &self.glyphs, self.baseline)
  226. }
  227. fn rhs(&self) -> f32 {
  228. match self.pos_iter().last() {
  229. None => 0.,
  230. Some(rect) => rect.rhs(),
  231. }
  232. }
  233. fn find_closest(&self, x: f32) -> TextPos {
  234. for (pos, glyph_rect) in self.pos_iter().enumerate() {
  235. let next_x = glyph_rect.center().x;
  236. if x < next_x {
  237. return pos
  238. }
  239. }
  240. if self.is_last {
  241. self.glyphs.len()
  242. } else {
  243. self.glyphs.len() - 1
  244. }
  245. }
  246. }
  247. struct WrappedLines {
  248. lines: Vec<WrappedLine>,
  249. font_size: f32,
  250. linespacing: f32,
  251. }
  252. impl WrappedLines {
  253. fn new(lines: Vec<WrappedLine>, font_size: f32, linespacing: f32) -> Self {
  254. Self { lines, font_size, linespacing }
  255. }
  256. /// Convert an (x, y) point to a glyph pos
  257. fn point_to_pos(&self, mut point: Point) -> TextPos {
  258. let mut pos = 0;
  259. for (line_idx, wrap_line) in self.lines.iter().enumerate() {
  260. // Is it within this line?
  261. if point.y < self.linespacing || wrap_line.is_last {
  262. //debug!(target: "ui::chatedit::wrapped_lines", "point to pos found line: {line_idx}");
  263. pos += wrap_line.find_closest(point.x);
  264. return pos
  265. }
  266. // Continue to the next line
  267. point.y -= self.linespacing;
  268. pos += wrap_line.len();
  269. }
  270. //debug!(target: "ui::chatedit::wrapped_lines", "point to pos using last line");
  271. panic!("point_to_pos() went past the last line")
  272. }
  273. fn height(&self) -> f32 {
  274. self.last_y() + self.linespacing
  275. }
  276. fn last_y(&self) -> f32 {
  277. if self.lines.is_empty() {
  278. return 0.
  279. }
  280. (self.lines.len() - 1) as f32 * self.linespacing
  281. }
  282. fn last_rhs(&self) -> f32 {
  283. if self.lines.is_empty() {
  284. return 0.
  285. }
  286. let last_line = self.lines.last().unwrap();
  287. let mut rhs = last_line.rhs();
  288. rhs += eol_nudge(self.font_size, &last_line.glyphs);
  289. rhs
  290. }
  291. fn get_glyph_info(&self, mut pos: TextPos) -> (Rectangle, usize) {
  292. let mut y = 0.;
  293. for (line_idx, wrap_line) in self.lines.iter().enumerate() {
  294. assert!(!wrap_line.glyphs.is_empty());
  295. if pos < wrap_line.len() {
  296. // Cursor is on this line
  297. let mut pos_iter = wrap_line.pos_iter();
  298. pos_iter.advance_by(pos).unwrap();
  299. let mut glyph_rect = pos_iter.next().unwrap();
  300. return (glyph_rect, line_idx)
  301. }
  302. pos -= wrap_line.len();
  303. y += self.linespacing;
  304. }
  305. let rhs = self.last_rhs();
  306. let last_y = self.last_y();
  307. let final_rect = Rectangle::new(rhs, last_y, 0., self.linespacing);
  308. let last_idx = if self.lines.is_empty() { 0 } else { self.lines.len() - 1 };
  309. (final_rect, last_idx)
  310. }
  311. }
  312. #[derive(Clone)]
  313. struct TouchStartInfo {
  314. pos: Point,
  315. instant: std::time::Instant,
  316. }
  317. impl TouchStartInfo {
  318. fn new(pos: Point) -> Self {
  319. Self { pos, instant: std::time::Instant::now() }
  320. }
  321. }
  322. #[derive(Clone)]
  323. enum TouchStateAction {
  324. Inactive,
  325. Started { pos: Point, instant: std::time::Instant },
  326. StartSelect,
  327. Select,
  328. DragSelectHandle { side: isize },
  329. ScrollVert { start_pos: Point, scroll_start: f32 },
  330. SetCursorPos,
  331. }
  332. struct TouchInfo {
  333. state: TouchStateAction,
  334. start: Option<TouchStartInfo>,
  335. scroll: PropertyFloat32,
  336. }
  337. impl TouchInfo {
  338. fn new(scroll: PropertyFloat32) -> Self {
  339. Self { state: TouchStateAction::Inactive, start: None, scroll }
  340. }
  341. fn start(&mut self, pos: Point) {
  342. debug!(target: "ui::chatedit::touch", "start touch: Started state");
  343. self.state = TouchStateAction::Started { pos, instant: std::time::Instant::now() };
  344. }
  345. fn stop(&mut self) -> TouchStateAction {
  346. debug!(target: "ui::chatedit::touch", "stop touch: Inactive state");
  347. std::mem::replace(&mut self.state, TouchStateAction::Inactive)
  348. }
  349. fn update(&mut self, pos: &Point) {
  350. match &self.state {
  351. TouchStateAction::Started { pos: start_pos, instant } => {
  352. let travel_dist = pos.dist_sq(&start_pos);
  353. let grad = (pos.y - start_pos.y) / (pos.x - start_pos.x);
  354. let elapsed = instant.elapsed().as_millis();
  355. //debug!(target: "ui::chatedit::touch", "TouchInfo::update() [travel_dist={travel_dist}, grad={grad}]");
  356. if travel_dist < 5. {
  357. if elapsed > 1000 {
  358. debug!(target: "ui::chatedit::touch", "update touch state: Started -> StartSelect");
  359. self.state = TouchStateAction::StartSelect;
  360. }
  361. } else if grad.abs() > 0.5 {
  362. // Vertical movement
  363. debug!(target: "ui::chatedit::touch", "update touch state: Started -> ScrollVert");
  364. let scroll_start = self.scroll.get();
  365. self.state =
  366. TouchStateAction::ScrollVert { start_pos: *start_pos, scroll_start };
  367. } else {
  368. // Horizontal movement
  369. debug!(target: "ui::chatedit::touch", "update touch state: Started -> SetCursorPos");
  370. self.state = TouchStateAction::SetCursorPos;
  371. }
  372. }
  373. _ => {}
  374. }
  375. }
  376. }
  377. pub type ChatEditPtr = Arc<ChatEdit>;
  378. pub struct ChatEdit {
  379. node: SceneNodeWeak,
  380. tasks: OnceLock<Vec<smol::Task<()>>>,
  381. render_api: RenderApi,
  382. text_shaper: TextShaperPtr,
  383. key_repeat: SyncMutex<PressedKeysSmoothRepeat>,
  384. glyphs: SyncMutex<Vec<Glyph>>,
  385. main_dc_key: u64,
  386. /// DC key for the text
  387. text_dc_key: u64,
  388. cursor_mesh: SyncMutex<Option<GfxDrawMesh>>,
  389. /// DC key for the cursor. Allows updating cursor independently.
  390. cursor_dc_key: u64,
  391. is_active: PropertyBool,
  392. is_focused: PropertyBool,
  393. max_height: PropertyFloat32,
  394. rect: PropertyRect,
  395. baseline: PropertyFloat32,
  396. linespacing: PropertyFloat32,
  397. descent: PropertyFloat32,
  398. scroll: PropertyFloat32,
  399. scroll_speed: PropertyFloat32,
  400. cursor_pos: PropertyUint32,
  401. font_size: PropertyFloat32,
  402. text: PropertyStr,
  403. text_color: PropertyColor,
  404. text_hi_color: PropertyColor,
  405. cursor_color: PropertyColor,
  406. cursor_width: PropertyFloat32,
  407. cursor_ascent: PropertyFloat32,
  408. cursor_descent: PropertyFloat32,
  409. cursor_blink_time: PropertyUint32,
  410. cursor_idle_time: PropertyUint32,
  411. hi_bg_color: PropertyColor,
  412. select_ascent: PropertyFloat32,
  413. select_descent: PropertyFloat32,
  414. handle_descent: PropertyFloat32,
  415. selected: PropertyPtr,
  416. z_index: PropertyUint32,
  417. debug: PropertyBool,
  418. text_wrap: SyncMutex<TextWrap>,
  419. mouse_btn_held: AtomicBool,
  420. cursor_is_visible: AtomicBool,
  421. blink_is_paused: AtomicBool,
  422. /// Used to explicitly hide the cursor. Must be manually re-enabled.
  423. hide_cursor: AtomicBool,
  424. touch_info: SyncMutex<TouchInfo>,
  425. is_phone_select: AtomicBool,
  426. old_window_scale: AtomicF32,
  427. window_scale: PropertyFloat32,
  428. parent_rect: SyncMutex<Option<Rectangle>>,
  429. is_mouse_hover: AtomicBool,
  430. }
  431. impl ChatEdit {
  432. pub async fn new(
  433. node: SceneNodeWeak,
  434. window_scale: PropertyFloat32,
  435. render_api: RenderApi,
  436. text_shaper: TextShaperPtr,
  437. ex: ExecutorPtr,
  438. ) -> Pimpl {
  439. debug!(target: "ui::chatedit", "EditBox::new()");
  440. let node_ref = &node.upgrade().unwrap();
  441. let is_active = PropertyBool::wrap(node_ref, Role::Internal, "is_active", 0).unwrap();
  442. let is_focused = PropertyBool::wrap(node_ref, Role::Internal, "is_focused", 0).unwrap();
  443. let max_height = PropertyFloat32::wrap(node_ref, Role::Internal, "max_height", 0).unwrap();
  444. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  445. let baseline = PropertyFloat32::wrap(node_ref, Role::Internal, "baseline", 0).unwrap();
  446. let linespacing =
  447. PropertyFloat32::wrap(node_ref, Role::Internal, "linespacing", 0).unwrap();
  448. let descent = PropertyFloat32::wrap(node_ref, Role::Internal, "descent", 0).unwrap();
  449. let scroll = PropertyFloat32::wrap(node_ref, Role::Internal, "scroll", 0).unwrap();
  450. let scroll_speed =
  451. PropertyFloat32::wrap(node_ref, Role::Internal, "scroll_speed", 0).unwrap();
  452. let cursor_pos = PropertyUint32::wrap(node_ref, Role::Internal, "cursor_pos", 0).unwrap();
  453. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  454. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  455. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  456. let text_hi_color = PropertyColor::wrap(node_ref, Role::Internal, "text_hi_color").unwrap();
  457. let cursor_color = PropertyColor::wrap(node_ref, Role::Internal, "cursor_color").unwrap();
  458. let cursor_width =
  459. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_width", 0).unwrap();
  460. let cursor_ascent =
  461. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_ascent", 0).unwrap();
  462. let cursor_descent =
  463. PropertyFloat32::wrap(node_ref, Role::Internal, "cursor_descent", 0).unwrap();
  464. let hi_bg_color = PropertyColor::wrap(node_ref, Role::Internal, "hi_bg_color").unwrap();
  465. let select_ascent =
  466. PropertyFloat32::wrap(node_ref, Role::Internal, "select_ascent", 0).unwrap();
  467. let select_descent =
  468. PropertyFloat32::wrap(node_ref, Role::Internal, "select_descent", 0).unwrap();
  469. let handle_descent =
  470. PropertyFloat32::wrap(node_ref, Role::Internal, "handle_descent", 0).unwrap();
  471. let selected = node_ref.get_property("selected").unwrap();
  472. let cursor_blink_time =
  473. PropertyUint32::wrap(node_ref, Role::Internal, "cursor_blink_time", 0).unwrap();
  474. let cursor_idle_time =
  475. PropertyUint32::wrap(node_ref, Role::Internal, "cursor_idle_time", 0).unwrap();
  476. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  477. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  478. let node_name = node_ref.name.clone();
  479. let node_id = node_ref.id;
  480. // Must do this whenever the text changes
  481. let glyphs = text_shaper.shape(text.get(), font_size.get(), window_scale.get());
  482. let self_ = Arc::new(Self {
  483. node,
  484. tasks: OnceLock::new(),
  485. render_api,
  486. text_shaper: text_shaper.clone(),
  487. key_repeat: SyncMutex::new(PressedKeysSmoothRepeat::new(400, 50)),
  488. glyphs: SyncMutex::new(glyphs),
  489. main_dc_key: OsRng.gen(),
  490. text_dc_key: OsRng.gen(),
  491. cursor_mesh: SyncMutex::new(None),
  492. cursor_dc_key: OsRng.gen(),
  493. is_active,
  494. is_focused,
  495. max_height,
  496. rect,
  497. baseline: baseline.clone(),
  498. linespacing: linespacing.clone(),
  499. descent,
  500. scroll: scroll.clone(),
  501. scroll_speed,
  502. cursor_pos,
  503. font_size: font_size.clone(),
  504. text,
  505. text_color,
  506. text_hi_color,
  507. cursor_color,
  508. cursor_width,
  509. cursor_ascent,
  510. cursor_descent,
  511. cursor_blink_time,
  512. cursor_idle_time,
  513. hi_bg_color,
  514. select_ascent,
  515. select_descent,
  516. handle_descent,
  517. selected,
  518. z_index,
  519. debug,
  520. text_wrap: SyncMutex::new(TextWrap::new(
  521. text_shaper,
  522. font_size,
  523. window_scale.clone(),
  524. baseline,
  525. linespacing,
  526. )),
  527. mouse_btn_held: AtomicBool::new(false),
  528. cursor_is_visible: AtomicBool::new(true),
  529. blink_is_paused: AtomicBool::new(false),
  530. hide_cursor: AtomicBool::new(false),
  531. touch_info: SyncMutex::new(TouchInfo::new(scroll)),
  532. is_phone_select: AtomicBool::new(false),
  533. old_window_scale: AtomicF32::new(window_scale.get()),
  534. window_scale,
  535. parent_rect: SyncMutex::new(None),
  536. is_mouse_hover: AtomicBool::new(false),
  537. });
  538. self_.text_wrap.lock().editable.set_text(
  539. "".to_string(),
  540. "A berry is a small, pulpy, and often edible fruit. Typically, berries are juicy, rounded, brightly colored, sweet, sour or tart, and do not have a stone or pit, although many pips or seeds may be present. Common examples of berries in the culinary sense are strawberries, raspberries, blueberries, blackberries, white currants, blackcurrants, and redcurrants. In Britain, soft fruit is a horticultural term for such fruits.".to_string()
  541. );
  542. //self_
  543. // .text_wrap
  544. // .lock()
  545. // .editable
  546. // .set_text("A berry is small and pulpy.".to_string(), "".to_string());
  547. Pimpl::ChatEdit(self_)
  548. }
  549. fn node(&self) -> SceneNodePtr {
  550. self.node.upgrade().unwrap()
  551. }
  552. fn wrap_width(&self) -> f32 {
  553. self.rect.prop().get_f32(2).unwrap() - self.cursor_width.get()
  554. }
  555. fn abs_to_local(&self, point: &mut Point) {
  556. let rect = self.rect.get();
  557. *point -= rect.pos();
  558. point.y += self.scroll.get();
  559. }
  560. /// Called whenever the text or any text property changes.
  561. fn regen_text_mesh(&self) -> GfxDrawMesh {
  562. let is_focused = self.is_focused.get();
  563. let text = self.text.get();
  564. let font_size = self.font_size.get();
  565. let window_scale = self.window_scale.get();
  566. let text_color = self.text_color.get();
  567. let text_hi_color = self.text_hi_color.get();
  568. let linespacing = self.linespacing.get();
  569. let baseline = self.baseline.get();
  570. let scroll = self.scroll.get();
  571. let cursor_pos = self.cursor_pos.get() as usize;
  572. let cursor_color = self.cursor_color.get();
  573. let debug = self.debug.get();
  574. let parent_rect = self.parent_rect.lock().clone().unwrap();
  575. self.rect.eval_with(
  576. vec![2],
  577. vec![("parent_w".to_string(), parent_rect.w), ("parent_h".to_string(), parent_rect.h)],
  578. );
  579. // Height is calculated from width based on wrapping
  580. let width = self.wrap_width();
  581. let (atlas, wrapped_lines, selections) = {
  582. let mut text_wrap = self.text_wrap.lock();
  583. let rendered_glyphs = &text_wrap.get_render().glyphs;
  584. let atlas = text::make_texture_atlas(&self.render_api, rendered_glyphs);
  585. let wrapped_lines = text_wrap.wrap(width);
  586. let selections = text_wrap.select.clone();
  587. (atlas, wrapped_lines, selections)
  588. };
  589. let mut height = wrapped_lines.height() + self.descent.get();
  590. height = height.clamp(0., self.max_height.get());
  591. self.rect.prop().set_f32(Role::Internal, 3, height);
  592. // Eval the rect
  593. let parent_rect = self.parent_rect.lock().clone().unwrap();
  594. self.rect.eval_with(
  595. vec![0, 1, 3],
  596. vec![
  597. ("parent_w".to_string(), parent_rect.w),
  598. ("parent_h".to_string(), parent_rect.h),
  599. ("rect_h".to_string(), height),
  600. ],
  601. );
  602. let mut clip = self.rect.get();
  603. //debug!(target: "ui::chatedit", "Rendering text '{text}' rect={clip:?} width={width}");
  604. clip.x = 0.;
  605. clip.y = 0.;
  606. let mut mesh = MeshBuilder::with_clip(clip.clone());
  607. let mut curr_y = -scroll;
  608. //debug!(target: "ui::chatedit", "regen_text_mesh() selections={selections:?}");
  609. for (line_idx, wrap_line) in wrapped_lines.lines.iter().enumerate() {
  610. let select_marks = self.mark_selected_glyphs(&wrap_line, &selections);
  611. self.draw_selected(&mut mesh, &select_marks, &wrap_line, curr_y);
  612. /*
  613. if rendered.has_underline() {
  614. self.draw_underline(
  615. &mut mesh,
  616. &rendered.glyphs,
  617. clip.h,
  618. rendered.under_start,
  619. rendered.under_end,
  620. );
  621. }
  622. */
  623. let pos_iter = wrap_line.pos_iter();
  624. for (_, mut glyph_rect, glyph, is_selected) in
  625. zip3(pos_iter, wrap_line.glyphs.iter(), select_marks.into_iter())
  626. {
  627. let uv_rect = atlas.fetch_uv(glyph.glyph_id).expect("missing glyph UV rect");
  628. glyph_rect.y += curr_y;
  629. //mesh.draw_outline(&glyph_rect, COLOR_BLUE, 2.);
  630. let mut color = text_color.clone();
  631. if is_selected {
  632. color = text_hi_color.clone();
  633. }
  634. if glyph.sprite.has_color {
  635. color = COLOR_WHITE;
  636. }
  637. // Some kewl styling
  638. let top_y = line_idx as f32 * linespacing + baseline - font_size - scroll;
  639. if top_y < 0. {
  640. let pct = 1. + (top_y / baseline).clamp(-1., 0.);
  641. color[3] = pct;
  642. }
  643. //let bottom_y = top_y + linespacing;
  644. let bottom_y = (line_idx + 1) as f32 * linespacing - scroll;
  645. let bottom_rect = clip.h;
  646. if bottom_y > bottom_rect {
  647. let dist = bottom_y - bottom_rect;
  648. let pct = 1. - (dist / linespacing).clamp(0., 1.);
  649. color[3] = pct;
  650. }
  651. mesh.draw_box(&glyph_rect, color, uv_rect);
  652. if self.debug.get() {
  653. mesh.draw_outline(&glyph_rect, COLOR_RED, 1.);
  654. }
  655. }
  656. curr_y += linespacing;
  657. }
  658. // Just an assert
  659. if self.is_phone_select.load(Ordering::Relaxed) {
  660. assert_eq!(selections.len(), 1);
  661. let select = selections.last().unwrap();
  662. self.draw_phone_select_handle(&mut mesh, select.start, &wrapped_lines, -1.);
  663. self.draw_phone_select_handle(&mut mesh, select.end, &wrapped_lines, 1.);
  664. }
  665. if self.debug.get() {
  666. mesh.draw_outline(&clip, COLOR_BLUE, 1.);
  667. }
  668. mesh.alloc(&self.render_api).draw_with_texture(atlas.texture)
  669. }
  670. fn regen_cursor_mesh(&self) -> GfxDrawMesh {
  671. let cursor_width = self.cursor_width.get();
  672. let cursor_ascent = self.cursor_ascent.get();
  673. let cursor_descent = self.cursor_descent.get();
  674. let baseline = self.baseline.get();
  675. let cursor_rect = Rectangle {
  676. x: 0.,
  677. y: baseline - cursor_ascent,
  678. w: cursor_width,
  679. h: cursor_ascent + cursor_descent,
  680. };
  681. let cursor_color = self.cursor_color.get();
  682. let mut mesh = MeshBuilder::new();
  683. mesh.draw_filled_box(&cursor_rect, cursor_color);
  684. mesh.alloc(&self.render_api).draw_untextured()
  685. }
  686. fn get_cursor_pos(&self) -> Point {
  687. assert!(self.is_focused.get());
  688. let font_size = self.font_size.get();
  689. let window_scale = self.window_scale.get();
  690. let linespacing = self.linespacing.get();
  691. let scroll = self.scroll.get();
  692. let width = self.wrap_width();
  693. let (cursor_pos, wrapped_lines) = {
  694. let mut text_wrap = self.text_wrap.lock();
  695. (text_wrap.cursor_pos(), text_wrap.wrap(width))
  696. };
  697. let glyph_info = wrapped_lines.get_glyph_info(cursor_pos);
  698. let lineidx = glyph_info.1;
  699. let mut point = glyph_info.0.pos();
  700. point.x = point.x.clamp(0., width);
  701. point.y = lineidx as f32 * linespacing - scroll;
  702. point
  703. }
  704. fn mark_selected_glyphs(
  705. &self,
  706. wrap_line: &WrappedLine,
  707. selections: &Vec<Selection>,
  708. ) -> Vec<bool> {
  709. let mut marks = vec![false; wrap_line.len()];
  710. for select in selections {
  711. let mut start = std::cmp::min(select.start, select.end);
  712. let mut end = std::cmp::max(select.start, select.end);
  713. let off_pos = wrap_line.off_pos;
  714. if end < off_pos || start > wrap_line.last_pos() {
  715. continue
  716. }
  717. end = std::cmp::min(end, wrap_line.last_pos()) - off_pos;
  718. start = start.saturating_sub(off_pos);
  719. for i in start..end {
  720. marks[i] = true;
  721. }
  722. }
  723. marks
  724. }
  725. fn draw_selected(
  726. &self,
  727. mesh: &mut MeshBuilder,
  728. select_marks: &Vec<bool>,
  729. wrap_line: &WrappedLine,
  730. y_off: f32,
  731. ) {
  732. let font_size = self.font_size.get();
  733. let baseline = self.baseline.get();
  734. let select_ascent = self.select_ascent.get();
  735. let select_descent = self.select_descent.get();
  736. let hi_bg_color = self.hi_bg_color.get();
  737. if select_marks.iter().all(|b| !b) {
  738. return
  739. }
  740. let mut start_x = None;
  741. let mut end_x = None;
  742. for (glyph_rect, is_selected) in wrap_line.pos_iter().zip(select_marks.iter()) {
  743. if *is_selected && start_x.is_none() {
  744. start_x = Some(glyph_rect.x);
  745. }
  746. if !*is_selected && start_x.is_some() && end_x.is_none() {
  747. end_x = Some(glyph_rect.x);
  748. }
  749. }
  750. let mut start_x = start_x.unwrap();
  751. if select_marks[0] {
  752. start_x = 0.;
  753. }
  754. let end_x = match end_x {
  755. Some(end_x) => end_x,
  756. None => {
  757. assert!(*select_marks.last().unwrap());
  758. wrap_line.rhs() + eol_nudge(font_size, &wrap_line.glyphs)
  759. }
  760. };
  761. let select_ascent = self.select_ascent.get();
  762. let select_descent = self.select_descent.get();
  763. let select_rect = Rectangle {
  764. x: start_x,
  765. y: y_off + baseline - select_ascent,
  766. w: end_x - start_x,
  767. h: select_ascent + select_descent,
  768. };
  769. mesh.draw_box(&select_rect, hi_bg_color, &Rectangle::zero());
  770. }
  771. fn draw_phone_select_handle(
  772. &self,
  773. mesh: &mut MeshBuilder,
  774. gpos: TextPos,
  775. wrapped_lines: &WrappedLines,
  776. side: f32,
  777. ) {
  778. //debug!(target: "ui::chatedit", "draw_phone_select_handle(..., {x}, {side})");
  779. let baseline = self.baseline.get();
  780. let select_ascent = self.select_ascent.get();
  781. let handle_descent = self.handle_descent.get();
  782. let color = self.text_hi_color.get();
  783. let linespacing = self.linespacing.get();
  784. let scroll = self.scroll.get();
  785. // Transparent for fade
  786. let mut color_trans = color.clone();
  787. color_trans[3] = 0.;
  788. // find start_x
  789. let (glyph_rect, line_idx) = wrapped_lines.get_glyph_info(gpos);
  790. let x = glyph_rect.x;
  791. let y_off = line_idx as f32 * linespacing - scroll;
  792. let y = y_off + baseline + handle_descent;
  793. if y < 0. {
  794. return
  795. }
  796. // Vertical line downwards. We use this instead of draw_box() so we have a fade.
  797. let verts = vec![
  798. Vertex {
  799. pos: [x - side * 1., y_off + baseline - select_ascent],
  800. color: color_trans,
  801. uv: [0., 0.],
  802. },
  803. Vertex {
  804. pos: [x + side * 4., y_off + baseline - select_ascent],
  805. color: color_trans,
  806. uv: [0., 0.],
  807. },
  808. Vertex {
  809. pos: [x - side * 1., y_off + baseline + handle_descent + 5.],
  810. color,
  811. uv: [0., 0.],
  812. },
  813. Vertex {
  814. pos: [x + side * 4., y_off + baseline + handle_descent + 5.],
  815. color,
  816. uv: [0., 0.],
  817. },
  818. ];
  819. let indices = vec![0, 2, 1, 1, 2, 3];
  820. mesh.append(verts, indices);
  821. // The arrow itself.
  822. // Go anti-clockwise
  823. let verts = vec![
  824. Vertex { pos: [x, y], color, uv: [0., 0.] },
  825. Vertex { pos: [x, y + 50.], color, uv: [0., 0.] },
  826. Vertex { pos: [x + side * 30., y + 50.], color, uv: [0., 0.] },
  827. Vertex { pos: [x + side * 50., y + 25.], color, uv: [0., 0.] },
  828. ];
  829. let indices = vec![0, 1, 2, 0, 2, 3];
  830. mesh.append(verts, indices);
  831. }
  832. fn draw_underline(
  833. &self,
  834. mesh: &mut MeshBuilder,
  835. glyphs: &Vec<Glyph>,
  836. clip_h: f32,
  837. under_start: usize,
  838. under_end: usize,
  839. ) {
  840. assert!(under_start < under_end);
  841. let font_size = self.font_size.get();
  842. let window_scale = self.window_scale.get();
  843. let baseline = self.baseline.get();
  844. let scroll = self.scroll.get();
  845. let text_color = self.text_color.get();
  846. let glyph_pos_iter = GlyphPositionIter::new(font_size, window_scale, &glyphs, baseline);
  847. let mut start_x = 0.;
  848. let mut end_x = 0.;
  849. // When cursor lands at the end of the line
  850. let mut rhs = 0.;
  851. for (glyph_idx, mut glyph_rect) in glyph_pos_iter.enumerate() {
  852. glyph_rect.x -= scroll;
  853. if glyph_idx == under_start {
  854. start_x = glyph_rect.x;
  855. }
  856. if glyph_idx == under_end {
  857. end_x = glyph_rect.x;
  858. }
  859. rhs = glyph_rect.rhs();
  860. }
  861. if under_start == 0 {
  862. start_x = scroll;
  863. }
  864. if under_end == glyphs.len() {
  865. end_x = rhs;
  866. }
  867. // We don't need to do manual clipping since MeshBuilder should do that
  868. let underline_rect = Rectangle { x: start_x, y: baseline + 6., w: end_x - start_x, h: 4. };
  869. mesh.draw_box(&underline_rect, text_color, &Rectangle::zero());
  870. }
  871. async fn change_focus(self: Arc<Self>) {
  872. if !self.is_active.get() {
  873. return
  874. }
  875. debug!(target: "ui::chatedit", "Focus changed");
  876. // Cursor visibility will change so just redraw everything lol
  877. self.redraw().await;
  878. }
  879. async fn insert_char(&self, key: char) {
  880. {
  881. let mut text_wrap = &mut self.text_wrap.lock();
  882. text_wrap.clear_cache();
  883. if !text_wrap.select.is_empty() {
  884. text_wrap.delete_selected();
  885. }
  886. let mut tmp = [0; 4];
  887. let key_str = key.encode_utf8(&mut tmp);
  888. text_wrap.editable.compose(key_str, true);
  889. }
  890. self.pause_blinking();
  891. self.redraw().await;
  892. }
  893. async fn handle_shortcut(&self, key: char, mods: &KeyMods) {
  894. debug!(target: "ui::chatedit", "handle_shortcut({:?}, {:?})", key, mods);
  895. match key {
  896. 'c' => {
  897. if mods.ctrl {
  898. self.copy_highlighted().unwrap();
  899. }
  900. }
  901. 'v' => {
  902. if mods.ctrl {
  903. if let Some(text) = window::clipboard_get() {
  904. self.paste_text(text).await;
  905. }
  906. }
  907. }
  908. _ => {}
  909. }
  910. }
  911. async fn handle_key(&self, key: &KeyCode, mods: &KeyMods) {
  912. debug!(target: "ui::chatedit", "handle_key({:?}, {:?})", key, mods);
  913. match key {
  914. KeyCode::Left => {
  915. self.adjust_cursor(mods.shift, |editable| editable.move_cursor(-1));
  916. self.pause_blinking();
  917. //self.apply_cursor_scrolling();
  918. self.redraw().await;
  919. }
  920. KeyCode::Right => {
  921. self.adjust_cursor(mods.shift, |editable| editable.move_cursor(1));
  922. self.pause_blinking();
  923. //self.apply_cursor_scrolling();
  924. self.redraw().await;
  925. }
  926. KeyCode::Kp0 => self.insert_char('0').await,
  927. KeyCode::Kp1 => self.insert_char('1').await,
  928. KeyCode::Kp2 => self.insert_char('2').await,
  929. KeyCode::Kp3 => self.insert_char('3').await,
  930. KeyCode::Kp4 => self.insert_char('4').await,
  931. KeyCode::Kp5 => self.insert_char('5').await,
  932. KeyCode::Kp6 => self.insert_char('6').await,
  933. KeyCode::Kp7 => self.insert_char('7').await,
  934. KeyCode::Kp8 => self.insert_char('8').await,
  935. KeyCode::Kp9 => self.insert_char('9').await,
  936. KeyCode::KpDecimal => self.insert_char('.').await,
  937. //KeyCode::Enter | KeyCode::KpEnter => self.insert_char('\n').await,
  938. KeyCode::Delete => {
  939. self.delete(0, 1);
  940. self.clamp_scroll(&mut self.text_wrap.lock());
  941. self.pause_blinking();
  942. self.redraw().await;
  943. }
  944. KeyCode::Backspace => {
  945. self.delete(1, 0);
  946. self.clamp_scroll(&mut self.text_wrap.lock());
  947. self.pause_blinking();
  948. self.redraw().await;
  949. }
  950. KeyCode::Home => {
  951. self.adjust_cursor(mods.shift, |editable| editable.move_start());
  952. self.pause_blinking();
  953. //self.apply_cursor_scrolling();
  954. self.redraw().await;
  955. }
  956. KeyCode::End => {
  957. self.adjust_cursor(mods.shift, |editable| editable.move_end());
  958. self.pause_blinking();
  959. //self.apply_cursor_scrolling();
  960. self.redraw().await;
  961. }
  962. _ => {}
  963. }
  964. }
  965. fn delete(&self, before: usize, after: usize) {
  966. let mut text_wrap = &mut self.text_wrap.lock();
  967. if text_wrap.select.is_empty() {
  968. text_wrap.editable.delete(before, after);
  969. text_wrap.clear_cache();
  970. } else {
  971. text_wrap.delete_selected();
  972. }
  973. self.is_phone_select.store(false, Ordering::Relaxed);
  974. // Reshow cursor (if hidden)
  975. self.hide_cursor.store(false, Ordering::Relaxed);
  976. }
  977. fn adjust_cursor(&self, has_shift: bool, move_cursor: impl Fn(&mut Editable)) {
  978. let mut text_wrap = &mut self.text_wrap.lock();
  979. let rendered = text_wrap.get_render().clone();
  980. let prev_cursor_pos = text_wrap.editable.get_cursor_pos(&rendered);
  981. move_cursor(&mut text_wrap.editable);
  982. let cursor_pos = text_wrap.editable.get_cursor_pos(&rendered);
  983. drop(text_wrap);
  984. debug!(target: "ui::editbox", "Adjust cursor pos to {cursor_pos}");
  985. let select = &mut self.text_wrap.lock().select;
  986. // Start selection if shift is held
  987. if has_shift {
  988. // Create a new selection
  989. if select.is_empty() {
  990. select.push(Selection::new(prev_cursor_pos, cursor_pos));
  991. }
  992. // Update the selection
  993. select.last_mut().unwrap().end = cursor_pos;
  994. } else {
  995. select.clear();
  996. }
  997. }
  998. /// This will select the entire word rather than move the cursor to that location
  999. fn start_touch_select(&self, touch_pos: Point) {
  1000. let mut text_wrap = &mut self.text_wrap.lock();
  1001. text_wrap.clear_cache();
  1002. text_wrap.editable.end_compose();
  1003. let width = self.wrap_width();
  1004. let wrapped_lines = text_wrap.wrap(width);
  1005. let pos = wrapped_lines.point_to_pos(touch_pos);
  1006. let (word_start, word_end) = text_wrap.get_word_boundary(pos);
  1007. // begin selection
  1008. let select = &mut text_wrap.select;
  1009. select.clear();
  1010. select.push(Selection::new(word_start, word_end));
  1011. debug!(target: "ui::chatview", "Selected {select:?} from {touch_pos:?}");
  1012. self.is_phone_select.store(true, Ordering::Relaxed);
  1013. // redraw() will now hide the cursor
  1014. self.hide_cursor.store(true, Ordering::Relaxed);
  1015. }
  1016. fn glyphs_to_string(glyphs: &Vec<Glyph>) -> String {
  1017. let mut text = String::new();
  1018. for (i, glyph) in glyphs.iter().enumerate() {
  1019. text.push_str(&glyph.substr);
  1020. }
  1021. text
  1022. }
  1023. fn delete_highlighted(&self) {
  1024. assert!(!self.selected.is_null(0).unwrap());
  1025. assert!(!self.selected.is_null(1).unwrap());
  1026. let start = self.selected.get_u32(0).unwrap() as usize;
  1027. let end = self.selected.get_u32(1).unwrap() as usize;
  1028. let sel_start = std::cmp::min(start, end);
  1029. let sel_end = std::cmp::max(start, end);
  1030. let mut glyphs = self.glyphs.lock().clone();
  1031. glyphs.drain(sel_start..sel_end);
  1032. let text = Self::glyphs_to_string(&glyphs);
  1033. debug!(
  1034. target: "ui::chatedit",
  1035. "delete_highlighted() text=\"{}\", cursor_pos={}",
  1036. text, sel_start
  1037. );
  1038. self.text.set(text);
  1039. self.selected.set_null(Role::Internal, 0).unwrap();
  1040. self.selected.set_null(Role::Internal, 1).unwrap();
  1041. self.cursor_pos.set(sel_start as u32);
  1042. }
  1043. fn copy_highlighted(&self) -> Result<()> {
  1044. let start = self.selected.get_u32(0)? as usize;
  1045. let end = self.selected.get_u32(1)? as usize;
  1046. let sel_start = std::cmp::min(start, end);
  1047. let sel_end = std::cmp::max(start, end);
  1048. let mut text = String::new();
  1049. let glyphs = self.glyphs.lock().clone();
  1050. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  1051. if sel_start <= glyph_idx && glyph_idx < sel_end {
  1052. text.push_str(&glyph.substr);
  1053. }
  1054. }
  1055. info!(target: "ui::chatedit", "Copied '{}'", text);
  1056. window::clipboard_set(&text);
  1057. Ok(())
  1058. }
  1059. async fn paste_text(&self, key: String) {
  1060. let mut text = String::new();
  1061. let cursor_pos = self.cursor_pos.get();
  1062. if cursor_pos == 0 {
  1063. text = key.clone();
  1064. }
  1065. let glyphs = self.glyphs.lock().clone();
  1066. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  1067. text.push_str(&glyph.substr);
  1068. if cursor_pos == glyph_idx as u32 + 1 {
  1069. text.push_str(&key);
  1070. }
  1071. }
  1072. self.text.set(text);
  1073. // Not always true lol
  1074. self.cursor_pos.set(cursor_pos + 1);
  1075. self.apply_cursor_scrolling();
  1076. self.redraw().await;
  1077. }
  1078. async fn handle_touch_start(&self, mut touch_pos: Point) -> bool {
  1079. //debug!(target: "ui::chatedit", "handle_touch_start({touch_pos:?})");
  1080. let mut touch_info = self.touch_info.lock();
  1081. if self.try_handle_drag(&mut touch_info, touch_pos) {
  1082. return true
  1083. }
  1084. let rect = self.rect.get();
  1085. if !rect.contains(touch_pos) {
  1086. return false
  1087. }
  1088. touch_info.start(touch_pos);
  1089. true
  1090. }
  1091. fn try_handle_drag(&self, touch_info: &mut TouchInfo, mut touch_pos: Point) -> bool {
  1092. // Is the handle visible? Use y within rect before adding the scroll.
  1093. let relative_y = touch_pos.y - self.rect.get().y;
  1094. if relative_y < 0. {
  1095. return false
  1096. }
  1097. self.abs_to_local(&mut touch_pos);
  1098. let linespacing = self.linespacing.get();
  1099. let baseline = self.baseline.get();
  1100. let select_descent = self.select_descent.get();
  1101. let scroll = self.scroll.get();
  1102. let mut text_wrap = self.text_wrap.lock();
  1103. let width = self.wrap_width();
  1104. let wrapped_lines = text_wrap.wrap(width);
  1105. let selections = &text_wrap.select;
  1106. if self.is_phone_select.load(Ordering::Relaxed) && selections.len() == 1 {
  1107. let select = selections.first().unwrap();
  1108. let handle_off_y = baseline + self.handle_descent.get();
  1109. // Get left handle centerpoint
  1110. let (glyph_rect, line_idx) = wrapped_lines.get_glyph_info(select.start);
  1111. let mut p1 = glyph_rect.pos();
  1112. // We always want the handles to be aligned so ignore the glyph's y pos
  1113. p1.y = line_idx as f32 * linespacing + handle_off_y;
  1114. // Get right handle centerpoint
  1115. let (glyph_rect, line_idx) = wrapped_lines.get_glyph_info(select.end);
  1116. let mut p2 = glyph_rect.top_right();
  1117. p2.y = line_idx as f32 * linespacing + handle_off_y;
  1118. // Are we within range of either one?
  1119. //debug!(target: "ui::chatedit", "handle center points = ({p1:?}, {p2:?})");
  1120. const TOUCH_RADIUS_SQ: f32 = 10_000.;
  1121. if p1.dist_sq(&touch_pos) <= TOUCH_RADIUS_SQ {
  1122. debug!(target: "ui::chatedit::touch", "start touch: DragSelectHandle state [side=-1]");
  1123. // Set touch_state status to enable begin dragging them
  1124. touch_info.state = TouchStateAction::DragSelectHandle { side: -1 };
  1125. return true;
  1126. }
  1127. if p2.dist_sq(&touch_pos) <= TOUCH_RADIUS_SQ {
  1128. debug!(target: "ui::chatedit::touch", "start touch: DragSelectHandle state [side=1]");
  1129. // Set touch_state status to enable begin dragging them
  1130. touch_info.state = TouchStateAction::DragSelectHandle { side: 1 };
  1131. return true;
  1132. }
  1133. }
  1134. false
  1135. }
  1136. async fn handle_touch_move(&self, mut touch_pos: Point) -> bool {
  1137. //debug!(target: "ui::chatedit", "handle_touch_move({touch_pos:?})");
  1138. // We must update with non relative touch_pos bcos when doing vertical scrolling
  1139. // we will modify the scroll, which is used by abs_to_local(), which is used
  1140. // to then calculate the max scroll. So it ends up jumping around.
  1141. // We use the abs touch_pos without scroll adjust applied for vert scrolling.
  1142. let touch_state = {
  1143. let mut touch_info = self.touch_info.lock();
  1144. touch_info.update(&touch_pos);
  1145. touch_info.state.clone()
  1146. };
  1147. match &touch_state {
  1148. TouchStateAction::Inactive => return false,
  1149. TouchStateAction::StartSelect => {
  1150. self.abs_to_local(&mut touch_pos);
  1151. self.start_touch_select(touch_pos);
  1152. self.redraw().await;
  1153. debug!(target: "ui::chatedit::touch", "touch state: StartSelect -> Select");
  1154. self.touch_info.lock().state = TouchStateAction::Select;
  1155. }
  1156. TouchStateAction::DragSelectHandle { side } => {
  1157. self.abs_to_local(&mut touch_pos);
  1158. {
  1159. let linespacing = self.linespacing.get();
  1160. let baseline = self.baseline.get();
  1161. let handle_descent = self.handle_descent.get();
  1162. let mut text_wrap = self.text_wrap.lock();
  1163. let width = self.wrap_width();
  1164. let wrapped_lines = text_wrap.wrap(width);
  1165. let rendered = text_wrap.get_render().clone();
  1166. let selections = &mut text_wrap.select;
  1167. assert!(*side == -1 || *side == 1);
  1168. assert!(self.is_phone_select.load(Ordering::Relaxed));
  1169. assert_eq!(selections.len(), 1);
  1170. let select = selections.first_mut().unwrap();
  1171. let mut point = touch_pos;
  1172. // Only allow selecting text that is visible in the box
  1173. // We do our calcs relative to (0, 0) so bhs = rect_h
  1174. point.y -= handle_descent + 25.;
  1175. let bhs = wrapped_lines.height();
  1176. point.y = min_f32(point.y, bhs);
  1177. let mut pos = wrapped_lines.point_to_pos(point);
  1178. if *side == -1 {
  1179. let select_other_pos = &mut select.end;
  1180. if pos >= *select_other_pos {
  1181. pos = *select_other_pos - 1;
  1182. }
  1183. select.start = pos;
  1184. } else {
  1185. let select_other_pos = &mut select.start;
  1186. if pos <= *select_other_pos {
  1187. pos = *select_other_pos + 1;
  1188. }
  1189. select.end = pos;
  1190. }
  1191. }
  1192. self.redraw().await;
  1193. }
  1194. TouchStateAction::ScrollVert { start_pos, scroll_start } => {
  1195. let max_scroll = {
  1196. let mut text_wrap = self.text_wrap.lock();
  1197. self.max_scroll(&mut text_wrap)
  1198. };
  1199. let y_dist = start_pos.y - touch_pos.y;
  1200. let mut scroll = scroll_start + y_dist;
  1201. scroll = scroll.clamp(0., max_scroll);
  1202. if (self.scroll.get() - scroll).abs() < VERT_SCROLL_UPDATE_INC {
  1203. return true
  1204. }
  1205. self.scroll.set(scroll);
  1206. self.redraw().await;
  1207. }
  1208. TouchStateAction::SetCursorPos => {
  1209. // TBH I can't even see the cursor under my thumb so I'll just
  1210. // comment this for now.
  1211. //self.abs_to_local(&mut touch_pos);
  1212. //self.touch_set_cursor_pos(touch_pos).await
  1213. }
  1214. _ => {}
  1215. }
  1216. true
  1217. }
  1218. async fn handle_touch_end(&self, mut touch_pos: Point) -> bool {
  1219. //debug!(target: "ui::chatedit", "handle_touch_end({touch_pos:?})");
  1220. self.abs_to_local(&mut touch_pos);
  1221. let state = self.touch_info.lock().stop();
  1222. match state {
  1223. TouchStateAction::Inactive => return false,
  1224. TouchStateAction::Started { pos: _, instant: _ } | TouchStateAction::SetCursorPos => {
  1225. self.touch_set_cursor_pos(touch_pos).await
  1226. }
  1227. _ => {}
  1228. }
  1229. window::show_keyboard(true);
  1230. true
  1231. }
  1232. async fn touch_set_cursor_pos(&self, mut touch_pos: Point) {
  1233. debug!(target: "ui::chatedit", "touch_set_cursor_pos({touch_pos:?})");
  1234. let width = self.wrap_width();
  1235. {
  1236. let mut text_wrap = self.text_wrap.lock();
  1237. let cursor_pos = text_wrap.set_cursor_with_point(touch_pos, width);
  1238. let select = &mut text_wrap.select;
  1239. select.clear();
  1240. }
  1241. self.is_phone_select.store(false, Ordering::Relaxed);
  1242. // Reshow cursor (if hidden)
  1243. self.pause_blinking();
  1244. self.hide_cursor.store(false, Ordering::Relaxed);
  1245. self.redraw().await;
  1246. }
  1247. /// Whenever the cursor property is modified this MUST be called
  1248. /// to recalculate the scroll x property.
  1249. fn apply_cursor_scrolling(&self) {
  1250. let rect = self.rect.get();
  1251. let cursor_pos = self.cursor_pos.get() as usize;
  1252. let cursor_width = self.cursor_width.get();
  1253. let mut scroll = self.scroll.get();
  1254. let cursor_x = {
  1255. let font_size = self.font_size.get();
  1256. let window_scale = self.window_scale.get();
  1257. let baseline = self.baseline.get();
  1258. let glyphs = self.glyphs.lock().clone();
  1259. let mut glyph_pos_iter =
  1260. GlyphPositionIter::new(font_size, window_scale, &glyphs, baseline);
  1261. if cursor_pos == 0 {
  1262. 0.
  1263. } else if cursor_pos == glyphs.len() {
  1264. let glyph_pos = glyph_pos_iter.last().unwrap();
  1265. let rhs = glyph_pos.rhs() + eol_nudge(font_size, &glyphs);
  1266. rhs
  1267. } else {
  1268. assert!(cursor_pos < glyphs.len());
  1269. let glyph_pos = glyph_pos_iter.nth(cursor_pos).expect("glyph pos mismatch glyphs");
  1270. glyph_pos.x
  1271. }
  1272. };
  1273. // The LHS and RHS of the cursor box
  1274. let cursor_lhs = cursor_x - scroll;
  1275. let cursor_rhs = cursor_lhs + cursor_width;
  1276. // RHS is outside
  1277. if cursor_rhs > rect.w {
  1278. // We want a scroll so RHS = w
  1279. // cursor_x - scroll + CURSOR_WIDTH = rect.w
  1280. scroll = cursor_x + cursor_width - rect.w;
  1281. // LHS is negative
  1282. } else if cursor_lhs < 0. {
  1283. // We want scroll so LHS = 0
  1284. // cursor_x - scroll = 0
  1285. scroll = cursor_x;
  1286. }
  1287. self.scroll.set(scroll);
  1288. }
  1289. fn max_scroll(&self, text_wrap: &mut TextWrap) -> f32 {
  1290. let width = self.wrap_width();
  1291. let wrapped_lines = text_wrap.wrap(width);
  1292. let rect_h = self.rect.get().h;
  1293. let max_scroll = wrapped_lines.height() - rect_h;
  1294. max_scroll.clamp(0., f32::MAX)
  1295. }
  1296. /// When we resize the screen, the rect changes so we may need to alter the scroll.
  1297. /// Or if we delete text.
  1298. fn clamp_scroll(&self, text_wrap: &mut TextWrap) {
  1299. let width = self.wrap_width();
  1300. let wrapped_lines = text_wrap.wrap(width);
  1301. let max_scroll = wrapped_lines.height();
  1302. let mut scroll = self.scroll.get();
  1303. scroll = scroll.clamp(0., wrapped_lines.height());
  1304. self.scroll.set(scroll);
  1305. }
  1306. fn pause_blinking(&self) {
  1307. self.blink_is_paused.store(true, Ordering::Relaxed);
  1308. self.cursor_is_visible.store(true, Ordering::Relaxed);
  1309. }
  1310. async fn redraw(&self) {
  1311. //debug!(target: "ui::chatedit", "redraw()");
  1312. let Some(draw_update) = self.make_draw_calls() else {
  1313. error!(target: "ui::chatedit", "Text failed to draw");
  1314. return;
  1315. };
  1316. self.render_api.replace_draw_calls(draw_update.draw_calls);
  1317. }
  1318. fn redraw_cursor(&self) {
  1319. let cursor_instrs = self.get_cursor_instrs();
  1320. let draw_calls = vec![(
  1321. self.cursor_dc_key,
  1322. GfxDrawCall { instrs: cursor_instrs, dcs: vec![], z_index: self.z_index.get() },
  1323. )];
  1324. self.render_api.replace_draw_calls(draw_calls);
  1325. }
  1326. fn get_cursor_instrs(&self) -> Vec<GfxDrawInstruction> {
  1327. if !self.is_focused.get() ||
  1328. !self.cursor_is_visible.load(Ordering::Relaxed) ||
  1329. self.hide_cursor.load(Ordering::Relaxed)
  1330. {
  1331. return vec![]
  1332. }
  1333. let mut cursor_instrs = vec![];
  1334. let cursor_pos = self.get_cursor_pos();
  1335. // There is some mess here since ApplyView is in abs screen coords but should be
  1336. // relative, and also work together with Move. We will fix this later in gfx subsys.
  1337. let mut view_rect = self.rect.get();
  1338. view_rect.h = self.max_height.get();
  1339. cursor_instrs.push(GfxDrawInstruction::ApplyView(view_rect));
  1340. cursor_instrs.push(GfxDrawInstruction::Move(cursor_pos));
  1341. let cursor_mesh = {
  1342. let mut cursor_mesh = self.cursor_mesh.lock();
  1343. if cursor_mesh.is_none() {
  1344. *cursor_mesh = Some(self.regen_cursor_mesh());
  1345. }
  1346. cursor_mesh.clone().unwrap()
  1347. };
  1348. cursor_instrs.push(GfxDrawInstruction::Draw(cursor_mesh));
  1349. cursor_instrs
  1350. }
  1351. fn make_draw_calls(&self) -> Option<DrawUpdate> {
  1352. let text_mesh = self.regen_text_mesh();
  1353. let cursor_instrs = self.get_cursor_instrs();
  1354. let rect = self.rect.get();
  1355. Some(DrawUpdate {
  1356. key: self.main_dc_key,
  1357. draw_calls: vec![
  1358. (
  1359. self.main_dc_key,
  1360. GfxDrawCall {
  1361. instrs: vec![],
  1362. dcs: vec![self.text_dc_key, self.cursor_dc_key],
  1363. z_index: self.z_index.get(),
  1364. },
  1365. ),
  1366. (
  1367. self.text_dc_key,
  1368. GfxDrawCall {
  1369. instrs: vec![
  1370. GfxDrawInstruction::Move(rect.pos()),
  1371. GfxDrawInstruction::Draw(text_mesh),
  1372. ],
  1373. dcs: vec![],
  1374. z_index: self.z_index.get(),
  1375. },
  1376. ),
  1377. (
  1378. self.cursor_dc_key,
  1379. GfxDrawCall { instrs: cursor_instrs, dcs: vec![], z_index: self.z_index.get() },
  1380. ),
  1381. ],
  1382. })
  1383. }
  1384. }
  1385. impl Drop for ChatEdit {
  1386. fn drop(&mut self) {
  1387. self.render_api.replace_draw_calls(vec![(self.text_dc_key, Default::default())]);
  1388. }
  1389. }
  1390. #[async_trait]
  1391. impl UIObject for ChatEdit {
  1392. fn z_index(&self) -> u32 {
  1393. self.z_index.get()
  1394. }
  1395. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  1396. let me = Arc::downgrade(&self);
  1397. let node_ref = &self.node.upgrade().unwrap();
  1398. let node_name = node_ref.name.clone();
  1399. let node_id = node_ref.id;
  1400. let mut on_modify = OnModify::new(ex.clone(), node_name, node_id, me.clone());
  1401. on_modify.when_change(self.is_focused.prop(), Self::change_focus);
  1402. // When text has been changed.
  1403. // Cursor and selection might be invalidated.
  1404. async fn reset(self_: Arc<ChatEdit>) {
  1405. self_.cursor_pos.set(0);
  1406. self_.selected.set_null(Role::Internal, 0).unwrap();
  1407. self_.selected.set_null(Role::Internal, 1).unwrap();
  1408. self_.scroll.set(0.);
  1409. self_.redraw();
  1410. }
  1411. async fn redraw(self_: Arc<ChatEdit>) {
  1412. self_.redraw().await;
  1413. }
  1414. on_modify.when_change(self.rect.prop(), redraw);
  1415. on_modify.when_change(self.baseline.prop(), redraw);
  1416. on_modify.when_change(self.linespacing.prop(), redraw);
  1417. on_modify.when_change(self.select_ascent.prop(), redraw);
  1418. on_modify.when_change(self.select_descent.prop(), redraw);
  1419. on_modify.when_change(self.handle_descent.prop(), redraw);
  1420. // The commented properties are modified on input events
  1421. // So then redraw() will get repeatedly triggered when these properties
  1422. // are changed. We should find a solution. For now the hooks are disabled.
  1423. //on_modify.when_change(scroll.prop(), redraw);
  1424. //on_modify.when_change(cursor_pos.prop(), redraw);
  1425. on_modify.when_change(self.font_size.prop(), redraw);
  1426. // We must also reshape text
  1427. on_modify.when_change(self.text.prop(), reset);
  1428. on_modify.when_change(self.text_color.prop(), redraw);
  1429. on_modify.when_change(self.hi_bg_color.prop(), redraw);
  1430. //on_modify.when_change(selected.clone(), redraw);
  1431. on_modify.when_change(self.z_index.prop(), redraw);
  1432. on_modify.when_change(self.debug.prop(), redraw);
  1433. async fn regen_cursor(self_: Arc<ChatEdit>) {
  1434. let mesh = std::mem::take(&mut *self_.cursor_mesh.lock());
  1435. }
  1436. on_modify.when_change(self.cursor_color.prop(), regen_cursor);
  1437. on_modify.when_change(self.cursor_ascent.prop(), regen_cursor);
  1438. on_modify.when_change(self.cursor_descent.prop(), regen_cursor);
  1439. on_modify.when_change(self.cursor_width.prop(), regen_cursor);
  1440. let me2 = me.clone();
  1441. let cursor_blink_time = self.cursor_blink_time.clone();
  1442. let cursor_idle_time = self.cursor_idle_time.clone();
  1443. let blinking_cursor_task = ex.spawn(async move {
  1444. loop {
  1445. msleep(cursor_blink_time.get() as u64).await;
  1446. let self_ = me2.upgrade().unwrap();
  1447. if self_.blink_is_paused.swap(false, Ordering::Relaxed) {
  1448. msleep(cursor_idle_time.get() as u64).await;
  1449. continue
  1450. }
  1451. // Invert the bool
  1452. self_.cursor_is_visible.fetch_not(Ordering::Relaxed);
  1453. self_.redraw_cursor();
  1454. }
  1455. });
  1456. let mut tasks = on_modify.tasks;
  1457. tasks.push(blinking_cursor_task);
  1458. self.tasks.set(tasks);
  1459. }
  1460. async fn draw(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  1461. debug!(target: "ui::chatedit", "EditBox::draw()");
  1462. *self.parent_rect.lock() = Some(parent_rect);
  1463. //self.clamp_scroll();
  1464. self.make_draw_calls()
  1465. }
  1466. async fn handle_char(&self, key: char, mods: KeyMods, repeat: bool) -> bool {
  1467. // First filter for only single digit keys
  1468. if DISALLOWED_CHARS.contains(&key) {
  1469. return false
  1470. }
  1471. if !self.is_focused.get() {
  1472. return false
  1473. }
  1474. if mods.ctrl || mods.alt {
  1475. if repeat {
  1476. return false
  1477. }
  1478. self.handle_shortcut(key, &mods).await;
  1479. return true
  1480. }
  1481. let actions = {
  1482. let mut repeater = self.key_repeat.lock();
  1483. repeater.key_down(PressedKey::Char(key), repeat)
  1484. };
  1485. //debug!(target: "ui::chatedit", "Key {:?} has {} actions", key, actions);
  1486. for _ in 0..actions {
  1487. self.insert_char(key).await;
  1488. }
  1489. true
  1490. }
  1491. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  1492. // First filter for only single digit keys
  1493. // Avoid processing events handled by insert_char()
  1494. if !ALLOWED_KEYCODES.contains(&key) {
  1495. return false
  1496. }
  1497. if !self.is_focused.get() {
  1498. return false
  1499. }
  1500. let actions = {
  1501. let mut repeater = self.key_repeat.lock();
  1502. repeater.key_down(PressedKey::Key(key), repeat)
  1503. };
  1504. // Suppress noisy message
  1505. /*if actions > 0 {
  1506. debug!(target: "ui::chatedit", "Key {:?} has {} actions", key, actions);
  1507. }*/
  1508. for _ in 0..actions {
  1509. self.handle_key(&key, &mods).await;
  1510. }
  1511. true
  1512. }
  1513. async fn handle_mouse_btn_down(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  1514. if !self.is_active.get() {
  1515. return false
  1516. }
  1517. if btn != MouseButton::Left {
  1518. return false
  1519. }
  1520. let rect = self.rect.get();
  1521. // clicking inside box will:
  1522. // 1. make it active
  1523. // 2. begin selection
  1524. if !rect.contains(mouse_pos) {
  1525. if self.is_focused.get() {
  1526. debug!(target: "ui::chatedit", "EditBox unfocused");
  1527. self.is_focused.set(false);
  1528. self.text_wrap.lock().select.clear();
  1529. self.redraw().await;
  1530. }
  1531. return false
  1532. }
  1533. if self.is_focused.get() {
  1534. debug!(target: "ui::chatedit", "EditBox clicked");
  1535. } else {
  1536. debug!(target: "ui::chatedit", "EditBox focused");
  1537. self.is_focused.set(true);
  1538. }
  1539. // Move mouse pos within this widget
  1540. self.abs_to_local(&mut mouse_pos);
  1541. let width = self.wrap_width();
  1542. {
  1543. let mut text_wrap = self.text_wrap.lock();
  1544. let cursor_pos = text_wrap.set_cursor_with_point(mouse_pos, width);
  1545. debug!(target: "ui::editbox", "Mouse move cursor pos to {cursor_pos}");
  1546. // begin selection
  1547. let select = &mut text_wrap.select;
  1548. select.clear();
  1549. select.push(Selection::new(cursor_pos, cursor_pos));
  1550. self.mouse_btn_held.store(true, Ordering::Relaxed);
  1551. }
  1552. self.pause_blinking();
  1553. self.redraw().await;
  1554. true
  1555. }
  1556. async fn handle_mouse_btn_up(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  1557. if !self.is_active.get() {
  1558. return false
  1559. }
  1560. // releasing mouse button will end selection
  1561. self.mouse_btn_held.store(false, Ordering::Relaxed);
  1562. false
  1563. }
  1564. async fn handle_mouse_move(&self, mut mouse_pos: Point) -> bool {
  1565. if !self.is_active.get() {
  1566. return false
  1567. }
  1568. let rect = self.rect.get();
  1569. self.is_mouse_hover.store(rect.contains(mouse_pos), Ordering::Relaxed);
  1570. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  1571. return false;
  1572. }
  1573. // if active and selection_active, then use x to modify the selection.
  1574. // also implement scrolling when cursor is to the left or right
  1575. // just scroll to the end
  1576. // also set cursor_pos too
  1577. // Move mouse pos within this widget
  1578. self.abs_to_local(&mut mouse_pos);
  1579. let width = self.wrap_width();
  1580. {
  1581. let mut text_wrap = self.text_wrap.lock();
  1582. let cursor_pos = text_wrap.set_cursor_with_point(mouse_pos, width);
  1583. // modify current selection
  1584. let select = &mut text_wrap.select;
  1585. select.last_mut().unwrap().end = cursor_pos;
  1586. }
  1587. self.pause_blinking();
  1588. //self.apply_cursor_scrolling();
  1589. self.redraw().await;
  1590. true
  1591. }
  1592. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  1593. //debug!(target: "ui::chatedit", "rect={rect:?}, wheel_pos={wheel_pos:?}");
  1594. if !self.is_mouse_hover.load(Ordering::Relaxed) {
  1595. return false
  1596. }
  1597. let max_scroll = {
  1598. let mut text_wrap = self.text_wrap.lock();
  1599. self.max_scroll(&mut text_wrap)
  1600. };
  1601. let mut scroll = self.scroll.get() + wheel_pos.y * self.scroll_speed.get();
  1602. scroll = scroll.clamp(0., max_scroll);
  1603. debug!(target: "ui::chatedit", "handle_mouse_wheel({wheel_pos:?}) [scroll={scroll}]");
  1604. self.scroll.set(scroll);
  1605. self.redraw().await;
  1606. true
  1607. }
  1608. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  1609. if !self.is_active.get() {
  1610. return false
  1611. }
  1612. // Ignore multi-touch
  1613. if id != 0 {
  1614. return false
  1615. }
  1616. match phase {
  1617. TouchPhase::Started => self.handle_touch_start(touch_pos).await,
  1618. TouchPhase::Moved => self.handle_touch_move(touch_pos).await,
  1619. TouchPhase::Ended => self.handle_touch_end(touch_pos).await,
  1620. TouchPhase::Cancelled => false,
  1621. }
  1622. }
  1623. async fn handle_compose_text(&self, suggest_text: &str, is_commit: bool) -> bool {
  1624. debug!(target: "ui::chatedit", "handle_compose_text({suggest_text}, {is_commit})");
  1625. if !self.is_active.get() {
  1626. return false
  1627. }
  1628. {
  1629. let mut text_wrap = self.text_wrap.lock();
  1630. text_wrap.clear_cache();
  1631. text_wrap.editable.compose(suggest_text, is_commit);
  1632. self.clamp_scroll(&mut text_wrap);
  1633. }
  1634. //self.apply_cursor_scrolling();
  1635. self.redraw().await;
  1636. true
  1637. }
  1638. async fn handle_set_compose_region(&self, start: usize, end: usize) -> bool {
  1639. debug!(target: "ui::chatedit", "handle_set_compose_region({start}, {end})");
  1640. if !self.is_active.get() {
  1641. return false
  1642. }
  1643. {
  1644. let mut text_wrap = self.text_wrap.lock();
  1645. text_wrap.clear_cache();
  1646. text_wrap.editable.set_compose_region(start, end);
  1647. }
  1648. self.redraw().await;
  1649. true
  1650. }
  1651. }