editbox.rs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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 miniquad::{window, BufferId, KeyCode, KeyMods, MouseButton, TextureId, TouchPhase};
  19. use rand::{rngs::OsRng, Rng};
  20. use std::{
  21. collections::HashMap,
  22. sync::{
  23. atomic::{AtomicBool, Ordering},
  24. Arc, Mutex as SyncMutex, Weak,
  25. },
  26. time::Instant,
  27. };
  28. use crate::{
  29. error::Result,
  30. gfx2::{
  31. DrawCall, DrawInstruction, DrawMesh, GraphicsEventPublisherPtr, Point, Rectangle,
  32. RenderApi, RenderApiPtr, Vertex,
  33. },
  34. mesh::{Color, MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_WHITE},
  35. prop::{
  36. PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr, PropertyStr, PropertyUint32,
  37. },
  38. pubsub::Subscription,
  39. scene::{Pimpl, SceneGraph, SceneGraphPtr2, SceneNodeId},
  40. text2::{self, Glyph, GlyphPositionIter, RenderedAtlas, SpritePtr, TextShaper, TextShaperPtr},
  41. util::zip3,
  42. };
  43. use super::{eval_rect, get_parent_rect, read_rect, DrawUpdate, OnModify, Stoppable};
  44. const CURSOR_WIDTH: f32 = 4.;
  45. #[derive(Debug, Clone, Eq, Hash, PartialEq)]
  46. enum PressedKey {
  47. Char(char),
  48. Key(KeyCode),
  49. }
  50. /// On key press (repeat=false), we immediately process the event.
  51. /// Then there's a delay (repeat=true) and then for every step time
  52. /// while key press events are being sent, we allow an event.
  53. /// This ensures smooth typing in the editbox.
  54. struct PressedKeysSmoothRepeat {
  55. /// When holding keys, we track from start and last sent time.
  56. /// This is useful for initial delay and smooth scrolling.
  57. pressed_keys: HashMap<PressedKey, RepeatingKeyTimer>,
  58. /// Initial delay before allowing keys
  59. start_delay: u32,
  60. /// Minimum time between repeated keys
  61. step_time: u32,
  62. }
  63. impl PressedKeysSmoothRepeat {
  64. fn new(start_delay: u32, step_time: u32) -> Self {
  65. Self { pressed_keys: HashMap::new(), start_delay, step_time }
  66. }
  67. fn key_down(&mut self, key: PressedKey, repeat: bool) -> u32 {
  68. //debug!(target: "PressedKeysSmoothRepeat", "key_down({:?}, {})", key, repeat);
  69. if !repeat {
  70. self.pressed_keys.remove(&key);
  71. return 1;
  72. }
  73. // Insert key if not exists
  74. if !self.pressed_keys.contains_key(&key) {
  75. //debug!(target: "PressedKeysSmoothRepeat", "insert key {:?}", key);
  76. self.pressed_keys.insert(key.clone(), RepeatingKeyTimer::new());
  77. }
  78. let repeater = self.pressed_keys.get_mut(&key).expect("repeat map");
  79. repeater.update(self.start_delay, self.step_time)
  80. }
  81. /*
  82. fn key_up(&mut self, key: &PressedKey) {
  83. //debug!(target: "PressedKeysSmoothRepeat", "key_up({:?})", key);
  84. println!("{:?}", self.pressed_keys.keys());
  85. assert!(self.pressed_keys.contains_key(key));
  86. self.pressed_keys.remove(key).expect("key was pressed");
  87. }
  88. */
  89. }
  90. struct RepeatingKeyTimer {
  91. start: Instant,
  92. actions: u32,
  93. }
  94. impl RepeatingKeyTimer {
  95. fn new() -> Self {
  96. Self { start: Instant::now(), actions: 0 }
  97. }
  98. fn update(&mut self, start_delay: u32, step_time: u32) -> u32 {
  99. let elapsed = self.start.elapsed().as_millis();
  100. //debug!(target: "RepeatingKeyTimer", "update() elapsed={}, actions={}",
  101. // elapsed, self.actions);
  102. if elapsed < start_delay as u128 {
  103. return 0
  104. }
  105. let total_actions = ((elapsed - start_delay as u128) / step_time as u128) as u32;
  106. let remaining_actions = total_actions - self.actions;
  107. self.actions = total_actions;
  108. remaining_actions
  109. }
  110. }
  111. #[derive(Clone)]
  112. struct TextRenderInfo {
  113. mesh: MeshInfo,
  114. texture_id: TextureId,
  115. }
  116. pub type EditBoxPtr = Arc<EditBox>;
  117. pub struct EditBox {
  118. node_id: SceneNodeId,
  119. tasks: Vec<smol::Task<()>>,
  120. sg: SceneGraphPtr2,
  121. render_api: RenderApiPtr,
  122. // So we can lock the event stream when we gain focus
  123. event_pub: GraphicsEventPublisherPtr,
  124. text_shaper: TextShaperPtr,
  125. key_repeat: SyncMutex<PressedKeysSmoothRepeat>,
  126. render_info: SyncMutex<Option<TextRenderInfo>>,
  127. glyphs: SyncMutex<Vec<Glyph>>,
  128. dc_key: u64,
  129. is_active: PropertyBool,
  130. is_focused: PropertyBool,
  131. rect: PropertyPtr,
  132. baseline: PropertyFloat32,
  133. scroll: PropertyFloat32,
  134. cursor_pos: PropertyUint32,
  135. font_size: PropertyFloat32,
  136. text: PropertyStr,
  137. text_color: PropertyColor,
  138. cursor_color: PropertyColor,
  139. hi_bg_color: PropertyColor,
  140. selected: PropertyPtr,
  141. z_index: PropertyUint32,
  142. debug: PropertyBool,
  143. mouse_btn_held: AtomicBool,
  144. }
  145. impl EditBox {
  146. pub async fn new(
  147. ex: Arc<smol::Executor<'static>>,
  148. sg: SceneGraphPtr2,
  149. node_id: SceneNodeId,
  150. render_api: RenderApiPtr,
  151. event_pub: GraphicsEventPublisherPtr,
  152. text_shaper: TextShaperPtr,
  153. ) -> Pimpl {
  154. let scene_graph = sg.lock().await;
  155. let node = scene_graph.get_node(node_id).unwrap();
  156. let node_name = node.name.clone();
  157. let is_active = PropertyBool::wrap(node, "is_active", 0).unwrap();
  158. let is_focused = PropertyBool::wrap(node, "is_focused", 0).unwrap();
  159. let rect = node.get_property("rect").expect("EditBox::rect");
  160. let baseline = PropertyFloat32::wrap(node, "baseline", 0).unwrap();
  161. let scroll = PropertyFloat32::wrap(node, "scroll", 0).unwrap();
  162. let cursor_pos = PropertyUint32::wrap(node, "cursor_pos", 0).unwrap();
  163. let font_size = PropertyFloat32::wrap(node, "font_size", 0).unwrap();
  164. let text = PropertyStr::wrap(node, "text", 0).unwrap();
  165. let text_color = PropertyColor::wrap(node, "text_color").unwrap();
  166. let cursor_color = PropertyColor::wrap(node, "cursor_color").unwrap();
  167. let hi_bg_color = PropertyColor::wrap(node, "hi_bg_color").unwrap();
  168. let selected = node.get_property("selected").unwrap();
  169. let z_index = PropertyUint32::wrap(node, "z_index", 0).unwrap();
  170. let debug = PropertyBool::wrap(node, "debug", 0).unwrap();
  171. drop(scene_graph);
  172. // testing
  173. window::show_keyboard(true);
  174. // Must do this whenever the text changes
  175. let glyphs = text_shaper.shape(text.get(), font_size.get()).await;
  176. let self_ = Arc::new_cyclic(|me: &Weak<Self>| {
  177. // Start a task monitoring for key down events
  178. let ev_sub = event_pub.subscribe_char();
  179. let me2 = me.clone();
  180. let char_task = ex.spawn(async move {
  181. loop {
  182. Self::process_char(&me2, &ev_sub).await;
  183. }
  184. });
  185. let ev_sub = event_pub.subscribe_key_down();
  186. let me2 = me.clone();
  187. let key_down_task = ex.spawn(async move {
  188. loop {
  189. Self::process_key_down(&me2, &ev_sub).await;
  190. }
  191. });
  192. /*
  193. let ev_sub = event_pub.subscribe_key_up();
  194. let me2 = me.clone();
  195. let key_up_task = ex.spawn(async move {
  196. loop {
  197. let Ok((key, mods)) = ev_sub.receive().await else {
  198. debug!(target: "ui::editbox", "Event relayer closed");
  199. break
  200. };
  201. let Some(self_) = me2.upgrade() else {
  202. // Should not happen
  203. panic!("self destroyed before key_up_task was stopped!");
  204. };
  205. let key = PressedKey::Key(key);
  206. let mut repeater = self_.key_repeat.lock().unwrap();
  207. repeater.key_up(&key);
  208. }
  209. });
  210. */
  211. let ev_sub = event_pub.subscribe_mouse_btn_down();
  212. let me2 = me.clone();
  213. let mouse_btn_down_task = ex.spawn(async move {
  214. loop {
  215. Self::process_mouse_btn_down(&me2, &ev_sub).await;
  216. }
  217. });
  218. let ev_sub = event_pub.subscribe_mouse_btn_up();
  219. let me2 = me.clone();
  220. let mouse_btn_up_task = ex.spawn(async move {
  221. loop {
  222. Self::process_mouse_btn_up(&me2, &ev_sub).await;
  223. }
  224. });
  225. let ev_sub = event_pub.subscribe_mouse_move();
  226. let me2 = me.clone();
  227. let mouse_move_task = ex.spawn(async move {
  228. loop {
  229. Self::process_mouse_move(&me2, &ev_sub).await;
  230. }
  231. });
  232. let ev_sub = event_pub.subscribe_touch();
  233. let me2 = me.clone();
  234. let touch_task = ex.spawn(async move {
  235. loop {
  236. Self::process_touch(&me2, &ev_sub).await;
  237. }
  238. });
  239. let mut on_modify = OnModify::new(ex, node_name, node_id, me.clone());
  240. on_modify.when_change(is_focused.prop(), Self::change_focus);
  241. async fn redraw(self_: Arc<EditBox>) {
  242. self_.redraw().await;
  243. }
  244. on_modify.when_change(rect.clone(), redraw);
  245. on_modify.when_change(baseline.prop(), redraw);
  246. // The commented properties are modified on input events
  247. // So then redraw() will get repeatedly triggered when these properties
  248. // are changed. We should find a solution. For now the hooks are disabled.
  249. //on_modify.when_change(scroll.prop(), redraw);
  250. //on_modify.when_change(cursor_pos.prop(), redraw);
  251. on_modify.when_change(font_size.prop(), redraw);
  252. // We must also reshape text
  253. //on_modify.when_change(text.prop(), redraw);
  254. on_modify.when_change(text_color.prop(), redraw);
  255. on_modify.when_change(cursor_color.prop(), redraw);
  256. on_modify.when_change(hi_bg_color.prop(), redraw);
  257. //on_modify.when_change(selected.clone(), redraw);
  258. on_modify.when_change(z_index.prop(), redraw);
  259. on_modify.when_change(debug.prop(), redraw);
  260. // on modify tasks too
  261. let mut tasks = vec![
  262. char_task,
  263. key_down_task,
  264. mouse_btn_down_task,
  265. mouse_btn_up_task,
  266. mouse_move_task,
  267. touch_task,
  268. ];
  269. tasks.append(&mut on_modify.tasks);
  270. Self {
  271. node_id,
  272. tasks,
  273. sg,
  274. render_api,
  275. event_pub,
  276. text_shaper,
  277. key_repeat: SyncMutex::new(PressedKeysSmoothRepeat::new(400, 50)),
  278. render_info: SyncMutex::new(None),
  279. glyphs: SyncMutex::new(glyphs),
  280. dc_key: OsRng.gen(),
  281. is_active,
  282. is_focused,
  283. rect,
  284. baseline,
  285. scroll,
  286. cursor_pos,
  287. font_size,
  288. text,
  289. text_color,
  290. cursor_color,
  291. hi_bg_color,
  292. selected,
  293. z_index,
  294. debug,
  295. mouse_btn_held: AtomicBool::new(false),
  296. }
  297. });
  298. Pimpl::EditBox(self_)
  299. }
  300. /// This MUST be called whenever the text property is changed.
  301. async fn regen_glyphs(&self) {
  302. let glyphs = self.text_shaper.shape(self.text.get(), self.font_size.get()).await;
  303. *self.glyphs.lock().unwrap() = glyphs;
  304. }
  305. /// Called whenever the text or any text property changes.
  306. /// Not related to cursor, text highlighting or bounding (clip) rects.
  307. async fn regen_mesh(&self, mut clip: Rectangle) -> TextRenderInfo {
  308. clip.x = 0.;
  309. clip.y = 0.;
  310. let is_focused = self.is_focused.get();
  311. let text = self.text.get();
  312. let font_size = self.font_size.get();
  313. let text_color = self.text_color.get();
  314. let baseline = self.baseline.get();
  315. let scroll = self.scroll.get();
  316. let cursor_pos = self.cursor_pos.get() as usize;
  317. let cursor_color = self.cursor_color.get();
  318. let debug = self.debug.get();
  319. debug!(target: "ui::editbox", "Rendering text '{}' clip={:?}", text, clip);
  320. let glyphs = self.glyphs.lock().unwrap().clone();
  321. let atlas = text2::make_texture_atlas(&self.render_api, font_size, &glyphs).await.unwrap();
  322. let mut mesh = MeshBuilder::with_clip(clip.clone());
  323. self.draw_selected(&mut mesh, &glyphs, clip.h).unwrap();
  324. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  325. // Used for drawing the cursor when it's at the end of the line.
  326. let mut rhs = 0.;
  327. for (glyph_idx, uv_rect, mut glyph_rect, glyph) in
  328. zip3(atlas.uv_rects.into_iter(), glyph_pos_iter, glyphs.iter())
  329. {
  330. glyph_rect.x += scroll;
  331. //mesh.draw_outline(&glyph_rect, COLOR_BLUE, 2.);
  332. let mut color = text_color.clone();
  333. if glyph.sprite.has_color {
  334. color = COLOR_WHITE;
  335. }
  336. mesh.draw_box(&glyph_rect, color, &uv_rect);
  337. if is_focused && cursor_pos != 0 && cursor_pos == glyph_idx {
  338. let cursor_rect =
  339. Rectangle { x: glyph_rect.x - CURSOR_WIDTH, y: 0., w: CURSOR_WIDTH, h: clip.h };
  340. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  341. }
  342. rhs = glyph_rect.rhs();
  343. }
  344. if is_focused && cursor_pos == 0 {
  345. let cursor_rect = Rectangle { x: 0., y: 0., w: CURSOR_WIDTH, h: clip.h };
  346. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  347. } else if is_focused && cursor_pos == glyphs.len() {
  348. let cursor_rect =
  349. Rectangle { x: rhs - CURSOR_WIDTH, y: 0., w: CURSOR_WIDTH, h: clip.h };
  350. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  351. }
  352. if debug {
  353. mesh.draw_outline(&clip, COLOR_BLUE, 1.);
  354. }
  355. let mesh = mesh.alloc(&self.render_api).await.unwrap();
  356. TextRenderInfo { mesh, texture_id: atlas.texture_id }
  357. }
  358. fn draw_selected(
  359. &self,
  360. mesh: &mut MeshBuilder,
  361. glyphs: &Vec<Glyph>,
  362. clip_h: f32,
  363. ) -> Result<()> {
  364. if self.selected.is_null(0)? || self.selected.is_null(1)? {
  365. // Nothing selected so do nothing
  366. return Ok(())
  367. }
  368. let start = self.selected.get_u32(0)? as usize;
  369. let end = self.selected.get_u32(1)? as usize;
  370. // Selection started but nothing selected yet so do nothing
  371. if start == end {
  372. return Ok(())
  373. }
  374. let sel_start = std::cmp::min(start, end);
  375. let sel_end = std::cmp::max(start, end);
  376. let font_size = self.font_size.get();
  377. let baseline = self.baseline.get();
  378. let scroll = self.scroll.get();
  379. let hi_bg_color = self.hi_bg_color.get();
  380. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  381. let mut start_x = 0.;
  382. let mut end_x = 0.;
  383. // When cursor lands at the end of the line
  384. let mut rhs = 0.;
  385. for (glyph_idx, mut glyph_rect) in glyph_pos_iter.enumerate() {
  386. glyph_rect.x += scroll;
  387. if glyph_idx == sel_start {
  388. start_x = glyph_rect.x;
  389. }
  390. if glyph_idx == sel_end {
  391. end_x = glyph_rect.x;
  392. }
  393. rhs = glyph_rect.rhs();
  394. }
  395. if sel_start == 0 {
  396. start_x = scroll;
  397. }
  398. if sel_end == glyphs.len() {
  399. end_x = rhs;
  400. }
  401. // We don't need to do manual clipping since MeshBuilder should do that
  402. let select_rect = Rectangle { x: start_x, y: 0., w: end_x - start_x, h: clip_h };
  403. mesh.draw_box(&select_rect, hi_bg_color, &Rectangle::zero());
  404. Ok(())
  405. }
  406. async fn do_key_action(&self, key: char, mods: &KeyMods) {
  407. match key {
  408. //KeyCode::Left => {}
  409. _ => self.insert_char(key).await,
  410. }
  411. }
  412. async fn process_char(me: &Weak<Self>, ev_sub: &Subscription<(char, KeyMods, bool)>) {
  413. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  414. debug!(target: "ui::editbox", "Event relayer closed");
  415. return
  416. };
  417. // First filter for only single digit keys
  418. if DISALLOWED_CHARS.contains(&key) {
  419. return
  420. }
  421. let Some(self_) = me.upgrade() else {
  422. // Should not happen
  423. panic!("self destroyed before char_task was stopped!");
  424. };
  425. if !self_.is_focused.get() {
  426. return
  427. }
  428. if mods.ctrl || mods.alt {
  429. if repeat {
  430. return
  431. }
  432. self_.handle_shortcut(key, &mods).await;
  433. return
  434. }
  435. let actions = {
  436. let mut repeater = self_.key_repeat.lock().unwrap();
  437. repeater.key_down(PressedKey::Char(key), repeat)
  438. };
  439. debug!(target: "ui::editbox", "Key {:?} has {} actions", key, actions);
  440. for _ in 0..actions {
  441. self_.insert_char(key).await;
  442. }
  443. }
  444. async fn process_key_down(me: &Weak<Self>, ev_sub: &Subscription<(KeyCode, KeyMods, bool)>) {
  445. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  446. debug!(target: "ui::editbox", "Event relayer closed");
  447. return
  448. };
  449. // First filter for only single digit keys
  450. // Avoid processing events handled by insert_char()
  451. if !ALLOWED_KEYCODES.contains(&key) {
  452. return
  453. }
  454. let Some(self_) = me.upgrade() else {
  455. // Should not happen
  456. panic!("self destroyed before char_task was stopped!");
  457. };
  458. if !self_.is_focused.get() {
  459. return
  460. }
  461. let actions = {
  462. let mut repeater = self_.key_repeat.lock().unwrap();
  463. repeater.key_down(PressedKey::Key(key), repeat)
  464. };
  465. // Suppress noisy message
  466. if actions > 0 {
  467. debug!(target: "ui::editbox", "Key {:?} has {} actions", key, actions);
  468. }
  469. for _ in 0..actions {
  470. self_.handle_key(&key, &mods).await;
  471. }
  472. }
  473. async fn process_mouse_btn_down(
  474. me: &Weak<Self>,
  475. ev_sub: &Subscription<(MouseButton, f32, f32)>,
  476. ) {
  477. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  478. debug!(target: "ui::editbox", "Event relayer closed");
  479. return
  480. };
  481. let Some(self_) = me.upgrade() else {
  482. // Should not happen
  483. panic!("self destroyed before mouse_btn_down_task was stopped!");
  484. };
  485. if !self_.is_active.get() {
  486. return
  487. }
  488. self_.handle_mouse_btn_down(btn, mouse_x, mouse_y).await;
  489. }
  490. async fn process_mouse_btn_up(me: &Weak<Self>, ev_sub: &Subscription<(MouseButton, f32, f32)>) {
  491. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  492. debug!(target: "ui::editbox", "Event relayer closed");
  493. return
  494. };
  495. let Some(self_) = me.upgrade() else {
  496. // Should not happen
  497. panic!("self destroyed before mouse_btn_up_task was stopped!");
  498. };
  499. if !self_.is_active.get() {
  500. return
  501. }
  502. self_.handle_mouse_btn_up(btn, mouse_x, mouse_y);
  503. }
  504. async fn process_mouse_move(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) {
  505. let Ok((mouse_x, mouse_y)) = ev_sub.receive().await else {
  506. debug!(target: "ui::editbox", "Event relayer closed");
  507. return
  508. };
  509. let Some(self_) = me.upgrade() else {
  510. // Should not happen
  511. panic!("self destroyed before mouse_move_task was stopped!");
  512. };
  513. if !self_.is_active.get() {
  514. return
  515. }
  516. self_.handle_mouse_move(mouse_x, mouse_y).await;
  517. }
  518. async fn process_touch(me: &Weak<Self>, ev_sub: &Subscription<(TouchPhase, u64, f32, f32)>) {
  519. let Ok((phase, id, touch_x, touch_y)) = ev_sub.receive().await else {
  520. debug!(target: "ui::editbox", "Event relayer closed");
  521. return
  522. };
  523. let Some(self_) = me.upgrade() else {
  524. // Should not happen
  525. panic!("self destroyed before touch_task was stopped!");
  526. };
  527. if !self_.is_active.get() {
  528. return
  529. }
  530. self_.handle_touch(phase, id, touch_x, touch_y).await;
  531. }
  532. async fn change_focus(self: Arc<Self>) {
  533. if !self.is_active.get() {
  534. return
  535. }
  536. debug!(target: "ui::editbox", "Focus changed");
  537. let is_focused = self.is_focused.get();
  538. // Cursor visibility will change so just redraw everything lol
  539. self.redraw().await;
  540. }
  541. async fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_x: f32, mouse_y: f32) {
  542. if btn != MouseButton::Left {
  543. return
  544. }
  545. let mouse_pos = Point::from([mouse_x, mouse_y]);
  546. let mut focus_changed = false;
  547. let Some(rect) = self.get_cached_world_rect().await else { return };
  548. // clicking inside box will:
  549. // 1. make it active
  550. // 2. begin selection
  551. if rect.contains(&mouse_pos) {
  552. window::show_keyboard(true);
  553. if self.is_focused.get() {
  554. debug!(target: "ui::editbox", "EditBox clicked");
  555. } else {
  556. debug!(target: "ui::editbox", "EditBox focused");
  557. self.is_focused.set(true);
  558. focus_changed = true;
  559. }
  560. let cpos = self.find_closest_glyph_idx(mouse_x, &rect);
  561. // set cursor pos
  562. self.cursor_pos.set(cpos);
  563. self.apply_cursor_scrolling();
  564. // begin selection
  565. self.selected.set_u32(0, cpos).unwrap();
  566. self.selected.set_u32(1, cpos).unwrap();
  567. self.mouse_btn_held.store(true, Ordering::Relaxed);
  568. // click outside the box will make it unfocused
  569. } else if self.is_focused.get() {
  570. debug!(target: "ui::editbox", "EditBox unfocused");
  571. self.is_focused.set(false);
  572. self.selected.set_null(0).unwrap();
  573. self.selected.set_null(1).unwrap();
  574. focus_changed = true;
  575. }
  576. // Further on_focus logic change is handled by property modified callback
  577. // which calls Self::change_focus()
  578. // We still need to redraw if cursor is changed though, but we want to avoid redrawing
  579. // twice, so we do this check:
  580. if !focus_changed {
  581. self.redraw().await;
  582. }
  583. }
  584. fn handle_mouse_btn_up(&self, btn: MouseButton, x: f32, y: f32) {
  585. if btn != MouseButton::Left {
  586. return
  587. }
  588. // releasing mouse button will end selection
  589. self.mouse_btn_held.store(false, Ordering::Relaxed);
  590. }
  591. async fn handle_mouse_move(&self, mouse_x: f32, mouse_y: f32) {
  592. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  593. return;
  594. }
  595. // if active and selection_active, then use x to modify the selection.
  596. // also implement scrolling when cursor is to the left or right
  597. // just scroll to the end
  598. // also set cursor_pos too
  599. let Some(rect) = self.get_cached_world_rect().await else { return };
  600. let cpos = self.find_closest_glyph_idx(mouse_x, &rect);
  601. self.cursor_pos.set(cpos);
  602. self.selected.set_u32(1, cpos).unwrap();
  603. self.apply_cursor_scrolling();
  604. self.redraw().await;
  605. }
  606. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_x: f32, touch_y: f32) {
  607. // Ignore multi-touch
  608. if id != 0 {
  609. return
  610. }
  611. // Simulate mouse events
  612. match phase {
  613. TouchPhase::Started => {
  614. self.handle_mouse_btn_down(MouseButton::Left, touch_x, touch_y).await
  615. }
  616. TouchPhase::Moved => self.handle_mouse_move(touch_x, touch_y).await,
  617. TouchPhase::Ended => self.handle_mouse_btn_up(MouseButton::Left, touch_x, touch_y),
  618. TouchPhase::Cancelled => {}
  619. }
  620. }
  621. /// Used when clicking the text. Given the x coord of the mouse, it finds the index
  622. /// of the closest glyph to that x coord.
  623. fn find_closest_glyph_idx(&self, x: f32, rect: &Rectangle) -> u32 {
  624. let font_size = self.font_size.get();
  625. let baseline = self.baseline.get();
  626. let glyphs = self.glyphs.lock().unwrap().clone();
  627. let mouse_x = x - rect.x;
  628. if mouse_x > rect.w {
  629. // Highlight to the end
  630. let cpos = glyphs.len() as u32;
  631. return cpos;
  632. // Scroll to the right handled in render
  633. } else if mouse_x < 0. {
  634. return 0;
  635. }
  636. let scroll = self.scroll.get();
  637. let mut cpos = 0;
  638. let lhs = 0.;
  639. let mut last_d = (lhs - mouse_x).abs();
  640. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  641. let mut rhs = 0.;
  642. for (i, glyph_rect) in glyph_pos_iter.skip(1).enumerate() {
  643. // Because we skip the first item
  644. let glyph_idx = (i + 1) as u32;
  645. let x1 = glyph_rect.x + scroll;
  646. // I don't know what this is doing but it works so I won't touch it for now.
  647. let curr_d = (x1 - mouse_x).abs();
  648. if curr_d < last_d {
  649. last_d = curr_d;
  650. cpos = glyph_idx;
  651. }
  652. rhs = glyph_rect.rhs();
  653. }
  654. // also check the right hand side
  655. let curr_d = (rhs - mouse_x).abs();
  656. if curr_d < last_d {
  657. //last_d = curr_d;
  658. cpos = glyphs.len() as u32;
  659. }
  660. cpos
  661. }
  662. async fn insert_char(&self, key: char) {
  663. if !self.selected.is_null(0).unwrap() {
  664. self.delete_highlighted();
  665. self.regen_glyphs().await;
  666. };
  667. let mut text = String::new();
  668. let cursor_pos = self.cursor_pos.get();
  669. let glyphs = self.glyphs.lock().unwrap().clone();
  670. // We rebuild the string but insert our substr at cursor_pos.
  671. // The substr is inserted before cursor_pos, and appending to the end
  672. // of the string is when cursor_pos = len(str).
  673. // We can't use String::insert() because sometimes multiple chars are combined
  674. // into a single glyph. We treat the cursor pos as acting on the substrs
  675. // themselves.
  676. for (i, glyph) in glyphs.iter().enumerate() {
  677. if cursor_pos == i as u32 {
  678. text.push(key);
  679. }
  680. text.push_str(&glyph.substr);
  681. }
  682. // Append to the end
  683. if cursor_pos == glyphs.len() as u32 {
  684. text.push(key);
  685. }
  686. self.text.set(text);
  687. // Not always true lol
  688. // If glyphs are recombined, this could get messed up
  689. // meh lets pretend it doesn't exist for now.
  690. self.cursor_pos.set(cursor_pos + 1);
  691. self.regen_glyphs().await;
  692. self.apply_cursor_scrolling();
  693. self.redraw().await;
  694. }
  695. async fn handle_shortcut(&self, key: char, mods: &KeyMods) {
  696. debug!(target: "ui::editbox", "handle_shortcut({:?}, {:?})", key, mods);
  697. match key {
  698. 'c' => {
  699. if mods.ctrl {
  700. self.copy_highlighted().unwrap();
  701. }
  702. }
  703. 'v' => {
  704. if mods.ctrl {
  705. if let Some(text) = window::clipboard_get() {
  706. self.paste_text(text).await;
  707. }
  708. }
  709. }
  710. _ => {}
  711. }
  712. }
  713. async fn handle_key(&self, key: &KeyCode, mods: &KeyMods) {
  714. debug!(target: "ui::editbox", "handle_key({:?}, {:?})", key, mods);
  715. match key {
  716. KeyCode::Left => {
  717. let mut cursor_pos = self.cursor_pos.get();
  718. // Start selection if shift is held
  719. if !mods.shift {
  720. self.selected.set_null(0).unwrap();
  721. self.selected.set_null(1).unwrap();
  722. } else if self.selected.is_null(0).unwrap() {
  723. assert!(self.selected.is_null(1).unwrap());
  724. self.selected.set_u32(0, cursor_pos).unwrap();
  725. }
  726. if cursor_pos > 0 {
  727. cursor_pos -= 1;
  728. debug!(target: "ui::editbox", "Left cursor_pos={}", cursor_pos);
  729. self.cursor_pos.set(cursor_pos);
  730. }
  731. // Update selection
  732. if mods.shift {
  733. self.selected.set_u32(1, cursor_pos).unwrap();
  734. }
  735. self.apply_cursor_scrolling();
  736. self.redraw().await;
  737. }
  738. KeyCode::Right => {
  739. let mut cursor_pos = self.cursor_pos.get();
  740. // Start selection if shift is held
  741. if !mods.shift {
  742. self.selected.set_null(0).unwrap();
  743. self.selected.set_null(1).unwrap();
  744. } else if self.selected.is_null(0).unwrap() {
  745. assert!(self.selected.is_null(1).unwrap());
  746. self.selected.set_u32(0, cursor_pos).unwrap();
  747. }
  748. let glyphs_len = self.glyphs.lock().unwrap().len() as u32;
  749. if cursor_pos < glyphs_len {
  750. cursor_pos += 1;
  751. debug!(target: "ui::editbox", "Right cursor_pos={}", cursor_pos);
  752. self.cursor_pos.set(cursor_pos);
  753. }
  754. // Update selection
  755. if mods.shift {
  756. self.selected.set_u32(1, cursor_pos).unwrap();
  757. }
  758. self.apply_cursor_scrolling();
  759. self.redraw().await;
  760. }
  761. //KeyCode::Up,
  762. //KeyCode::Down,
  763. //KeyCode::Enter,
  764. KeyCode::Kp0 => self.insert_char('0').await,
  765. KeyCode::Kp1 => self.insert_char('1').await,
  766. KeyCode::Kp2 => self.insert_char('2').await,
  767. KeyCode::Kp3 => self.insert_char('3').await,
  768. KeyCode::Kp4 => self.insert_char('4').await,
  769. KeyCode::Kp5 => self.insert_char('5').await,
  770. KeyCode::Kp6 => self.insert_char('6').await,
  771. KeyCode::Kp7 => self.insert_char('7').await,
  772. KeyCode::Kp8 => self.insert_char('8').await,
  773. KeyCode::Kp9 => self.insert_char('9').await,
  774. KeyCode::KpDecimal => self.insert_char('.').await,
  775. KeyCode::Enter | KeyCode::KpEnter => self.send_event().await,
  776. KeyCode::Delete => {
  777. if !self.selected.is_null(0).unwrap() {
  778. self.delete_highlighted();
  779. } else {
  780. let glyphs = self.glyphs.lock().unwrap().clone();
  781. let cursor_pos = self.cursor_pos.get();
  782. if cursor_pos == glyphs.len() as u32 {
  783. return;
  784. }
  785. // Regen text
  786. let mut text = String::new();
  787. for (i, glyph) in glyphs.iter().enumerate() {
  788. let mut substr = glyph.substr.clone();
  789. if cursor_pos as usize == i {
  790. // Lmk if anyone knows a better way to do substr.pop_front()
  791. let mut chars = substr.chars();
  792. chars.next();
  793. substr = chars.as_str().to_string();
  794. }
  795. text.push_str(&substr);
  796. }
  797. self.text.set(text);
  798. };
  799. self.regen_glyphs().await;
  800. self.apply_cursor_scrolling();
  801. self.redraw().await;
  802. }
  803. KeyCode::Backspace => {
  804. if !self.selected.is_null(0).unwrap() {
  805. self.delete_highlighted();
  806. } else {
  807. let glyphs = self.glyphs.lock().unwrap().clone();
  808. let cursor_pos = self.cursor_pos.get();
  809. if cursor_pos == 0 {
  810. return;
  811. }
  812. let mut text = String::new();
  813. for (i, glyph) in glyphs.iter().enumerate() {
  814. let mut substr = glyph.substr.clone();
  815. if cursor_pos as usize - 1 == i {
  816. substr.pop().unwrap();
  817. }
  818. text.push_str(&substr);
  819. }
  820. self.text.set(text);
  821. self.cursor_pos.set(cursor_pos - 1);
  822. };
  823. self.regen_glyphs().await;
  824. self.apply_cursor_scrolling();
  825. self.redraw().await;
  826. }
  827. KeyCode::Home => {
  828. let cursor_pos = self.cursor_pos.get();
  829. if !mods.shift {
  830. self.selected.set_null(0).unwrap();
  831. self.selected.set_null(1).unwrap();
  832. } else if self.selected.is_null(0).unwrap() {
  833. assert!(self.selected.is_null(1).unwrap());
  834. self.selected.set_u32(0, cursor_pos).unwrap();
  835. }
  836. self.cursor_pos.set(0);
  837. // Update selection
  838. if mods.shift {
  839. self.selected.set_u32(1, cursor_pos).unwrap();
  840. }
  841. self.apply_cursor_scrolling();
  842. self.redraw().await;
  843. }
  844. KeyCode::End => {
  845. let cursor_pos = self.cursor_pos.get();
  846. if !mods.shift {
  847. self.selected.set_null(0).unwrap();
  848. self.selected.set_null(1).unwrap();
  849. } else if self.selected.is_null(0).unwrap() {
  850. assert!(self.selected.is_null(1).unwrap());
  851. self.selected.set_u32(0, cursor_pos).unwrap();
  852. }
  853. let glyphs_len = self.glyphs.lock().unwrap().len();
  854. self.cursor_pos.set(glyphs_len as u32);
  855. // Update selection
  856. if mods.shift {
  857. self.selected.set_u32(1, cursor_pos).unwrap();
  858. }
  859. self.apply_cursor_scrolling();
  860. self.redraw().await;
  861. }
  862. _ => {}
  863. }
  864. }
  865. fn delete_highlighted(&self) {
  866. assert!(!self.selected.is_null(0).unwrap());
  867. assert!(!self.selected.is_null(1).unwrap());
  868. let start = self.selected.get_u32(0).unwrap() as usize;
  869. let end = self.selected.get_u32(1).unwrap() as usize;
  870. let sel_start = std::cmp::min(start, end);
  871. let sel_end = std::cmp::max(start, end);
  872. let mut text = String::new();
  873. let glyphs = self.glyphs.lock().unwrap().clone();
  874. // Regen text
  875. for (i, glyph) in glyphs.iter().enumerate() {
  876. if sel_start <= i && i < sel_end {
  877. continue
  878. }
  879. text.push_str(&glyph.substr);
  880. }
  881. debug!(
  882. target: "ui::editbox",
  883. "delete_highlighted() text=\"{}\", cursor_pos={}",
  884. text, sel_start
  885. );
  886. self.text.set(text);
  887. self.selected.set_null(0).unwrap();
  888. self.selected.set_null(1).unwrap();
  889. self.cursor_pos.set(sel_start as u32);
  890. }
  891. fn copy_highlighted(&self) -> Result<()> {
  892. let start = self.selected.get_u32(0)? as usize;
  893. let end = self.selected.get_u32(1)? as usize;
  894. let sel_start = std::cmp::min(start, end);
  895. let sel_end = std::cmp::max(start, end);
  896. let mut text = String::new();
  897. let glyphs = self.glyphs.lock().unwrap().clone();
  898. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  899. if sel_start <= glyph_idx && glyph_idx < sel_end {
  900. text.push_str(&glyph.substr);
  901. }
  902. }
  903. info!(target: "ui::editbox", "Copied '{}'", text);
  904. window::clipboard_set(&text);
  905. Ok(())
  906. }
  907. async fn paste_text(&self, key: String) {
  908. let mut text = String::new();
  909. let cursor_pos = self.cursor_pos.get();
  910. if cursor_pos == 0 {
  911. text = key.clone();
  912. }
  913. let glyphs = self.glyphs.lock().unwrap().clone();
  914. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  915. text.push_str(&glyph.substr);
  916. if cursor_pos == glyph_idx as u32 + 1 {
  917. text.push_str(&key);
  918. }
  919. }
  920. self.text.set(text);
  921. // Not always true lol
  922. self.cursor_pos.set(cursor_pos + 1);
  923. self.apply_cursor_scrolling();
  924. self.redraw().await;
  925. }
  926. /// Beware of this method. Here be dragons.
  927. /// Possibly racy so we limit it just to cursor scrolling.
  928. fn cached_rect(&self) -> Rectangle {
  929. let Ok(rect) = read_rect(self.rect.clone()) else {
  930. panic!("Node bad rect property");
  931. };
  932. rect
  933. }
  934. async fn get_parent_rect(&self) -> Option<Rectangle> {
  935. let sg = self.sg.lock().await;
  936. let node = sg.get_node(self.node_id).unwrap();
  937. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  938. return None;
  939. };
  940. drop(sg);
  941. Some(parent_rect)
  942. }
  943. async fn get_cached_world_rect(&self) -> Option<Rectangle> {
  944. // NBD if it's slightly wrong
  945. let mut rect = self.cached_rect();
  946. // If layers can be nested and we use offsets for (x, y)
  947. // then this will be incorrect for nested layers.
  948. // For now we don't allow nesting of layers.
  949. let parent_rect = self.get_parent_rect().await?;
  950. // Offset rect which is now in world coords
  951. rect.x += parent_rect.x;
  952. rect.y += parent_rect.y;
  953. Some(rect)
  954. }
  955. /// Whenever the cursor property is modified this MUST be called
  956. /// to recalculate the scroll x property.
  957. fn apply_cursor_scrolling(&self) {
  958. // This may need updating but yolo rite
  959. let rect = self.cached_rect();
  960. let cursor_pos = self.cursor_pos.get() as usize;
  961. let mut scroll = self.scroll.get();
  962. let cursor_x = {
  963. let font_size = self.font_size.get();
  964. let baseline = self.baseline.get();
  965. let glyphs = self.glyphs.lock().unwrap().clone();
  966. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  967. if cursor_pos == 0 {
  968. 0.
  969. } else if cursor_pos == glyphs.len() {
  970. let glyph_pos = glyph_pos_iter.last().unwrap();
  971. glyph_pos.rhs()
  972. } else {
  973. assert!(cursor_pos < glyphs.len());
  974. let glyph_pos = glyph_pos_iter.nth(cursor_pos).expect("glyph pos mismatch glyphs");
  975. glyph_pos.x
  976. }
  977. };
  978. let cursor_lhs = cursor_x + scroll;
  979. let cursor_rhs = cursor_lhs + CURSOR_WIDTH;
  980. if cursor_rhs > rect.w {
  981. scroll = rect.w - cursor_x;
  982. } else if cursor_lhs < 0. {
  983. scroll = -cursor_x + CURSOR_WIDTH;
  984. }
  985. self.scroll.set(scroll);
  986. }
  987. async fn redraw(&self) {
  988. // draw will recalc this when it's None
  989. let old = std::mem::replace(&mut *self.render_info.lock().unwrap(), None);
  990. let sg = self.sg.lock().await;
  991. let node = sg.get_node(self.node_id).unwrap();
  992. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  993. return;
  994. };
  995. let Some(draw_update) = self.draw(&sg, &parent_rect).await else {
  996. error!(target: "ui::editbox", "Text {:?} failed to draw", node);
  997. return;
  998. };
  999. self.render_api.replace_draw_calls(draw_update.draw_calls).await;
  1000. debug!(target: "ui::editbox", "replace draw calls done");
  1001. // We're finished with these so clean up.
  1002. if let Some(old) = old {
  1003. self.render_api.delete_buffer(old.mesh.vertex_buffer);
  1004. self.render_api.delete_buffer(old.mesh.index_buffer);
  1005. self.render_api.delete_texture(old.texture_id);
  1006. }
  1007. }
  1008. pub async fn draw(&self, sg: &SceneGraph, parent_rect: &Rectangle) -> Option<DrawUpdate> {
  1009. debug!(target: "ui::editbox", "EditBox::draw()");
  1010. // Only used for debug messages
  1011. let node = sg.get_node(self.node_id).unwrap();
  1012. if let Err(err) = eval_rect(self.rect.clone(), parent_rect) {
  1013. panic!("Node {:?} bad rect property: {}", node, err);
  1014. }
  1015. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  1016. panic!("Node {:?} bad rect property", node);
  1017. };
  1018. rect.x += parent_rect.x;
  1019. rect.y += parent_rect.y;
  1020. let render_info = self.render_info.lock().unwrap().clone();
  1021. let render_info = match render_info {
  1022. Some(render_info) => render_info,
  1023. None => {
  1024. let render_info = self.regen_mesh(rect.clone()).await;
  1025. *self.render_info.lock().unwrap() = Some(render_info.clone());
  1026. render_info
  1027. }
  1028. };
  1029. let mesh = DrawMesh {
  1030. vertex_buffer: render_info.mesh.vertex_buffer,
  1031. index_buffer: render_info.mesh.index_buffer,
  1032. texture: Some(render_info.texture_id),
  1033. num_elements: render_info.mesh.num_elements,
  1034. };
  1035. let off_x = rect.x / parent_rect.w;
  1036. let off_y = rect.y / parent_rect.h;
  1037. let scale_x = 1. / parent_rect.w;
  1038. let scale_y = 1. / parent_rect.h;
  1039. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  1040. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  1041. Some(DrawUpdate {
  1042. key: self.dc_key,
  1043. draw_calls: vec![(
  1044. self.dc_key,
  1045. DrawCall {
  1046. instrs: vec![DrawInstruction::ApplyMatrix(model), DrawInstruction::Draw(mesh)],
  1047. dcs: vec![],
  1048. z_index: self.z_index.get(),
  1049. },
  1050. )],
  1051. })
  1052. }
  1053. async fn send_event(&self) {
  1054. let text = self.text.get();
  1055. debug!(target: "ui::editbox", "sending text {}", text);
  1056. // This should probably be unset instead
  1057. self.text.set(String::new());
  1058. self.cursor_pos.set(0);
  1059. self.redraw().await;
  1060. }
  1061. }
  1062. impl Stoppable for EditBox {
  1063. async fn stop(&self) {
  1064. // TODO: Delete own draw call
  1065. // Free buffers
  1066. // Should this be in drop?
  1067. //self.render_api.delete_buffer(self.vertex_buffer);
  1068. //self.render_api.delete_buffer(self.index_buffer);
  1069. }
  1070. }
  1071. /// Filter these char events from being handled since we handle them
  1072. /// using the key_up/key_down events.
  1073. /// Avoids duplicate processing of keyboard input events.
  1074. static DISALLOWED_CHARS: &'static [char] = &['\r', '\u{8}', '\u{7f}', '\t', '\n'];
  1075. /// These keycodes are handled via normal key_up/key_down events.
  1076. /// Anything in this list must be disallowed char events.
  1077. static ALLOWED_KEYCODES: &'static [KeyCode] = &[
  1078. KeyCode::Left,
  1079. KeyCode::Right,
  1080. KeyCode::Up,
  1081. KeyCode::Down,
  1082. KeyCode::Enter,
  1083. KeyCode::Kp0,
  1084. KeyCode::Kp1,
  1085. KeyCode::Kp2,
  1086. KeyCode::Kp3,
  1087. KeyCode::Kp4,
  1088. KeyCode::Kp5,
  1089. KeyCode::Kp6,
  1090. KeyCode::Kp7,
  1091. KeyCode::Kp8,
  1092. KeyCode::Kp9,
  1093. KeyCode::KpDecimal,
  1094. KeyCode::KpEnter,
  1095. KeyCode::Delete,
  1096. KeyCode::Backspace,
  1097. KeyCode::Home,
  1098. KeyCode::End,
  1099. ];