editbox.rs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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, 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, &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, (mut glyph_rect, glyph)) in glyph_pos_iter.zip(glyphs.iter()).enumerate() {
  328. let uv_rect = atlas.fetch_uv(glyph.glyph_id).expect("missing glyph UV rect");
  329. glyph_rect.x += scroll;
  330. //mesh.draw_outline(&glyph_rect, COLOR_BLUE, 2.);
  331. let mut color = text_color.clone();
  332. if glyph.sprite.has_color {
  333. color = COLOR_WHITE;
  334. }
  335. mesh.draw_box(&glyph_rect, color, uv_rect);
  336. if is_focused && cursor_pos != 0 && cursor_pos == glyph_idx {
  337. let cursor_rect =
  338. Rectangle { x: glyph_rect.x - CURSOR_WIDTH, y: 0., w: CURSOR_WIDTH, h: clip.h };
  339. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  340. }
  341. rhs = glyph_rect.rhs();
  342. }
  343. if is_focused && cursor_pos == 0 {
  344. let cursor_rect = Rectangle { x: 0., y: 0., w: CURSOR_WIDTH, h: clip.h };
  345. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  346. } else if is_focused && cursor_pos == glyphs.len() {
  347. let cursor_rect =
  348. Rectangle { x: rhs - CURSOR_WIDTH, y: 0., w: CURSOR_WIDTH, h: clip.h };
  349. mesh.draw_box(&cursor_rect, cursor_color, &Rectangle::zero());
  350. }
  351. if debug {
  352. mesh.draw_outline(&clip, COLOR_BLUE, 1.);
  353. }
  354. let mesh = mesh.alloc(&self.render_api).await.unwrap();
  355. TextRenderInfo { mesh, texture_id: atlas.texture_id }
  356. }
  357. fn draw_selected(
  358. &self,
  359. mesh: &mut MeshBuilder,
  360. glyphs: &Vec<Glyph>,
  361. clip_h: f32,
  362. ) -> Result<()> {
  363. if self.selected.is_null(0)? || self.selected.is_null(1)? {
  364. // Nothing selected so do nothing
  365. return Ok(())
  366. }
  367. let start = self.selected.get_u32(0)? as usize;
  368. let end = self.selected.get_u32(1)? as usize;
  369. // Selection started but nothing selected yet so do nothing
  370. if start == end {
  371. return Ok(())
  372. }
  373. let sel_start = std::cmp::min(start, end);
  374. let sel_end = std::cmp::max(start, end);
  375. let font_size = self.font_size.get();
  376. let baseline = self.baseline.get();
  377. let scroll = self.scroll.get();
  378. let hi_bg_color = self.hi_bg_color.get();
  379. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  380. let mut start_x = 0.;
  381. let mut end_x = 0.;
  382. // When cursor lands at the end of the line
  383. let mut rhs = 0.;
  384. for (glyph_idx, mut glyph_rect) in glyph_pos_iter.enumerate() {
  385. glyph_rect.x += scroll;
  386. if glyph_idx == sel_start {
  387. start_x = glyph_rect.x;
  388. }
  389. if glyph_idx == sel_end {
  390. end_x = glyph_rect.x;
  391. }
  392. rhs = glyph_rect.rhs();
  393. }
  394. if sel_start == 0 {
  395. start_x = scroll;
  396. }
  397. if sel_end == glyphs.len() {
  398. end_x = rhs;
  399. }
  400. // We don't need to do manual clipping since MeshBuilder should do that
  401. let select_rect = Rectangle { x: start_x, y: 0., w: end_x - start_x, h: clip_h };
  402. mesh.draw_box(&select_rect, hi_bg_color, &Rectangle::zero());
  403. Ok(())
  404. }
  405. async fn do_key_action(&self, key: char, mods: &KeyMods) {
  406. match key {
  407. //KeyCode::Left => {}
  408. _ => self.insert_char(key).await,
  409. }
  410. }
  411. async fn process_char(me: &Weak<Self>, ev_sub: &Subscription<(char, KeyMods, bool)>) {
  412. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  413. debug!(target: "ui::editbox", "Event relayer closed");
  414. return
  415. };
  416. // First filter for only single digit keys
  417. if DISALLOWED_CHARS.contains(&key) {
  418. return
  419. }
  420. let Some(self_) = me.upgrade() else {
  421. // Should not happen
  422. panic!("self destroyed before char_task was stopped!");
  423. };
  424. if !self_.is_focused.get() {
  425. return
  426. }
  427. if mods.ctrl || mods.alt {
  428. if repeat {
  429. return
  430. }
  431. self_.handle_shortcut(key, &mods).await;
  432. return
  433. }
  434. let actions = {
  435. let mut repeater = self_.key_repeat.lock().unwrap();
  436. repeater.key_down(PressedKey::Char(key), repeat)
  437. };
  438. debug!(target: "ui::editbox", "Key {:?} has {} actions", key, actions);
  439. for _ in 0..actions {
  440. self_.insert_char(key).await;
  441. }
  442. }
  443. async fn process_key_down(me: &Weak<Self>, ev_sub: &Subscription<(KeyCode, KeyMods, bool)>) {
  444. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  445. debug!(target: "ui::editbox", "Event relayer closed");
  446. return
  447. };
  448. // First filter for only single digit keys
  449. // Avoid processing events handled by insert_char()
  450. if !ALLOWED_KEYCODES.contains(&key) {
  451. return
  452. }
  453. let Some(self_) = me.upgrade() else {
  454. // Should not happen
  455. panic!("self destroyed before char_task was stopped!");
  456. };
  457. if !self_.is_focused.get() {
  458. return
  459. }
  460. let actions = {
  461. let mut repeater = self_.key_repeat.lock().unwrap();
  462. repeater.key_down(PressedKey::Key(key), repeat)
  463. };
  464. // Suppress noisy message
  465. if actions > 0 {
  466. debug!(target: "ui::editbox", "Key {:?} has {} actions", key, actions);
  467. }
  468. for _ in 0..actions {
  469. self_.handle_key(&key, &mods).await;
  470. }
  471. }
  472. async fn process_mouse_btn_down(
  473. me: &Weak<Self>,
  474. ev_sub: &Subscription<(MouseButton, f32, f32)>,
  475. ) {
  476. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  477. debug!(target: "ui::editbox", "Event relayer closed");
  478. return
  479. };
  480. let Some(self_) = me.upgrade() else {
  481. // Should not happen
  482. panic!("self destroyed before mouse_btn_down_task was stopped!");
  483. };
  484. if !self_.is_active.get() {
  485. return
  486. }
  487. self_.handle_mouse_btn_down(btn, mouse_x, mouse_y).await;
  488. }
  489. async fn process_mouse_btn_up(me: &Weak<Self>, ev_sub: &Subscription<(MouseButton, f32, f32)>) {
  490. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  491. debug!(target: "ui::editbox", "Event relayer closed");
  492. return
  493. };
  494. let Some(self_) = me.upgrade() else {
  495. // Should not happen
  496. panic!("self destroyed before mouse_btn_up_task was stopped!");
  497. };
  498. if !self_.is_active.get() {
  499. return
  500. }
  501. self_.handle_mouse_btn_up(btn, mouse_x, mouse_y);
  502. }
  503. async fn process_mouse_move(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) {
  504. let Ok((mouse_x, mouse_y)) = ev_sub.receive().await else {
  505. debug!(target: "ui::editbox", "Event relayer closed");
  506. return
  507. };
  508. let Some(self_) = me.upgrade() else {
  509. // Should not happen
  510. panic!("self destroyed before mouse_move_task was stopped!");
  511. };
  512. if !self_.is_active.get() {
  513. return
  514. }
  515. self_.handle_mouse_move(mouse_x, mouse_y).await;
  516. }
  517. async fn process_touch(me: &Weak<Self>, ev_sub: &Subscription<(TouchPhase, u64, f32, f32)>) {
  518. let Ok((phase, id, touch_x, touch_y)) = ev_sub.receive().await else {
  519. debug!(target: "ui::editbox", "Event relayer closed");
  520. return
  521. };
  522. let Some(self_) = me.upgrade() else {
  523. // Should not happen
  524. panic!("self destroyed before touch_task was stopped!");
  525. };
  526. if !self_.is_active.get() {
  527. return
  528. }
  529. self_.handle_touch(phase, id, touch_x, touch_y).await;
  530. }
  531. async fn change_focus(self: Arc<Self>) {
  532. if !self.is_active.get() {
  533. return
  534. }
  535. debug!(target: "ui::editbox", "Focus changed");
  536. let is_focused = self.is_focused.get();
  537. // Cursor visibility will change so just redraw everything lol
  538. self.redraw().await;
  539. }
  540. async fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_x: f32, mouse_y: f32) {
  541. if btn != MouseButton::Left {
  542. return
  543. }
  544. let mouse_pos = Point::from([mouse_x, mouse_y]);
  545. let mut focus_changed = false;
  546. let Some(rect) = self.get_cached_world_rect().await else { return };
  547. // clicking inside box will:
  548. // 1. make it active
  549. // 2. begin selection
  550. if rect.contains(&mouse_pos) {
  551. window::show_keyboard(true);
  552. if self.is_focused.get() {
  553. debug!(target: "ui::editbox", "EditBox clicked");
  554. } else {
  555. debug!(target: "ui::editbox", "EditBox focused");
  556. self.is_focused.set(true);
  557. focus_changed = true;
  558. }
  559. let cpos = self.find_closest_glyph_idx(mouse_x, &rect);
  560. // set cursor pos
  561. self.cursor_pos.set(cpos);
  562. self.apply_cursor_scrolling();
  563. // begin selection
  564. self.selected.set_u32(0, cpos).unwrap();
  565. self.selected.set_u32(1, cpos).unwrap();
  566. self.mouse_btn_held.store(true, Ordering::Relaxed);
  567. // click outside the box will make it unfocused
  568. } else if self.is_focused.get() {
  569. debug!(target: "ui::editbox", "EditBox unfocused");
  570. self.is_focused.set(false);
  571. self.selected.set_null(0).unwrap();
  572. self.selected.set_null(1).unwrap();
  573. focus_changed = true;
  574. }
  575. // Further on_focus logic change is handled by property modified callback
  576. // which calls Self::change_focus()
  577. // We still need to redraw if cursor is changed though, but we want to avoid redrawing
  578. // twice, so we do this check:
  579. if !focus_changed {
  580. self.redraw().await;
  581. }
  582. }
  583. fn handle_mouse_btn_up(&self, btn: MouseButton, x: f32, y: f32) {
  584. if btn != MouseButton::Left {
  585. return
  586. }
  587. // releasing mouse button will end selection
  588. self.mouse_btn_held.store(false, Ordering::Relaxed);
  589. }
  590. async fn handle_mouse_move(&self, mouse_x: f32, mouse_y: f32) {
  591. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  592. return;
  593. }
  594. // if active and selection_active, then use x to modify the selection.
  595. // also implement scrolling when cursor is to the left or right
  596. // just scroll to the end
  597. // also set cursor_pos too
  598. let Some(rect) = self.get_cached_world_rect().await else { return };
  599. let cpos = self.find_closest_glyph_idx(mouse_x, &rect);
  600. self.cursor_pos.set(cpos);
  601. self.selected.set_u32(1, cpos).unwrap();
  602. self.apply_cursor_scrolling();
  603. self.redraw().await;
  604. }
  605. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_x: f32, touch_y: f32) {
  606. // Ignore multi-touch
  607. if id != 0 {
  608. return
  609. }
  610. // Simulate mouse events
  611. match phase {
  612. TouchPhase::Started => {
  613. self.handle_mouse_btn_down(MouseButton::Left, touch_x, touch_y).await
  614. }
  615. TouchPhase::Moved => self.handle_mouse_move(touch_x, touch_y).await,
  616. TouchPhase::Ended => self.handle_mouse_btn_up(MouseButton::Left, touch_x, touch_y),
  617. TouchPhase::Cancelled => {}
  618. }
  619. }
  620. /// Used when clicking the text. Given the x coord of the mouse, it finds the index
  621. /// of the closest glyph to that x coord.
  622. fn find_closest_glyph_idx(&self, x: f32, rect: &Rectangle) -> u32 {
  623. let font_size = self.font_size.get();
  624. let baseline = self.baseline.get();
  625. let glyphs = self.glyphs.lock().unwrap().clone();
  626. let mouse_x = x - rect.x;
  627. if mouse_x > rect.w {
  628. // Highlight to the end
  629. let cpos = glyphs.len() as u32;
  630. return cpos;
  631. // Scroll to the right handled in render
  632. } else if mouse_x < 0. {
  633. return 0;
  634. }
  635. let scroll = self.scroll.get();
  636. let mut cpos = 0;
  637. let lhs = 0.;
  638. let mut last_d = (lhs - mouse_x).abs();
  639. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  640. let mut rhs = 0.;
  641. for (i, glyph_rect) in glyph_pos_iter.skip(1).enumerate() {
  642. // Because we skip the first item
  643. let glyph_idx = (i + 1) as u32;
  644. let x1 = glyph_rect.x + scroll;
  645. // I don't know what this is doing but it works so I won't touch it for now.
  646. let curr_d = (x1 - mouse_x).abs();
  647. if curr_d < last_d {
  648. last_d = curr_d;
  649. cpos = glyph_idx;
  650. }
  651. rhs = glyph_rect.rhs();
  652. }
  653. // also check the right hand side
  654. let curr_d = (rhs - mouse_x).abs();
  655. if curr_d < last_d {
  656. //last_d = curr_d;
  657. cpos = glyphs.len() as u32;
  658. }
  659. cpos
  660. }
  661. async fn insert_char(&self, key: char) {
  662. if !self.selected.is_null(0).unwrap() {
  663. self.delete_highlighted();
  664. self.regen_glyphs().await;
  665. };
  666. let mut text = String::new();
  667. let cursor_pos = self.cursor_pos.get();
  668. let glyphs = self.glyphs.lock().unwrap().clone();
  669. // We rebuild the string but insert our substr at cursor_pos.
  670. // The substr is inserted before cursor_pos, and appending to the end
  671. // of the string is when cursor_pos = len(str).
  672. // We can't use String::insert() because sometimes multiple chars are combined
  673. // into a single glyph. We treat the cursor pos as acting on the substrs
  674. // themselves.
  675. for (i, glyph) in glyphs.iter().enumerate() {
  676. if cursor_pos == i as u32 {
  677. text.push(key);
  678. }
  679. text.push_str(&glyph.substr);
  680. }
  681. // Append to the end
  682. if cursor_pos == glyphs.len() as u32 {
  683. text.push(key);
  684. }
  685. self.text.set(text);
  686. // Not always true lol
  687. // If glyphs are recombined, this could get messed up
  688. // meh lets pretend it doesn't exist for now.
  689. self.cursor_pos.set(cursor_pos + 1);
  690. self.regen_glyphs().await;
  691. self.apply_cursor_scrolling();
  692. self.redraw().await;
  693. }
  694. async fn handle_shortcut(&self, key: char, mods: &KeyMods) {
  695. debug!(target: "ui::editbox", "handle_shortcut({:?}, {:?})", key, mods);
  696. match key {
  697. 'c' => {
  698. if mods.ctrl {
  699. self.copy_highlighted().unwrap();
  700. }
  701. }
  702. 'v' => {
  703. if mods.ctrl {
  704. if let Some(text) = window::clipboard_get() {
  705. self.paste_text(text).await;
  706. }
  707. }
  708. }
  709. _ => {}
  710. }
  711. }
  712. async fn handle_key(&self, key: &KeyCode, mods: &KeyMods) {
  713. debug!(target: "ui::editbox", "handle_key({:?}, {:?})", key, mods);
  714. match key {
  715. KeyCode::Left => {
  716. let mut cursor_pos = self.cursor_pos.get();
  717. // Start selection if shift is held
  718. if !mods.shift {
  719. self.selected.set_null(0).unwrap();
  720. self.selected.set_null(1).unwrap();
  721. } else if self.selected.is_null(0).unwrap() {
  722. assert!(self.selected.is_null(1).unwrap());
  723. self.selected.set_u32(0, cursor_pos).unwrap();
  724. }
  725. if cursor_pos > 0 {
  726. cursor_pos -= 1;
  727. debug!(target: "ui::editbox", "Left cursor_pos={}", cursor_pos);
  728. self.cursor_pos.set(cursor_pos);
  729. }
  730. // Update selection
  731. if mods.shift {
  732. self.selected.set_u32(1, cursor_pos).unwrap();
  733. }
  734. self.apply_cursor_scrolling();
  735. self.redraw().await;
  736. }
  737. KeyCode::Right => {
  738. let mut cursor_pos = self.cursor_pos.get();
  739. // Start selection if shift is held
  740. if !mods.shift {
  741. self.selected.set_null(0).unwrap();
  742. self.selected.set_null(1).unwrap();
  743. } else if self.selected.is_null(0).unwrap() {
  744. assert!(self.selected.is_null(1).unwrap());
  745. self.selected.set_u32(0, cursor_pos).unwrap();
  746. }
  747. let glyphs_len = self.glyphs.lock().unwrap().len() as u32;
  748. if cursor_pos < glyphs_len {
  749. cursor_pos += 1;
  750. debug!(target: "ui::editbox", "Right cursor_pos={}", cursor_pos);
  751. self.cursor_pos.set(cursor_pos);
  752. }
  753. // Update selection
  754. if mods.shift {
  755. self.selected.set_u32(1, cursor_pos).unwrap();
  756. }
  757. self.apply_cursor_scrolling();
  758. self.redraw().await;
  759. }
  760. //KeyCode::Up,
  761. //KeyCode::Down,
  762. //KeyCode::Enter,
  763. KeyCode::Kp0 => self.insert_char('0').await,
  764. KeyCode::Kp1 => self.insert_char('1').await,
  765. KeyCode::Kp2 => self.insert_char('2').await,
  766. KeyCode::Kp3 => self.insert_char('3').await,
  767. KeyCode::Kp4 => self.insert_char('4').await,
  768. KeyCode::Kp5 => self.insert_char('5').await,
  769. KeyCode::Kp6 => self.insert_char('6').await,
  770. KeyCode::Kp7 => self.insert_char('7').await,
  771. KeyCode::Kp8 => self.insert_char('8').await,
  772. KeyCode::Kp9 => self.insert_char('9').await,
  773. KeyCode::KpDecimal => self.insert_char('.').await,
  774. KeyCode::Enter | KeyCode::KpEnter => self.send_event().await,
  775. KeyCode::Delete => {
  776. if !self.selected.is_null(0).unwrap() {
  777. self.delete_highlighted();
  778. } else {
  779. let glyphs = self.glyphs.lock().unwrap().clone();
  780. let cursor_pos = self.cursor_pos.get();
  781. if cursor_pos == glyphs.len() as u32 {
  782. return;
  783. }
  784. // Regen text
  785. let mut text = String::new();
  786. for (i, glyph) in glyphs.iter().enumerate() {
  787. let mut substr = glyph.substr.clone();
  788. if cursor_pos as usize == i {
  789. // Lmk if anyone knows a better way to do substr.pop_front()
  790. let mut chars = substr.chars();
  791. chars.next();
  792. substr = chars.as_str().to_string();
  793. }
  794. text.push_str(&substr);
  795. }
  796. self.text.set(text);
  797. };
  798. self.regen_glyphs().await;
  799. self.apply_cursor_scrolling();
  800. self.redraw().await;
  801. }
  802. KeyCode::Backspace => {
  803. if !self.selected.is_null(0).unwrap() {
  804. self.delete_highlighted();
  805. } else {
  806. let glyphs = self.glyphs.lock().unwrap().clone();
  807. let cursor_pos = self.cursor_pos.get();
  808. if cursor_pos == 0 {
  809. return;
  810. }
  811. let mut text = String::new();
  812. for (i, glyph) in glyphs.iter().enumerate() {
  813. let mut substr = glyph.substr.clone();
  814. if cursor_pos as usize - 1 == i {
  815. substr.pop().unwrap();
  816. }
  817. text.push_str(&substr);
  818. }
  819. self.text.set(text);
  820. self.cursor_pos.set(cursor_pos - 1);
  821. };
  822. self.regen_glyphs().await;
  823. self.apply_cursor_scrolling();
  824. self.redraw().await;
  825. }
  826. KeyCode::Home => {
  827. let cursor_pos = self.cursor_pos.get();
  828. if !mods.shift {
  829. self.selected.set_null(0).unwrap();
  830. self.selected.set_null(1).unwrap();
  831. } else if self.selected.is_null(0).unwrap() {
  832. assert!(self.selected.is_null(1).unwrap());
  833. self.selected.set_u32(0, cursor_pos).unwrap();
  834. }
  835. self.cursor_pos.set(0);
  836. // Update selection
  837. if mods.shift {
  838. self.selected.set_u32(1, cursor_pos).unwrap();
  839. }
  840. self.apply_cursor_scrolling();
  841. self.redraw().await;
  842. }
  843. KeyCode::End => {
  844. let cursor_pos = self.cursor_pos.get();
  845. if !mods.shift {
  846. self.selected.set_null(0).unwrap();
  847. self.selected.set_null(1).unwrap();
  848. } else if self.selected.is_null(0).unwrap() {
  849. assert!(self.selected.is_null(1).unwrap());
  850. self.selected.set_u32(0, cursor_pos).unwrap();
  851. }
  852. let glyphs_len = self.glyphs.lock().unwrap().len();
  853. self.cursor_pos.set(glyphs_len as u32);
  854. // Update selection
  855. if mods.shift {
  856. self.selected.set_u32(1, cursor_pos).unwrap();
  857. }
  858. self.apply_cursor_scrolling();
  859. self.redraw().await;
  860. }
  861. _ => {}
  862. }
  863. }
  864. fn delete_highlighted(&self) {
  865. assert!(!self.selected.is_null(0).unwrap());
  866. assert!(!self.selected.is_null(1).unwrap());
  867. let start = self.selected.get_u32(0).unwrap() as usize;
  868. let end = self.selected.get_u32(1).unwrap() as usize;
  869. let sel_start = std::cmp::min(start, end);
  870. let sel_end = std::cmp::max(start, end);
  871. let mut text = String::new();
  872. let glyphs = self.glyphs.lock().unwrap().clone();
  873. // Regen text
  874. for (i, glyph) in glyphs.iter().enumerate() {
  875. if sel_start <= i && i < sel_end {
  876. continue
  877. }
  878. text.push_str(&glyph.substr);
  879. }
  880. debug!(
  881. target: "ui::editbox",
  882. "delete_highlighted() text=\"{}\", cursor_pos={}",
  883. text, sel_start
  884. );
  885. self.text.set(text);
  886. self.selected.set_null(0).unwrap();
  887. self.selected.set_null(1).unwrap();
  888. self.cursor_pos.set(sel_start as u32);
  889. }
  890. fn copy_highlighted(&self) -> Result<()> {
  891. let start = self.selected.get_u32(0)? as usize;
  892. let end = self.selected.get_u32(1)? as usize;
  893. let sel_start = std::cmp::min(start, end);
  894. let sel_end = std::cmp::max(start, end);
  895. let mut text = String::new();
  896. let glyphs = self.glyphs.lock().unwrap().clone();
  897. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  898. if sel_start <= glyph_idx && glyph_idx < sel_end {
  899. text.push_str(&glyph.substr);
  900. }
  901. }
  902. info!(target: "ui::editbox", "Copied '{}'", text);
  903. window::clipboard_set(&text);
  904. Ok(())
  905. }
  906. async fn paste_text(&self, key: String) {
  907. let mut text = String::new();
  908. let cursor_pos = self.cursor_pos.get();
  909. if cursor_pos == 0 {
  910. text = key.clone();
  911. }
  912. let glyphs = self.glyphs.lock().unwrap().clone();
  913. for (glyph_idx, glyph) in glyphs.iter().enumerate() {
  914. text.push_str(&glyph.substr);
  915. if cursor_pos == glyph_idx as u32 + 1 {
  916. text.push_str(&key);
  917. }
  918. }
  919. self.text.set(text);
  920. // Not always true lol
  921. self.cursor_pos.set(cursor_pos + 1);
  922. self.apply_cursor_scrolling();
  923. self.redraw().await;
  924. }
  925. /// Beware of this method. Here be dragons.
  926. /// Possibly racy so we limit it just to cursor scrolling.
  927. fn cached_rect(&self) -> Rectangle {
  928. let Ok(rect) = read_rect(self.rect.clone()) else {
  929. panic!("Node bad rect property");
  930. };
  931. rect
  932. }
  933. async fn get_parent_rect(&self) -> Option<Rectangle> {
  934. let sg = self.sg.lock().await;
  935. let node = sg.get_node(self.node_id).unwrap();
  936. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  937. return None;
  938. };
  939. drop(sg);
  940. Some(parent_rect)
  941. }
  942. async fn get_cached_world_rect(&self) -> Option<Rectangle> {
  943. // NBD if it's slightly wrong
  944. let mut rect = self.cached_rect();
  945. // If layers can be nested and we use offsets for (x, y)
  946. // then this will be incorrect for nested layers.
  947. // For now we don't allow nesting of layers.
  948. let parent_rect = self.get_parent_rect().await?;
  949. // Offset rect which is now in world coords
  950. rect.x += parent_rect.x;
  951. rect.y += parent_rect.y;
  952. Some(rect)
  953. }
  954. /// Whenever the cursor property is modified this MUST be called
  955. /// to recalculate the scroll x property.
  956. fn apply_cursor_scrolling(&self) {
  957. // This may need updating but yolo rite
  958. let rect = self.cached_rect();
  959. let cursor_pos = self.cursor_pos.get() as usize;
  960. let mut scroll = self.scroll.get();
  961. let cursor_x = {
  962. let font_size = self.font_size.get();
  963. let baseline = self.baseline.get();
  964. let glyphs = self.glyphs.lock().unwrap().clone();
  965. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &glyphs, baseline);
  966. if cursor_pos == 0 {
  967. 0.
  968. } else if cursor_pos == glyphs.len() {
  969. let glyph_pos = glyph_pos_iter.last().unwrap();
  970. glyph_pos.rhs()
  971. } else {
  972. assert!(cursor_pos < glyphs.len());
  973. let glyph_pos = glyph_pos_iter.nth(cursor_pos).expect("glyph pos mismatch glyphs");
  974. glyph_pos.x
  975. }
  976. };
  977. let cursor_lhs = cursor_x + scroll;
  978. let cursor_rhs = cursor_lhs + CURSOR_WIDTH;
  979. if cursor_rhs > rect.w {
  980. scroll = rect.w - cursor_x;
  981. } else if cursor_lhs < 0. {
  982. scroll = -cursor_x + CURSOR_WIDTH;
  983. }
  984. self.scroll.set(scroll);
  985. }
  986. async fn redraw(&self) {
  987. let sg = self.sg.lock().await;
  988. let node = sg.get_node(self.node_id).unwrap();
  989. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  990. return;
  991. };
  992. let Some(draw_update) = self.draw(&sg, &parent_rect).await else {
  993. error!(target: "ui::editbox", "Text {:?} failed to draw", node);
  994. return;
  995. };
  996. self.render_api.replace_draw_calls(draw_update.draw_calls).await;
  997. debug!(target: "ui::editbox", "replace draw calls done");
  998. for buffer_id in draw_update.freed_buffers {
  999. self.render_api.delete_buffer(buffer_id);
  1000. }
  1001. for texture_id in draw_update.freed_textures {
  1002. self.render_api.delete_texture(texture_id);
  1003. }
  1004. }
  1005. pub async fn draw(&self, sg: &SceneGraph, parent_rect: &Rectangle) -> Option<DrawUpdate> {
  1006. debug!(target: "ui::editbox", "EditBox::draw()");
  1007. // Only used for debug messages
  1008. let node = sg.get_node(self.node_id).unwrap();
  1009. if let Err(err) = eval_rect(self.rect.clone(), parent_rect) {
  1010. panic!("Node {:?} bad rect property: {}", node, err);
  1011. }
  1012. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  1013. panic!("Node {:?} bad rect property", node);
  1014. };
  1015. // draw will recalc this when it's None
  1016. let render_info = self.regen_mesh(rect.clone()).await;
  1017. let old_render_info =
  1018. std::mem::replace(&mut *self.render_info.lock().unwrap(), Some(render_info.clone()));
  1019. // We're finished with these so clean up.
  1020. let mut freed_textures = vec![];
  1021. let mut freed_buffers = vec![];
  1022. if let Some(old) = old_render_info {
  1023. freed_textures.push(old.texture_id);
  1024. freed_buffers.push(old.mesh.vertex_buffer);
  1025. freed_buffers.push(old.mesh.index_buffer);
  1026. }
  1027. let mesh = DrawMesh {
  1028. vertex_buffer: render_info.mesh.vertex_buffer,
  1029. index_buffer: render_info.mesh.index_buffer,
  1030. texture: Some(render_info.texture_id),
  1031. num_elements: render_info.mesh.num_elements,
  1032. };
  1033. let off_x = rect.x / parent_rect.w;
  1034. let off_y = rect.y / parent_rect.h;
  1035. let scale_x = 1. / parent_rect.w;
  1036. let scale_y = 1. / parent_rect.h;
  1037. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  1038. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  1039. Some(DrawUpdate {
  1040. key: self.dc_key,
  1041. draw_calls: vec![(
  1042. self.dc_key,
  1043. DrawCall {
  1044. instrs: vec![DrawInstruction::ApplyMatrix(model), DrawInstruction::Draw(mesh)],
  1045. dcs: vec![],
  1046. z_index: self.z_index.get(),
  1047. },
  1048. )],
  1049. freed_textures,
  1050. freed_buffers,
  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 Drop for EditBox {
  1063. fn drop(&mut self) {
  1064. let render_info = std::mem::replace(&mut *self.render_info.lock().unwrap(), None);
  1065. // We're finished with these so clean up.
  1066. if let Some(old) = render_info {
  1067. self.render_api.delete_buffer(old.mesh.vertex_buffer);
  1068. self.render_api.delete_buffer(old.mesh.index_buffer);
  1069. self.render_api.delete_texture(old.texture_id);
  1070. }
  1071. }
  1072. }
  1073. impl Stoppable for EditBox {
  1074. async fn stop(&self) {
  1075. // TODO: Delete own draw call
  1076. // Free buffers
  1077. // Should this be in drop?
  1078. //self.render_api.delete_buffer(self.vertex_buffer);
  1079. //self.render_api.delete_buffer(self.index_buffer);
  1080. }
  1081. }
  1082. /// Filter these char events from being handled since we handle them
  1083. /// using the key_up/key_down events.
  1084. /// Avoids duplicate processing of keyboard input events.
  1085. static DISALLOWED_CHARS: &'static [char] = &['\r', '\u{8}', '\u{7f}', '\t', '\n'];
  1086. /// These keycodes are handled via normal key_up/key_down events.
  1087. /// Anything in this list must be disallowed char events.
  1088. static ALLOWED_KEYCODES: &'static [KeyCode] = &[
  1089. KeyCode::Left,
  1090. KeyCode::Right,
  1091. KeyCode::Up,
  1092. KeyCode::Down,
  1093. KeyCode::Enter,
  1094. KeyCode::Kp0,
  1095. KeyCode::Kp1,
  1096. KeyCode::Kp2,
  1097. KeyCode::Kp3,
  1098. KeyCode::Kp4,
  1099. KeyCode::Kp5,
  1100. KeyCode::Kp6,
  1101. KeyCode::Kp7,
  1102. KeyCode::Kp8,
  1103. KeyCode::Kp9,
  1104. KeyCode::KpDecimal,
  1105. KeyCode::KpEnter,
  1106. KeyCode::Delete,
  1107. KeyCode::Backspace,
  1108. KeyCode::Home,
  1109. KeyCode::End,
  1110. ];