chatedit.rs 70 KB

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