{"repo_name": "edit", "file_name": "/edit/src/fuzzy.rs", "inference_info": {"prefix_code": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Fuzzy search algorithm based on the one used in VS Code (`/src/vs/base/common/fuzzyScorer.ts`).\n//! Other algorithms exist, such as Sublime Text's, or the one used in `fzf`,\n//! but I figured that this one is what lots of people may be familiar with.\n\nuse std::vec;\n\nuse crate::arena::{Arena, scratch_arena};\nuse crate::icu;\n\nconst NO_MATCH: i32 = 0;\n\npub fn score_fuzzy<'a>(\n arena: &'a Arena,\n haystack: &str,\n needle: &str,\n allow_non_contiguous_matches: bool,\n) -> (i32, Vec) {\n if haystack.is_empty() || needle.is_empty() {\n // return early if target or query are empty\n return (NO_MATCH, Vec::new_in(arena));\n }\n\n let scratch = scratch_arena(Some(arena));\n let target = map_chars(&scratch, haystack);\n let query = map_chars(&scratch, needle);\n\n if target.len() < query.len() {\n // impossible for query to be contained in target\n return (NO_MATCH, Vec::new_in(arena));\n }\n\n let target_lower = icu::fold_case(&scratch, haystack);\n let query_lower = icu::fold_case(&scratch, needle);\n let target_lower = map_chars(&scratch, &target_lower);\n let query_lower = map_chars(&scratch, &query_lower);\n\n let area = query.len() * target.len();\n let mut scores = vec::from_elem_in(0, area, &*scratch);\n let mut matches = vec::from_elem_in(0, area, &*scratch);\n\n //\n // Build Scorer Matrix:\n //\n // The matrix is composed of query q and target t. For each index we score\n // q[i] with t[i] and compare that with the previous score. If the score is\n // equal or larger, we keep the match. In addition to the score, we also keep\n // the length of the consecutive matches to use as boost for the score.\n //\n // t a r g e t\n // q\n // u\n // e\n // r\n // y\n //\n for query_index in 0..query.len() {\n let query_index_offset = query_index * target.len();\n let query_index_previous_offset =\n if query_index > 0 { (query_index - 1) * target.len() } else { 0 };\n\n for target_index in 0..target.len() {\n let current_index = query_index_offset + target_index;\n let diag_index = if query_index > 0 && target_index > 0 {\n query_index_previous_offset + target_index - 1\n } else {\n 0\n };\n let left_score = if target_index > 0 { scores[current_index - 1] } else { 0 };\n let diag_score =\n if query_index > 0 && target_index > 0 { scores[diag_index] } else { 0 };\n let matches_sequence_len =\n if query_index > 0 && target_index > 0 { matches[diag_index] } else { 0 };\n\n // If we are not matching on the first query character anymore, we only produce a\n // score if we had a score previously for the last query index (by looking at the diagScore).\n // This makes sure that the query always matches in sequence on the target. For example\n // given a target of \"ede\" and a query of \"de\", we would otherwise produce a wrong high score\n // for query[1] (\"e\") matching on target[0] (\"e\") because of the \"beginning of word\" boost.\n let score = if diag_score == 0 && query_index != 0 {\n 0\n } else {\n compute_char_score(\n query[query_index],\n query_lower[query_index],\n if target_index != 0 { Some(target[target_index - 1]) } else { None },\n target[target_index],\n target_lower[target_index],\n matches_sequence_len,\n )\n };\n\n // We have a score and its equal or larger than the left score\n // Match: sequence continues growing from previous diag value\n // Score: increases by diag score value\n let is_valid_score = score != 0 && diag_score + score >= left_score;\n if is_valid_score\n && (\n // We don't need to check if it's contiguous if we allow non-contiguous matches\n allow_non_contiguous_matches ||\n // We must be looking for a contiguous match.\n // Looking at an index above 0 in the query means we must have already\n // found out this is contiguous otherwise there wouldn't have been a score\n query_index > 0 ||\n // lastly check if the query is completely contiguous at this index in the target\n target_lower[target_index..].starts_with(&query_lower)\n )\n {\n matches[current_index] = matches_sequence_len + 1;\n scores[current_index] = diag_score + score;\n } else {\n // We either have no score or the score is lower than the left score\n // Match: reset to 0\n // Score: pick up from left hand side\n matches[current_index] = NO_MATCH;\n scores[current_index] = left_score;\n }\n }\n }\n\n // Restore Positions (starting from bottom right of matrix)\n let mut positions = Vec::new_in(arena);\n\n ", "suffix_code": "\n\n (scores[area - 1], positions)\n}\n\nfn compute_char_score(\n query: char,\n query_lower: char,\n target_prev: Option,\n target_curr: char,\n target_curr_lower: char,\n matches_sequence_len: i32,\n) -> i32 {\n let mut score = 0;\n\n if !consider_as_equal(query_lower, target_curr_lower) {\n return score; // no match of characters\n }\n\n // Character match bonus\n score += 1;\n\n // Consecutive match bonus\n if matches_sequence_len > 0 {\n score += matches_sequence_len * 5;\n }\n\n // Same case bonus\n if query == target_curr {\n score += 1;\n }\n\n if let Some(target_prev) = target_prev {\n // After separator bonus\n let separator_bonus = score_separator_at_pos(target_prev);\n if separator_bonus > 0 {\n score += separator_bonus;\n }\n // Inside word upper case bonus (camel case). We only give this bonus if we're not in a contiguous sequence.\n // For example:\n // NPE => NullPointerException = boost\n // HTTP => HTTP = not boost\n else if target_curr != target_curr_lower && matches_sequence_len == 0 {\n score += 2;\n }\n } else {\n // Start of word bonus\n score += 8;\n }\n\n score\n}\n\nfn consider_as_equal(a: char, b: char) -> bool {\n // Special case path separators: ignore platform differences\n a == b || (a == '/' && b == '\\\\') || (a == '\\\\' && b == '/')\n}\n\nfn score_separator_at_pos(ch: char) -> i32 {\n match ch {\n '/' | '\\\\' => 5, // prefer path separators...\n '_' | '-' | '.' | ' ' | '\\'' | '\"' | ':' => 4, // ...over other separators\n _ => 0,\n }\n}\n\nfn map_chars<'a>(arena: &'a Arena, s: &str) -> Vec {\n let mut chars = Vec::with_capacity_in(s.len(), arena);\n chars.extend(s.chars());\n chars.shrink_to_fit();\n chars\n}\n", "middle_code": "if !query.is_empty() && !target.is_empty() {\n let mut query_index = query.len() - 1;\n let mut target_index = target.len() - 1;\n loop {\n let current_index = query_index * target.len() + target_index;\n if matches[current_index] == NO_MATCH {\n if target_index == 0 {\n break;\n }\n target_index -= 1; \n } else {\n positions.push(target_index);\n if query_index == 0 || target_index == 0 {\n break;\n }\n query_index -= 1;\n target_index -= 1;\n }\n }\n positions.reverse();\n }", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "rust", "sub_task_type": "if_statement"}, "context_code": [["/edit/src/icu.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Bindings to the ICU library.\n\nuse std::cmp::Ordering;\nuse std::ffi::{CStr, c_char};\nuse std::mem;\nuse std::mem::MaybeUninit;\nuse std::ops::Range;\nuse std::ptr::{null, null_mut};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::buffer::TextBuffer;\nuse crate::unicode::Utf8Chars;\nuse crate::{apperr, arena_format, sys};\n\n#[derive(Clone, Copy)]\npub struct Encoding {\n pub label: &'static str,\n pub canonical: &'static str,\n}\n\npub struct Encodings {\n pub preferred: &'static [Encoding],\n pub all: &'static [Encoding],\n}\n\nstatic mut ENCODINGS: Encodings = Encodings { preferred: &[], all: &[] };\n\n/// Returns a list of encodings ICU supports.\npub fn get_available_encodings() -> &'static Encodings {\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n unsafe {\n if ENCODINGS.all.is_empty() {\n let scratch = scratch_arena(None);\n let mut preferred = Vec::new_in(&*scratch);\n let mut alternative = Vec::new_in(&*scratch);\n\n // These encodings are always available.\n preferred.push(Encoding { label: \"UTF-8\", canonical: \"UTF-8\" });\n preferred.push(Encoding { label: \"UTF-8 BOM\", canonical: \"UTF-8 BOM\" });\n\n if let Ok(f) = init_if_needed() {\n let mut n = 0;\n loop {\n let name = (f.ucnv_getAvailableName)(n);\n if name.is_null() {\n break;\n }\n\n n += 1;\n\n let name = CStr::from_ptr(name).to_str().unwrap_unchecked();\n // We have already pushed UTF-8 above and can skip it.\n // There is no need to filter UTF-8 BOM here,\n // since ICU does not distinguish it from UTF-8.\n if name.is_empty() || name == \"UTF-8\" {\n continue;\n }\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let mime = (f.ucnv_getStandardName)(\n name.as_ptr(),\n c\"MIME\".as_ptr() as *const _,\n &mut status,\n );\n if !mime.is_null() && status.is_success() {\n let mime = CStr::from_ptr(mime).to_str().unwrap_unchecked();\n preferred.push(Encoding { label: mime, canonical: name });\n } else {\n alternative.push(Encoding { label: name, canonical: name });\n }\n }\n }\n\n let preferred_len = preferred.len();\n\n // Combine the preferred and alternative encodings into a single list.\n let mut all = Vec::with_capacity(preferred.len() + alternative.len());\n all.extend(preferred);\n all.extend(alternative);\n\n let all = all.leak();\n ENCODINGS.preferred = &all[..preferred_len];\n ENCODINGS.all = &all[..];\n }\n\n &ENCODINGS\n }\n}\n\n/// Formats the given ICU error code into a human-readable string.\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n fn format(code: u32) -> &'static str {\n let Ok(f) = init_if_needed() else {\n return \"\";\n };\n\n let status = icu_ffi::UErrorCode::new(code);\n let ptr = unsafe { (f.u_errorName)(status) };\n if ptr.is_null() {\n return \"\";\n }\n\n let str = unsafe { CStr::from_ptr(ptr) };\n str.to_str().unwrap_or(\"\")\n }\n\n let msg = format(code);\n if !msg.is_empty() {\n write!(f, \"ICU Error: {msg}\")\n } else {\n write!(f, \"ICU Error: {code:#08x}\")\n }\n}\n\n/// Converts between two encodings using ICU.\npub struct Converter<'pivot> {\n source: *mut icu_ffi::UConverter,\n target: *mut icu_ffi::UConverter,\n pivot_buffer: &'pivot mut [MaybeUninit],\n pivot_source: *mut u16,\n pivot_target: *mut u16,\n reset: bool,\n}\n\nimpl Drop for Converter<'_> {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.ucnv_close)(self.source) };\n unsafe { (f.ucnv_close)(self.target) };\n }\n}\n\nimpl<'pivot> Converter<'pivot> {\n /// Constructs a new `Converter` instance.\n ///\n /// # Parameters\n ///\n /// * `pivot_buffer`: A buffer used to cache partial conversions.\n /// Don't make it too small.\n /// * `source_encoding`: The source encoding name (e.g., \"UTF-8\").\n /// * `target_encoding`: The target encoding name (e.g., \"UTF-16\").\n pub fn new(\n pivot_buffer: &'pivot mut [MaybeUninit],\n source_encoding: &str,\n target_encoding: &str,\n ) -> apperr::Result {\n let f = init_if_needed()?;\n\n let arena = scratch_arena(None);\n let source_encoding = Self::append_nul(&arena, source_encoding);\n let target_encoding = Self::append_nul(&arena, target_encoding);\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let source = unsafe { (f.ucnv_open)(source_encoding.as_ptr(), &mut status) };\n let target = unsafe { (f.ucnv_open)(target_encoding.as_ptr(), &mut status) };\n if status.is_failure() {\n if !source.is_null() {\n unsafe { (f.ucnv_close)(source) };\n }\n if !target.is_null() {\n unsafe { (f.ucnv_close)(target) };\n }\n return Err(status.as_error());\n }\n\n let pivot_source = pivot_buffer.as_mut_ptr() as *mut u16;\n let pivot_target = unsafe { pivot_source.add(pivot_buffer.len()) };\n\n Ok(Self { source, target, pivot_buffer, pivot_source, pivot_target, reset: true })\n }\n\n fn append_nul<'a>(arena: &'a Arena, input: &str) -> ArenaString<'a> {\n arena_format!(arena, \"{}\\0\", input)\n }\n\n /// Performs one step of the encoding conversion.\n ///\n /// # Parameters\n ///\n /// * `input`: The input buffer to convert from.\n /// It should be in the `source_encoding` that was previously specified.\n /// * `output`: The output buffer to convert to.\n /// It should be in the `target_encoding` that was previously specified.\n ///\n /// # Returns\n ///\n /// A tuple containing:\n /// 1. The number of bytes read from the input buffer.\n /// 2. The number of bytes written to the output buffer.\n pub fn convert(\n &mut self,\n input: &[u8],\n output: &mut [MaybeUninit],\n ) -> apperr::Result<(usize, usize)> {\n let f = assume_loaded();\n\n let input_beg = input.as_ptr();\n let input_end = unsafe { input_beg.add(input.len()) };\n let mut input_ptr = input_beg;\n\n let output_beg = output.as_mut_ptr() as *mut u8;\n let output_end = unsafe { output_beg.add(output.len()) };\n let mut output_ptr = output_beg;\n\n let pivot_beg = self.pivot_buffer.as_mut_ptr() as *mut u16;\n let pivot_end = unsafe { pivot_beg.add(self.pivot_buffer.len()) };\n\n let flush = input.is_empty();\n let mut status = icu_ffi::U_ZERO_ERROR;\n\n unsafe {\n (f.ucnv_convertEx)(\n /* target_cnv */ self.target,\n /* source_cnv */ self.source,\n /* target */ &mut output_ptr,\n /* target_limit */ output_end,\n /* source */ &mut input_ptr,\n /* source_limit */ input_end,\n /* pivot_start */ pivot_beg,\n /* pivot_source */ &mut self.pivot_source,\n /* pivot_target */ &mut self.pivot_target,\n /* pivot_limit */ pivot_end,\n /* reset */ self.reset,\n /* flush */ flush,\n /* status */ &mut status,\n );\n }\n\n self.reset = false;\n if status.is_failure() && status != icu_ffi::U_BUFFER_OVERFLOW_ERROR {\n return Err(status.as_error());\n }\n\n let input_advance = unsafe { input_ptr.offset_from(input_beg) as usize };\n let output_advance = unsafe { output_ptr.offset_from(output_beg) as usize };\n Ok((input_advance, output_advance))\n }\n}\n\n// In benchmarking, I found that the performance does not really change much by changing this value.\n// I picked 64 because it seemed like a reasonable lower bound.\nconst CACHE_SIZE: usize = 64;\n\n/// Caches a chunk of TextBuffer contents (UTF-8) in UTF-16 format.\n#[repr(C)]\nstruct Cache {\n /// The translated text. Contains [`Cache::utf16_len`]-many valid items.\n utf16: [u16; CACHE_SIZE],\n /// For each character in [`Cache::utf16`] this stores the offset in the [`TextBuffer`],\n /// relative to the start offset stored in `native_beg`.\n /// This has the same length as [`Cache::utf16`].\n utf16_to_utf8_offsets: [u16; CACHE_SIZE],\n /// `utf8_to_utf16_offsets[native_offset - native_beg]` will tell you which character in\n /// [`Cache::utf16`] maps to the given `native_offset` in the underlying [`TextBuffer`].\n /// Contains `native_end - native_beg`-many valid items.\n utf8_to_utf16_offsets: [u16; CACHE_SIZE],\n\n /// The number of valid items in [`Cache::utf16`].\n utf16_len: usize,\n /// Offset of the first non-ASCII character.\n /// Less than or equal to [`Cache::utf16_len`].\n native_indexing_limit: usize,\n\n /// The range of UTF-8 text in the [`TextBuffer`] that this chunk covers.\n utf8_range: Range,\n}\n\n#[repr(C)]\nstruct DoubleCache {\n cache: [Cache; 2],\n /// You can consider this a 1 bit index into `cache`.\n mru: bool,\n}\n\n/// A wrapper around ICU's `UText` struct.\n///\n/// In our case its only purpose is to adapt a [`TextBuffer`] for ICU.\n///\n/// # Safety\n///\n/// Warning! No lifetime tracking is done here.\n/// I initially did it properly with a PhantomData marker for the TextBuffer\n/// lifetime, but it was a pain so now I don't. Not a big deal in our case.\npub struct Text(&'static mut icu_ffi::UText);\n\nimpl Drop for Text {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.utext_close)(self.0) };\n }\n}\n\nimpl Text {\n /// Constructs an ICU `UText` instance from a [`TextBuffer`].\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given [`TextBuffer`]\n /// outlives the returned `Text` instance.\n pub unsafe fn new(tb: &TextBuffer) -> apperr::Result {\n let f = init_if_needed()?;\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let ptr =\n unsafe { (f.utext_setup)(null_mut(), size_of::() as i32, &mut status) };\n if status.is_failure() {\n return Err(status.as_error());\n }\n\n const FUNCS: icu_ffi::UTextFuncs = icu_ffi::UTextFuncs {\n table_size: size_of::() as i32,\n reserved1: 0,\n reserved2: 0,\n reserved3: 0,\n clone: Some(utext_clone),\n native_length: Some(utext_native_length),\n access: Some(utext_access),\n extract: None,\n replace: None,\n copy: None,\n map_offset_to_native: Some(utext_map_offset_to_native),\n map_native_index_to_utf16: Some(utext_map_native_index_to_utf16),\n close: None,\n spare1: None,\n spare2: None,\n spare3: None,\n };\n\n let ut = unsafe { &mut *ptr };\n ut.p_funcs = &FUNCS;\n ut.context = tb as *const TextBuffer as *mut _;\n ut.a = -1;\n\n Ok(Self(ut))\n }\n}\n\nfn text_buffer_from_utext<'a>(ut: &icu_ffi::UText) -> &'a TextBuffer {\n unsafe { &*(ut.context as *const TextBuffer) }\n}\n\nfn double_cache_from_utext<'a>(ut: &icu_ffi::UText) -> &'a mut DoubleCache {\n unsafe { &mut *(ut.p_extra as *mut DoubleCache) }\n}\n\nextern \"C\" fn utext_clone(\n dest: *mut icu_ffi::UText,\n src: &icu_ffi::UText,\n deep: bool,\n status: &mut icu_ffi::UErrorCode,\n) -> *mut icu_ffi::UText {\n if status.is_failure() {\n return null_mut();\n }\n\n if deep {\n *status = icu_ffi::U_UNSUPPORTED_ERROR;\n return null_mut();\n }\n\n let f = assume_loaded();\n let ut_ptr = unsafe { (f.utext_setup)(dest, size_of::() as i32, status) };\n if status.is_failure() {\n return null_mut();\n }\n\n // TODO: I'm somewhat unsure whether we have to preserve the `chunk_offset`.\n // We can't blindly copy chunk contents and the `Cache` in `ut.p_extra`,\n // because they may contain dirty contents (different `TextBuffer` generation).\n unsafe {\n let ut = &mut *ut_ptr;\n ut.p_funcs = src.p_funcs;\n ut.context = src.context;\n ut.a = -1;\n }\n\n ut_ptr\n}\n\nextern \"C\" fn utext_native_length(ut: &mut icu_ffi::UText) -> i64 {\n let tb = text_buffer_from_utext(ut);\n tb.text_length() as i64\n}\n\nextern \"C\" fn utext_access(ut: &mut icu_ffi::UText, native_index: i64, forward: bool) -> bool {\n if let Some(cache) = utext_access_impl(ut, native_index, forward) {\n let native_off = native_index as usize - cache.utf8_range.start;\n ut.chunk_contents = cache.utf16.as_ptr();\n ut.chunk_length = cache.utf16_len as i32;\n ut.chunk_offset = cache.utf8_to_utf16_offsets[native_off] as i32;\n ut.chunk_native_start = cache.utf8_range.start as i64;\n ut.chunk_native_limit = cache.utf8_range.end as i64;\n ut.native_indexing_limit = cache.native_indexing_limit as i32;\n true\n } else {\n false\n }\n}\n\nfn utext_access_impl<'a>(\n ut: &mut icu_ffi::UText,\n native_index: i64,\n forward: bool,\n) -> Option<&'a mut Cache> {\n let tb = text_buffer_from_utext(ut);\n let mut index_contained = native_index;\n\n if !forward {\n index_contained -= 1;\n }\n if index_contained < 0 || index_contained as usize >= tb.text_length() {\n return None;\n }\n\n let index_contained = index_contained as usize;\n let native_index = native_index as usize;\n let double_cache = double_cache_from_utext(ut);\n let dirty = ut.a != tb.generation() as i64;\n\n if dirty {\n // The text buffer contents have changed.\n // Invalidate both caches so that future calls don't mistakenly use them\n // when they enter the for loop in the else branch below (`dirty == false`).\n double_cache.cache[0].utf16_len = 0;\n double_cache.cache[1].utf16_len = 0;\n double_cache.cache[0].utf8_range = 0..0;\n double_cache.cache[1].utf8_range = 0..0;\n ut.a = tb.generation() as i64;\n } else {\n // Check if one of the caches already contains the requested range.\n for (i, cache) in double_cache.cache.iter_mut().enumerate() {\n if cache.utf8_range.contains(&index_contained) {\n double_cache.mru = i != 0;\n return Some(cache);\n }\n }\n }\n\n // Turn the least recently used cache into the most recently used one.\n let double_cache = double_cache_from_utext(ut);\n double_cache.mru = !double_cache.mru;\n let cache = &mut double_cache.cache[double_cache.mru as usize];\n\n // In order to safely fit any UTF-8 character into our cache,\n // we must assume the worst case of a 4-byte long encoding.\n const UTF16_LEN_LIMIT: usize = CACHE_SIZE - 4;\n let utf8_len_limit;\n let native_start;\n\n if forward {\n utf8_len_limit = (tb.text_length() - native_index).min(UTF16_LEN_LIMIT);\n native_start = native_index;\n } else {\n // The worst case ratio for UTF-8 to UTF-16 is 1:1, when the text is ASCII.\n // This allows us to safely subtract the UTF-16 buffer size\n // and assume that whatever we read as UTF-8 will fit.\n // TODO: Test what happens if you have lots of invalid UTF-8 text blow up to U+FFFD.\n utf8_len_limit = native_index.min(UTF16_LEN_LIMIT);\n\n // Since simply subtracting an offset may end up in the middle of a codepoint sequence,\n // we must align the offset to the next codepoint boundary.\n // Here we skip trail bytes until we find a lead.\n let mut beg = native_index - utf8_len_limit;\n let chunk = tb.read_forward(beg);\n for &c in chunk {\n if c & 0b1100_0000 != 0b1000_0000 {\n break;\n }\n beg += 1;\n }\n\n native_start = beg;\n }\n\n // Translate the given range from UTF-8 to UTF-16.\n // NOTE: This code makes the assumption that the `native_index` is always\n // at UTF-8 codepoint boundaries which technically isn't guaranteed.\n let mut utf16_len = 0;\n let mut utf8_len = 0;\n let mut ascii_len = 0;\n 'outer: loop {\n let initial_utf8_len = utf8_len;\n let chunk = tb.read_forward(native_start + utf8_len);\n if chunk.is_empty() {\n break;\n }\n\n let mut it = Utf8Chars::new(chunk, 0);\n\n // If we've only seen ASCII so far we can fast-pass the UTF-16 translation,\n // because we can just widen from u8 -> u16.\n if utf16_len == ascii_len {\n let haystack = &chunk[..chunk.len().min(utf8_len_limit - ascii_len)];\n\n // When it comes to performance, and the search space is small (which it is here),\n // it's always a good idea to keep the loops small and tight...\n let len = haystack.iter().position(|&c| c >= 0x80).unwrap_or(haystack.len());\n\n // ...In this case it allows the compiler to vectorize this loop and double\n // the performance. Luckily, llvm doesn't unroll the loop, which is great,\n // because `len` will always be a relatively small number.\n for &c in &chunk[..len] {\n unsafe {\n *cache.utf16.get_unchecked_mut(ascii_len) = c as u16;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(ascii_len) = ascii_len as u16;\n *cache.utf8_to_utf16_offsets.get_unchecked_mut(ascii_len) = ascii_len as u16;\n }\n ascii_len += 1;\n }\n\n utf16_len += len;\n utf8_len += len;\n it.seek(len);\n if ascii_len >= UTF16_LEN_LIMIT {\n break;\n }\n }\n\n loop {\n let Some(c) = it.next() else {\n break;\n };\n\n // Thanks to our `if utf16_len >= UTF16_LEN_LIMIT` check,\n // we can safely assume that this will fit.\n unsafe {\n let utf8_len_beg = utf8_len;\n let utf8_len_end = initial_utf8_len + it.offset();\n\n while utf8_len < utf8_len_end {\n *cache.utf8_to_utf16_offsets.get_unchecked_mut(utf8_len) = utf16_len as u16;\n utf8_len += 1;\n }\n\n if c <= '\\u{FFFF}' {\n *cache.utf16.get_unchecked_mut(utf16_len) = c as u16;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len) = utf8_len_beg as u16;\n utf16_len += 1;\n } else {\n let c = c as u32 - 0x10000;\n let b = utf8_len_beg as u16;\n *cache.utf16.get_unchecked_mut(utf16_len) = (c >> 10) as u16 | 0xD800;\n *cache.utf16.get_unchecked_mut(utf16_len + 1) = (c & 0x3FF) as u16 | 0xDC00;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len) = b;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len + 1) = b;\n utf16_len += 2;\n }\n }\n\n if utf16_len >= UTF16_LEN_LIMIT || utf8_len >= utf8_len_limit {\n break 'outer;\n }\n }\n }\n\n // Allow for looking up past-the-end indices via\n // `utext_map_offset_to_native` and `utext_map_native_index_to_utf16`.\n cache.utf16_to_utf8_offsets[utf16_len] = utf8_len as u16;\n cache.utf8_to_utf16_offsets[utf8_len] = utf16_len as u16;\n\n let native_limit = native_start + utf8_len;\n cache.utf16_len = utf16_len;\n // If parts of the UTF-8 chunk are ASCII, we can tell ICU that it doesn't need to call\n // utext_map_offset_to_native. For some reason, uregex calls that function *a lot*,\n // literally half the CPU time is spent on it.\n cache.native_indexing_limit = ascii_len;\n cache.utf8_range = native_start..native_limit;\n Some(cache)\n}\n\nextern \"C\" fn utext_map_offset_to_native(ut: &icu_ffi::UText) -> i64 {\n debug_assert!((0..=ut.chunk_length).contains(&ut.chunk_offset));\n\n let double_cache = double_cache_from_utext(ut);\n let cache = &double_cache.cache[double_cache.mru as usize];\n let off_rel = cache.utf16_to_utf8_offsets[ut.chunk_offset as usize];\n let off_abs = cache.utf8_range.start + off_rel as usize;\n off_abs as i64\n}\n\nextern \"C\" fn utext_map_native_index_to_utf16(ut: &icu_ffi::UText, native_index: i64) -> i32 {\n debug_assert!((ut.chunk_native_start..=ut.chunk_native_limit).contains(&native_index));\n\n let double_cache = double_cache_from_utext(ut);\n let cache = &double_cache.cache[double_cache.mru as usize];\n let off_rel = cache.utf8_to_utf16_offsets[(native_index - ut.chunk_native_start) as usize];\n off_rel as i32\n}\n\n/// A wrapper around ICU's `URegularExpression` struct.\n///\n/// # Safety\n///\n/// Warning! No lifetime tracking is done here.\npub struct Regex(&'static mut icu_ffi::URegularExpression);\n\nimpl Drop for Regex {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.uregex_close)(self.0) };\n }\n}\n\nimpl Regex {\n /// Enable case-insensitive matching.\n pub const CASE_INSENSITIVE: i32 = icu_ffi::UREGEX_CASE_INSENSITIVE;\n\n /// If set, ^ and $ match the start and end of each line.\n /// Otherwise, they match the start and end of the entire string.\n pub const MULTILINE: i32 = icu_ffi::UREGEX_MULTILINE;\n\n /// Treat the given pattern as a literal string.\n pub const LITERAL: i32 = icu_ffi::UREGEX_LITERAL;\n\n /// Constructs a regex, plain and simple. Read `uregex_open` docs.\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given `Text` outlives the returned `Regex` instance.\n pub unsafe fn new(pattern: &str, flags: i32, text: &Text) -> apperr::Result {\n let f = init_if_needed()?;\n unsafe {\n let scratch = scratch_arena(None);\n let mut utf16 = Vec::new_in(&*scratch);\n let mut status = icu_ffi::U_ZERO_ERROR;\n\n utf16.extend(pattern.encode_utf16());\n\n let ptr = (f.uregex_open)(\n utf16.as_ptr(),\n utf16.len() as i32,\n icu_ffi::UREGEX_MULTILINE | icu_ffi::UREGEX_ERROR_ON_UNKNOWN_ESCAPES | flags,\n None,\n &mut status,\n );\n // ICU describes the time unit as being dependent on CPU performance\n // and \"typically [in] the order of milliseconds\", but this claim seems\n // highly outdated. On my CPU from 2021, a limit of 4096 equals roughly 600ms.\n (f.uregex_setTimeLimit)(ptr, 4096, &mut status);\n (f.uregex_setUText)(ptr, text.0 as *const _ as *mut _, &mut status);\n if status.is_failure() {\n return Err(status.as_error());\n }\n\n Ok(Self(&mut *ptr))\n }\n }\n\n /// Updates the regex pattern with the given text.\n /// If the text contents have changed, you can pass the same text as you used\n /// initially and it'll trigger ICU to reload the text and invalidate its caches.\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given `Text` outlives the `Regex` instance.\n pub unsafe fn set_text(&mut self, text: &mut Text, offset: usize) {\n // Get `utext_access_impl` to detect the `TextBuffer::generation` change,\n // and refresh its contents. This ensures that ICU doesn't reuse\n // stale `UText::chunk_contents`, as it has no way tell that it's stale.\n utext_access(text.0, offset as i64, true);\n\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n unsafe { (f.uregex_setUText)(self.0, text.0 as *const _ as *mut _, &mut status) };\n // `uregex_setUText` resets the regex to the start of the text.\n // Because of this, we must also call `uregex_reset64`.\n unsafe { (f.uregex_reset64)(self.0, offset as i64, &mut status) };\n }\n\n /// Sets the regex to the absolute offset in the underlying text.\n pub fn reset(&mut self, offset: usize) {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n unsafe { (f.uregex_reset64)(self.0, offset as i64, &mut status) };\n }\n\n /// Gets captured group count.\n pub fn group_count(&mut self) -> i32 {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let count = unsafe { (f.uregex_groupCount)(self.0, &mut status) };\n if status.is_failure() { 0 } else { count }\n }\n\n /// Gets the text range of a captured group by index.\n pub fn group(&mut self, group: i32) -> Option> {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let start = unsafe { (f.uregex_start64)(self.0, group, &mut status) };\n let end = unsafe { (f.uregex_end64)(self.0, group, &mut status) };\n if status.is_failure() {\n None\n } else {\n let start = start.max(0);\n let end = end.max(start);\n Some(start as usize..end as usize)\n }\n }\n}\n\nimpl Iterator for Regex {\n type Item = Range;\n\n fn next(&mut self) -> Option {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let ok = unsafe { (f.uregex_findNext)(self.0, &mut status) };\n if !ok {\n return None;\n }\n\n self.group(0)\n }\n}\n\nstatic mut ROOT_COLLATOR: Option<*mut icu_ffi::UCollator> = None;\n\n/// Compares two UTF-8 strings for sorting using ICU's collation algorithm.\npub fn compare_strings(a: &[u8], b: &[u8]) -> Ordering {\n #[cold]\n fn init() {\n unsafe {\n let mut coll = null_mut();\n\n if let Ok(f) = init_if_needed() {\n let mut status = icu_ffi::U_ZERO_ERROR;\n coll = (f.ucol_open)(c\"\".as_ptr(), &mut status);\n }\n\n ROOT_COLLATOR = Some(coll);\n }\n }\n\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n let coll = unsafe {\n if ROOT_COLLATOR.is_none() {\n init();\n }\n ROOT_COLLATOR.unwrap_unchecked()\n };\n\n if coll.is_null() {\n compare_strings_ascii(a, b)\n } else {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n let res = unsafe {\n (f.ucol_strcollUTF8)(\n coll,\n a.as_ptr(),\n a.len() as i32,\n b.as_ptr(),\n b.len() as i32,\n &mut status,\n )\n };\n\n match res {\n icu_ffi::UCollationResult::UCOL_EQUAL => Ordering::Equal,\n icu_ffi::UCollationResult::UCOL_GREATER => Ordering::Greater,\n icu_ffi::UCollationResult::UCOL_LESS => Ordering::Less,\n }\n }\n}\n\n/// Unicode collation via `ucol_strcollUTF8`, now for ASCII!\nfn compare_strings_ascii(a: &[u8], b: &[u8]) -> Ordering {\n let mut iter = a.iter().zip(b.iter());\n\n // Low weight: Find the first character which differs.\n //\n // Remember that result in case all remaining characters are\n // case-insensitive equal, because then we use that as a fallback.\n while let Some((&a, &b)) = iter.next() {\n if a != b {\n let mut order = a.cmp(&b);\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n\n if la == lb {\n // High weight: Find the first character which\n // differs case-insensitively.\n for (a, b) in iter {\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n\n if la != lb {\n order = la.cmp(&lb);\n break;\n }\n }\n }\n\n return order;\n }\n }\n\n // Fallback: The shorter string wins.\n a.len().cmp(&b.len())\n}\n\nstatic mut ROOT_CASEMAP: Option<*mut icu_ffi::UCaseMap> = None;\n\n/// Converts the given UTF-8 string to lower case.\n///\n/// Case folding differs from lower case in that the output is primarily useful\n/// to machines for comparisons. It's like applying Unicode normalization.\npub fn fold_case<'a>(arena: &'a Arena, input: &str) -> ArenaString<'a> {\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n let casemap = unsafe {\n if ROOT_CASEMAP.is_none() {\n ROOT_CASEMAP = Some(if let Ok(f) = init_if_needed() {\n let mut status = icu_ffi::U_ZERO_ERROR;\n (f.ucasemap_open)(null(), 0, &mut status)\n } else {\n null_mut()\n })\n }\n ROOT_CASEMAP.unwrap_unchecked()\n };\n\n if !casemap.is_null() {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n let mut output = Vec::new_in(arena);\n let mut output_len;\n\n // First, guess the output length:\n // TODO: What's a good heuristic here?\n {\n output.reserve_exact(input.len() + 16);\n let output = output.spare_capacity_mut();\n output_len = unsafe {\n (f.ucasemap_utf8FoldCase)(\n casemap,\n output.as_mut_ptr() as *mut _,\n output.len() as i32,\n input.as_ptr() as *const _,\n input.len() as i32,\n &mut status,\n )\n };\n }\n\n // If that failed to fit, retry with the correct length.\n if status == icu_ffi::U_BUFFER_OVERFLOW_ERROR && output_len > 0 {\n output.reserve_exact(output_len as usize);\n let output = output.spare_capacity_mut();\n output_len = unsafe {\n (f.ucasemap_utf8FoldCase)(\n casemap,\n output.as_mut_ptr() as *mut _,\n output.len() as i32,\n input.as_ptr() as *const _,\n input.len() as i32,\n &mut status,\n )\n };\n }\n\n if status.is_success() && output_len > 0 {\n unsafe {\n output.set_len(output_len as usize);\n }\n return unsafe { ArenaString::from_utf8_unchecked(output) };\n }\n }\n\n let mut result = ArenaString::from_str(arena, input);\n for b in unsafe { result.as_bytes_mut() } {\n b.make_ascii_lowercase();\n }\n result\n}\n\n// NOTE:\n// To keep this neat, fields are ordered by prefix (= `ucol_` before `uregex_`),\n// followed by functions in this order:\n// * Static methods (e.g. `ucnv_getAvailableName`)\n// * Constructors (e.g. `ucnv_open`)\n// * Destructors (e.g. `ucnv_close`)\n// * Methods, grouped by relationship\n// (e.g. `uregex_start64` and `uregex_end64` are near each other)\n//\n// WARNING:\n// The order of the fields MUST match the order of strings in the following two arrays.\n#[allow(non_snake_case)]\n#[repr(C)]\nstruct LibraryFunctions {\n // LIBICUUC_PROC_NAMES\n u_errorName: icu_ffi::u_errorName,\n ucasemap_open: icu_ffi::ucasemap_open,\n ucasemap_utf8FoldCase: icu_ffi::ucasemap_utf8FoldCase,\n ucnv_getAvailableName: icu_ffi::ucnv_getAvailableName,\n ucnv_getStandardName: icu_ffi::ucnv_getStandardName,\n ucnv_open: icu_ffi::ucnv_open,\n ucnv_close: icu_ffi::ucnv_close,\n ucnv_convertEx: icu_ffi::ucnv_convertEx,\n utext_setup: icu_ffi::utext_setup,\n utext_close: icu_ffi::utext_close,\n\n // LIBICUI18N_PROC_NAMES\n ucol_open: icu_ffi::ucol_open,\n ucol_strcollUTF8: icu_ffi::ucol_strcollUTF8,\n uregex_open: icu_ffi::uregex_open,\n uregex_close: icu_ffi::uregex_close,\n uregex_setTimeLimit: icu_ffi::uregex_setTimeLimit,\n uregex_setUText: icu_ffi::uregex_setUText,\n uregex_reset64: icu_ffi::uregex_reset64,\n uregex_findNext: icu_ffi::uregex_findNext,\n uregex_groupCount: icu_ffi::uregex_groupCount,\n uregex_start64: icu_ffi::uregex_start64,\n uregex_end64: icu_ffi::uregex_end64,\n}\n\nmacro_rules! proc_name {\n ($s:literal) => {\n concat!(env!(\"EDIT_CFG_ICU_EXPORT_PREFIX\"), $s, env!(\"EDIT_CFG_ICU_EXPORT_SUFFIX\"), \"\\0\")\n .as_ptr() as *const c_char\n };\n}\n\n// Found in libicuuc.so on UNIX, icuuc.dll/icu.dll on Windows.\nconst LIBICUUC_PROC_NAMES: [*const c_char; 10] = [\n proc_name!(\"u_errorName\"),\n proc_name!(\"ucasemap_open\"),\n proc_name!(\"ucasemap_utf8FoldCase\"),\n proc_name!(\"ucnv_getAvailableName\"),\n proc_name!(\"ucnv_getStandardName\"),\n proc_name!(\"ucnv_open\"),\n proc_name!(\"ucnv_close\"),\n proc_name!(\"ucnv_convertEx\"),\n proc_name!(\"utext_setup\"),\n proc_name!(\"utext_close\"),\n];\n\n// Found in libicui18n.so on UNIX, icuin.dll/icu.dll on Windows.\nconst LIBICUI18N_PROC_NAMES: [*const c_char; 11] = [\n proc_name!(\"ucol_open\"),\n proc_name!(\"ucol_strcollUTF8\"),\n proc_name!(\"uregex_open\"),\n proc_name!(\"uregex_close\"),\n proc_name!(\"uregex_setTimeLimit\"),\n proc_name!(\"uregex_setUText\"),\n proc_name!(\"uregex_reset64\"),\n proc_name!(\"uregex_findNext\"),\n proc_name!(\"uregex_groupCount\"),\n proc_name!(\"uregex_start64\"),\n proc_name!(\"uregex_end64\"),\n];\n\nenum LibraryFunctionsState {\n Uninitialized,\n Failed,\n Loaded(LibraryFunctions),\n}\n\nstatic mut LIBRARY_FUNCTIONS: LibraryFunctionsState = LibraryFunctionsState::Uninitialized;\n\npub fn init() -> apperr::Result<()> {\n init_if_needed()?;\n Ok(())\n}\n\n#[allow(static_mut_refs)]\nfn init_if_needed() -> apperr::Result<&'static LibraryFunctions> {\n #[cold]\n fn load() {\n unsafe {\n LIBRARY_FUNCTIONS = LibraryFunctionsState::Failed;\n\n let Ok(icu) = sys::load_icu() else {\n return;\n };\n\n type TransparentFunction = unsafe extern \"C\" fn() -> *const ();\n\n // OH NO I'M DOING A BAD THING\n //\n // If this assertion hits, you either forgot to update `LIBRARY_PROC_NAMES`\n // or you're on a platform where `dlsym` behaves different from classic UNIX and Windows.\n //\n // This code assumes that we can treat the `LibraryFunctions` struct containing various different function\n // pointers as an array of `TransparentFunction` pointers. In C, this works on any platform that supports\n // POSIX `dlsym` or equivalent, but I suspect Rust is once again being extra about it. In any case, that's\n // still better than loading every function one by one, just to blow up our binary size for no reason.\n const _: () = assert!(\n mem::size_of::()\n == mem::size_of::()\n * (LIBICUUC_PROC_NAMES.len() + LIBICUI18N_PROC_NAMES.len())\n );\n\n let mut funcs = MaybeUninit::::uninit();\n let mut ptr = funcs.as_mut_ptr() as *mut TransparentFunction;\n\n #[cfg(edit_icu_renaming_auto_detect)]\n let scratch_outer = scratch_arena(None);\n #[cfg(edit_icu_renaming_auto_detect)]\n let suffix = sys::icu_detect_renaming_suffix(&scratch_outer, icu.libicuuc);\n\n for (handle, names) in [\n (icu.libicuuc, &LIBICUUC_PROC_NAMES[..]),\n (icu.libicui18n, &LIBICUI18N_PROC_NAMES[..]),\n ] {\n for &name in names {\n #[cfg(edit_icu_renaming_auto_detect)]\n let scratch = scratch_arena(Some(&scratch_outer));\n #[cfg(edit_icu_renaming_auto_detect)]\n let name = sys::icu_add_renaming_suffix(&scratch, name, &suffix);\n\n let Ok(func) = sys::get_proc_address(handle, name) else {\n debug_assert!(\n false,\n \"Failed to load ICU function: {:?}\",\n CStr::from_ptr(name)\n );\n return;\n };\n\n ptr.write(func);\n ptr = ptr.add(1);\n }\n }\n\n LIBRARY_FUNCTIONS = LibraryFunctionsState::Loaded(funcs.assume_init());\n }\n }\n\n unsafe {\n if matches!(&LIBRARY_FUNCTIONS, LibraryFunctionsState::Uninitialized) {\n load();\n }\n }\n\n match unsafe { &LIBRARY_FUNCTIONS } {\n LibraryFunctionsState::Loaded(f) => Ok(f),\n _ => Err(apperr::APP_ICU_MISSING),\n }\n}\n\n#[allow(static_mut_refs)]\nfn assume_loaded() -> &'static LibraryFunctions {\n match unsafe { &LIBRARY_FUNCTIONS } {\n LibraryFunctionsState::Loaded(f) => f,\n _ => unreachable!(),\n }\n}\n\nmod icu_ffi {\n #![allow(dead_code, non_camel_case_types)]\n\n use std::ffi::{c_char, c_int, c_void};\n\n use crate::apperr;\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct UErrorCode(c_int);\n\n impl UErrorCode {\n pub const fn new(code: u32) -> Self {\n Self(code as c_int)\n }\n\n pub fn is_success(&self) -> bool {\n self.0 <= 0\n }\n\n pub fn is_failure(&self) -> bool {\n self.0 > 0\n }\n\n pub fn as_error(&self) -> apperr::Error {\n debug_assert!(self.0 > 0);\n apperr::Error::new_icu(self.0 as u32)\n }\n }\n\n pub const U_ZERO_ERROR: UErrorCode = UErrorCode(0);\n pub const U_BUFFER_OVERFLOW_ERROR: UErrorCode = UErrorCode(15);\n pub const U_UNSUPPORTED_ERROR: UErrorCode = UErrorCode(16);\n\n pub type u_errorName = unsafe extern \"C\" fn(code: UErrorCode) -> *const c_char;\n\n pub struct UConverter;\n\n pub type ucnv_getAvailableName = unsafe extern \"C\" fn(n: i32) -> *const c_char;\n\n pub type ucnv_getStandardName = unsafe extern \"C\" fn(\n name: *const u8,\n standard: *const u8,\n status: &mut UErrorCode,\n ) -> *const c_char;\n\n pub type ucnv_open =\n unsafe extern \"C\" fn(converter_name: *const u8, status: &mut UErrorCode) -> *mut UConverter;\n\n pub type ucnv_close = unsafe extern \"C\" fn(converter: *mut UConverter);\n\n pub type ucnv_convertEx = unsafe extern \"C\" fn(\n target_cnv: *mut UConverter,\n source_cnv: *mut UConverter,\n target: *mut *mut u8,\n target_limit: *const u8,\n source: *mut *const u8,\n source_limit: *const u8,\n pivot_start: *mut u16,\n pivot_source: *mut *mut u16,\n pivot_target: *mut *mut u16,\n pivot_limit: *const u16,\n reset: bool,\n flush: bool,\n status: &mut UErrorCode,\n );\n\n pub struct UCaseMap;\n\n pub type ucasemap_open = unsafe extern \"C\" fn(\n locale: *const c_char,\n options: u32,\n status: &mut UErrorCode,\n ) -> *mut UCaseMap;\n\n pub type ucasemap_utf8FoldCase = unsafe extern \"C\" fn(\n csm: *const UCaseMap,\n dest: *mut c_char,\n dest_capacity: i32,\n src: *const c_char,\n src_length: i32,\n status: &mut UErrorCode,\n ) -> i32;\n\n #[repr(C)]\n pub enum UCollationResult {\n UCOL_EQUAL = 0,\n UCOL_GREATER = 1,\n UCOL_LESS = -1,\n }\n\n #[repr(C)]\n pub struct UCollator;\n\n pub type ucol_open =\n unsafe extern \"C\" fn(loc: *const c_char, status: &mut UErrorCode) -> *mut UCollator;\n\n pub type ucol_strcollUTF8 = unsafe extern \"C\" fn(\n coll: *mut UCollator,\n source: *const u8,\n source_length: i32,\n target: *const u8,\n target_length: i32,\n status: &mut UErrorCode,\n ) -> UCollationResult;\n\n // UText callback functions\n pub type UTextClone = unsafe extern \"C\" fn(\n dest: *mut UText,\n src: &UText,\n deep: bool,\n status: &mut UErrorCode,\n ) -> *mut UText;\n pub type UTextNativeLength = unsafe extern \"C\" fn(ut: &mut UText) -> i64;\n pub type UTextAccess =\n unsafe extern \"C\" fn(ut: &mut UText, native_index: i64, forward: bool) -> bool;\n pub type UTextExtract = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n dest: *mut u16,\n dest_capacity: i32,\n status: &mut UErrorCode,\n ) -> i32;\n pub type UTextReplace = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n replacement_text: *const u16,\n replacement_length: i32,\n status: &mut UErrorCode,\n ) -> i32;\n pub type UTextCopy = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n native_dest: i64,\n move_text: bool,\n status: &mut UErrorCode,\n );\n pub type UTextMapOffsetToNative = unsafe extern \"C\" fn(ut: &UText) -> i64;\n pub type UTextMapNativeIndexToUTF16 =\n unsafe extern \"C\" fn(ut: &UText, native_index: i64) -> i32;\n pub type UTextClose = unsafe extern \"C\" fn(ut: &mut UText);\n\n #[repr(C)]\n pub struct UTextFuncs {\n pub table_size: i32,\n pub reserved1: i32,\n pub reserved2: i32,\n pub reserved3: i32,\n pub clone: Option,\n pub native_length: Option,\n pub access: Option,\n pub extract: Option,\n pub replace: Option,\n pub copy: Option,\n pub map_offset_to_native: Option,\n pub map_native_index_to_utf16: Option,\n pub close: Option,\n pub spare1: Option,\n pub spare2: Option,\n pub spare3: Option,\n }\n\n #[repr(C)]\n pub struct UText {\n pub magic: u32,\n pub flags: i32,\n pub provider_properties: i32,\n pub size_of_struct: i32,\n pub chunk_native_limit: i64,\n pub extra_size: i32,\n pub native_indexing_limit: i32,\n pub chunk_native_start: i64,\n pub chunk_offset: i32,\n pub chunk_length: i32,\n pub chunk_contents: *const u16,\n pub p_funcs: &'static UTextFuncs,\n pub p_extra: *mut c_void,\n pub context: *mut c_void,\n pub p: *mut c_void,\n pub q: *mut c_void,\n pub r: *mut c_void,\n pub priv_p: *mut c_void,\n pub a: i64,\n pub b: i32,\n pub c: i32,\n pub priv_a: i64,\n pub priv_b: i32,\n pub priv_c: i32,\n }\n\n pub const UTEXT_MAGIC: u32 = 0x345ad82c;\n pub const UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE: i32 = 1;\n pub const UTEXT_PROVIDER_STABLE_CHUNKS: i32 = 2;\n pub const UTEXT_PROVIDER_WRITABLE: i32 = 3;\n pub const UTEXT_PROVIDER_HAS_META_DATA: i32 = 4;\n pub const UTEXT_PROVIDER_OWNS_TEXT: i32 = 5;\n\n pub type utext_setup = unsafe extern \"C\" fn(\n ut: *mut UText,\n extra_space: i32,\n status: &mut UErrorCode,\n ) -> *mut UText;\n pub type utext_close = unsafe extern \"C\" fn(ut: *mut UText) -> *mut UText;\n\n #[repr(C)]\n pub struct UParseError {\n pub line: i32,\n pub offset: i32,\n pub pre_context: [u16; 16],\n pub post_context: [u16; 16],\n }\n\n #[repr(C)]\n pub struct URegularExpression;\n\n pub const UREGEX_UNIX_LINES: i32 = 1;\n pub const UREGEX_CASE_INSENSITIVE: i32 = 2;\n pub const UREGEX_COMMENTS: i32 = 4;\n pub const UREGEX_MULTILINE: i32 = 8;\n pub const UREGEX_LITERAL: i32 = 16;\n pub const UREGEX_DOTALL: i32 = 32;\n pub const UREGEX_UWORD: i32 = 256;\n pub const UREGEX_ERROR_ON_UNKNOWN_ESCAPES: i32 = 512;\n\n pub type uregex_open = unsafe extern \"C\" fn(\n pattern: *const u16,\n pattern_length: i32,\n flags: i32,\n pe: Option<&mut UParseError>,\n status: &mut UErrorCode,\n ) -> *mut URegularExpression;\n pub type uregex_close = unsafe extern \"C\" fn(regexp: *mut URegularExpression);\n pub type uregex_setTimeLimit =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, limit: i32, status: &mut UErrorCode);\n pub type uregex_setUText = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n text: *mut UText,\n status: &mut UErrorCode,\n );\n pub type uregex_reset64 =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, index: i64, status: &mut UErrorCode);\n pub type uregex_findNext =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, status: &mut UErrorCode) -> bool;\n pub type uregex_groupCount =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, status: &mut UErrorCode) -> i32;\n pub type uregex_start64 = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n group_num: i32,\n status: &mut UErrorCode,\n ) -> i64;\n pub type uregex_end64 = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n group_num: i32,\n status: &mut UErrorCode,\n ) -> i64;\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[ignore]\n #[test]\n fn init() {\n assert!(init_if_needed().is_ok());\n }\n\n #[test]\n fn test_compare_strings_ascii() {\n // Empty strings\n assert_eq!(compare_strings_ascii(b\"\", b\"\"), Ordering::Equal);\n // Equal strings\n assert_eq!(compare_strings_ascii(b\"hello\", b\"hello\"), Ordering::Equal);\n // Different lengths\n assert_eq!(compare_strings_ascii(b\"abc\", b\"abcd\"), Ordering::Less);\n assert_eq!(compare_strings_ascii(b\"abcd\", b\"abc\"), Ordering::Greater);\n // Same chars, different cases - 1st char wins\n assert_eq!(compare_strings_ascii(b\"AbC\", b\"aBc\"), Ordering::Less);\n // Different chars, different cases - 2nd char wins, because it differs\n assert_eq!(compare_strings_ascii(b\"hallo\", b\"Hello\"), Ordering::Less);\n assert_eq!(compare_strings_ascii(b\"Hello\", b\"hallo\"), Ordering::Greater);\n }\n}\n"], ["/edit/src/tui.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! An immediate mode UI framework for terminals.\n//!\n//! # Why immediate mode?\n//!\n//! This uses an \"immediate mode\" design, similar to [ImGui](https://github.com/ocornut/imgui).\n//! The reason for this is that I expect the UI needs for any terminal application to be\n//! fairly minimal, and for that purpose an immediate mode design is much simpler to use.\n//!\n//! So what's \"immediate mode\"? The primary alternative is called \"retained mode\".\n//! The difference is that when you create a button in this framework in one frame,\n//! and you stop telling this framework in the next frame, the button will vanish.\n//! When you use a regular retained mode UI framework, you create the button once,\n//! set up callbacks for when it is clicked, and then stop worrying about it.\n//!\n//! The downside of immediate mode is that your UI code _may_ become cluttered.\n//! The upside however is that you cannot leak UI elements, you don't need to\n//! worry about lifetimes nor callbacks, and that simple UIs are simple to write.\n//!\n//! More importantly though, the primary reason for this is that the\n//! lack of callbacks means we can use this design across a plain C ABI,\n//! which we'll need once plugins come into play. GTK's `g_signal_connect`\n//! shows that the alternative can be rather cumbersome.\n//!\n//! # Design overview\n//!\n//! While this file is fairly lengthy, the overall algorithm is simple.\n//! On the first frame ever:\n//! * Prepare an empty `arena_next`.\n//! * Parse the incoming [`input::Input`] which should be a resize event.\n//! * Create a new [`Context`] instance and give it the caller.\n//! * Now the caller will draw their UI with the [`Context`] by calling the\n//! various [`Context`] UI methods, such as [`Context::block_begin()`] and\n//! [`Context::block_end()`]. These two are the basis which all other UI\n//! elements are built upon by the way. Each UI element that is created gets\n//! allocated onto `arena_next` and inserted into the UI tree.\n//! That tree works exactly like the DOM tree in HTML: Each node in the tree\n//! has a parent, children, and siblings. The tree layout at the end is then\n//! a direct mirror of the code \"layout\" that created it.\n//! * Once the caller is done and drops the [`Context`], it'll secretly call\n//! `report_context_completion`. This causes a number of things:\n//! * The DOM tree that was built is stored in `prev_tree`.\n//! * A hashmap of all nodes is built and stored in `prev_node_map`.\n//! * `arena_next` is swapped with `arena_prev`.\n//! * Each UI node is measured and laid out.\n//! * Now the caller is expected to repeat this process with a [`None`]\n//! input event until [`Tui::needs_settling()`] returns false.\n//! This is necessary, because when [`Context::button()`] returns `true`\n//! in one frame, it may change the state in the caller's code\n//! and require another frame to be drawn.\n//! * Finally a call to [`Tui::render()`] will render the UI tree into the\n//! framebuffer and return VT output.\n//!\n//! On every subsequent frame the process is similar, but one crucial element\n//! of any immediate mode UI framework is added:\n//! Now when the caller draws their UI, the various [`Context`] UI elements\n//! have access to `prev_node_map` and the previously built UI tree.\n//! This allows the UI framework to reuse the previously computed layout for\n//! hit tests, caching scroll offsets, and so on.\n//!\n//! In the end it looks very similar:\n//! * Prepare an empty `arena_next`.\n//! * Parse the incoming [`input::Input`]...\n//! * **BUT** now we can hit-test mouse clicks onto the previously built\n//! UI tree. This way we can delegate focus on left mouse clicks.\n//! * Create a new [`Context`] instance and give it the caller.\n//! * The caller draws their UI with the [`Context`]...\n//! * **BUT** we can preserve the UI state across frames.\n//! * Continue rendering until [`Tui::needs_settling()`] returns false.\n//! * And the final call to [`Tui::render()`].\n//!\n//! # Classnames and node IDs\n//!\n//! So how do we find which node from the previous tree correlates to the\n//! current node? Each node needs to be constructed with a \"classname\".\n//! The classname is hashed with the parent node ID as the seed. This derived\n//! hash is then used as the new child node ID. Under the assumption that the\n//! collision likelihood of the hash function is low, this serves as true IDs.\n//!\n//! This has the nice added property that finding a node with the same ID\n//! guarantees that all of the parent nodes must have equivalent IDs as well.\n//! This turns \"is the focus anywhere inside this subtree\" into an O(1) check.\n//!\n//! The reason \"classnames\" are used is because I was hoping to add theming\n//! in the future with a syntax similar to CSS (simplified, however).\n//!\n//! # Example\n//!\n//! ```\n//! use edit::helpers::Size;\n//! use edit::input::Input;\n//! use edit::tui::*;\n//! use edit::{arena, arena_format};\n//!\n//! struct State {\n//! counter: i32,\n//! }\n//!\n//! fn main() {\n//! arena::init(128 * 1024 * 1024).unwrap();\n//!\n//! // Create a `Tui` instance which holds state across frames.\n//! let mut tui = Tui::new().unwrap();\n//! let mut state = State { counter: 0 };\n//! let input = Input::Resize(Size { width: 80, height: 24 });\n//!\n//! // Pass the input to the TUI.\n//! {\n//! let mut ctx = tui.create_context(Some(input));\n//! draw(&mut ctx, &mut state);\n//! }\n//!\n//! // Continue until the layout has settled.\n//! while tui.needs_settling() {\n//! let mut ctx = tui.create_context(None);\n//! draw(&mut ctx, &mut state);\n//! }\n//!\n//! // Render the output.\n//! let scratch = arena::scratch_arena(None);\n//! let output = tui.render(&*scratch);\n//! println!(\"{}\", output);\n//! }\n//!\n//! fn draw(ctx: &mut Context, state: &mut State) {\n//! ctx.table_begin(\"classname\");\n//! {\n//! ctx.table_next_row();\n//!\n//! // Thanks to the lack of callbacks, we can use a primitive\n//! // if condition here, as well as in any potential C code.\n//! if ctx.button(\"button\", \"Click me!\", ButtonStyle::default()) {\n//! state.counter += 1;\n//! }\n//!\n//! // Similarly, formatting and showing labels is straightforward.\n//! // It's impossible to forget updating the label this way.\n//! ctx.label(\"label\", &arena_format!(ctx.arena(), \"Counter: {}\", state.counter));\n//! }\n//! ctx.table_end();\n//! }\n//! ```\n\nuse std::arch::breakpoint;\n#[cfg(debug_assertions)]\nuse std::collections::HashSet;\nuse std::fmt::Write as _;\nuse std::{iter, mem, ptr, time};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::buffer::{CursorMovement, MoveLineDirection, RcTextBuffer, TextBuffer, TextBufferCell};\nuse crate::cell::*;\nuse crate::clipboard::Clipboard;\nuse crate::document::WriteableDocument;\nuse crate::framebuffer::{Attributes, Framebuffer, INDEXED_COLORS_COUNT, IndexedColor};\nuse crate::hash::*;\nuse crate::helpers::*;\nuse crate::input::{InputKeyMod, kbmod, vk};\nuse crate::{apperr, arena_format, input, simd, unicode};\n\nconst ROOT_ID: u64 = 0x14057B7EF767814F; // Knuth's MMIX constant\nconst SHIFT_TAB: InputKey = vk::TAB.with_modifiers(kbmod::SHIFT);\nconst KBMOD_FOR_WORD_NAV: InputKeyMod =\n if cfg!(target_os = \"macos\") { kbmod::ALT } else { kbmod::CTRL };\n\ntype Input<'input> = input::Input<'input>;\ntype InputKey = input::InputKey;\ntype InputMouseState = input::InputMouseState;\n\n/// Since [`TextBuffer`] creation and management is expensive,\n/// we cache instances of them for reuse between frames.\n/// This is used for [`Context::editline()`].\nstruct CachedTextBuffer {\n node_id: u64,\n editor: RcTextBuffer,\n seen: bool,\n}\n\n/// Since [`Context::editline()`] and [`Context::textarea()`]\n/// do almost the same thing, this abstracts over the two.\nenum TextBufferPayload<'a> {\n Editline(&'a mut dyn WriteableDocument),\n Textarea(RcTextBuffer),\n}\n\n/// In order for the TUI to show the correct Ctrl/Alt/Shift\n/// translations, this struct lets you set them.\npub struct ModifierTranslations {\n pub ctrl: &'static str,\n pub alt: &'static str,\n pub shift: &'static str,\n}\n\n/// Controls to which node the floater is anchored.\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub enum Anchor {\n /// The floater is attached relative to the node created last.\n #[default]\n Last,\n /// The floater is attached relative to the current node (= parent of new nodes).\n Parent,\n /// The floater is attached relative to the root node (= usually the viewport).\n Root,\n}\n\n/// Controls the position of the floater. See [`Context::attr_float`].\n#[derive(Default)]\npub struct FloatSpec {\n /// Controls to which node the floater is anchored.\n pub anchor: Anchor,\n // Specifies the origin of the container relative to the container size. [0, 1]\n pub gravity_x: f32,\n pub gravity_y: f32,\n // Specifies an offset from the origin in cells.\n pub offset_x: f32,\n pub offset_y: f32,\n}\n\n/// Informs you about the change that was made to the list selection.\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum ListSelection {\n /// The selection wasn't changed.\n Unchanged,\n /// The selection was changed to the current list item.\n Selected,\n /// The selection was changed to the current list item\n /// *and* the item was also activated (Enter or Double-click).\n Activated,\n}\n\n/// Controls the position of a node relative to its parent.\n#[derive(Default)]\npub enum Position {\n /// The child is stretched to fill the parent.\n #[default]\n Stretch,\n /// The child is positioned at the left edge of the parent.\n Left,\n /// The child is positioned at the center of the parent.\n Center,\n /// The child is positioned at the right edge of the parent.\n Right,\n}\n\n/// Controls the text overflow behavior of a label\n/// when the text doesn't fit the container.\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub enum Overflow {\n /// Text is simply cut off when it doesn't fit.\n #[default]\n Clip,\n /// An ellipsis is shown at the end of the text.\n TruncateHead,\n /// An ellipsis is shown in the middle of the text.\n TruncateMiddle,\n /// An ellipsis is shown at the beginning of the text.\n TruncateTail,\n}\n\n/// Controls the style with which a button label renders\n#[derive(Clone, Copy)]\npub struct ButtonStyle {\n accelerator: Option,\n checked: Option,\n bracketed: bool,\n}\n\nimpl ButtonStyle {\n /// Draw an accelerator label: `[_E_xample button]` or `[Example button(X)]`\n ///\n /// Must provide an upper-case ASCII character.\n pub fn accelerator(self, char: char) -> Self {\n Self { accelerator: Some(char), ..self }\n }\n /// Draw a checkbox prefix: `[🗹 Example Button]`\n pub fn checked(self, checked: bool) -> Self {\n Self { checked: Some(checked), ..self }\n }\n /// Draw with or without brackets: `[Example Button]` or `Example Button`\n pub fn bracketed(self, bracketed: bool) -> Self {\n Self { bracketed, ..self }\n }\n}\n\nimpl Default for ButtonStyle {\n fn default() -> Self {\n Self {\n accelerator: None,\n checked: None,\n bracketed: true, // Default style for most buttons. Brackets may be disabled e.g. for buttons in menus\n }\n }\n}\n\n/// There's two types of lifetimes the TUI code needs to manage:\n/// * Across frames\n/// * Per frame\n///\n/// [`Tui`] manages the first one. It's also the entrypoint for\n/// everything else you may want to do.\npub struct Tui {\n /// Arena used for the previous frame.\n arena_prev: Arena,\n /// Arena used for the current frame.\n arena_next: Arena,\n /// The UI tree built in the previous frame.\n /// This refers to memory in `arena_prev`.\n prev_tree: Tree<'static>,\n /// A hashmap of all nodes built in the previous frame.\n /// This refers to memory in `arena_prev`.\n prev_node_map: NodeMap<'static>,\n /// The framebuffer used for rendering.\n framebuffer: Framebuffer,\n\n modifier_translations: ModifierTranslations,\n floater_default_bg: u32,\n floater_default_fg: u32,\n modal_default_bg: u32,\n modal_default_fg: u32,\n\n /// Last known terminal size.\n ///\n /// This lives here instead of [`Context`], because we need to\n /// track the state across frames and input events.\n /// This also applies to the remaining members in this block below.\n size: Size,\n /// Last known mouse position.\n mouse_position: Point,\n /// Between mouse down and up, the position where the mouse was pressed.\n /// Otherwise, this contains Point::MIN.\n mouse_down_position: Point,\n /// Node ID of the node that was clicked on.\n /// Used for tracking drag targets.\n left_mouse_down_target: u64,\n /// Timestamp of the last mouse up event.\n /// Used for tracking double/triple clicks.\n mouse_up_timestamp: std::time::Instant,\n /// The current mouse state.\n mouse_state: InputMouseState,\n /// Whether the mouse is currently being dragged.\n mouse_is_drag: bool,\n /// The number of clicks that have happened in a row.\n /// Gets reset when the mouse was released for a while.\n mouse_click_counter: CoordType,\n /// The path to the node that was clicked on.\n mouse_down_node_path: Vec,\n /// The position of the first click in a double/triple click series.\n first_click_position: Point,\n /// The node ID of the node that was first clicked on\n /// in a double/triple click series.\n first_click_target: u64,\n\n /// Path to the currently focused node.\n focused_node_path: Vec,\n /// Contains the last element in [`Tui::focused_node_path`].\n /// This way we can track if the focus changed, because then we\n /// need to scroll the node into view if it's within a scrollarea.\n focused_node_for_scrolling: u64,\n\n /// A list of cached text buffers used for [`Context::editline()`].\n cached_text_buffers: Vec,\n\n /// The clipboard contents.\n clipboard: Clipboard,\n\n settling_have: i32,\n settling_want: i32,\n read_timeout: time::Duration,\n}\n\nimpl Tui {\n /// Creates a new [`Tui`] instance for storing state across frames.\n pub fn new() -> apperr::Result {\n let arena_prev = Arena::new(128 * MEBI)?;\n let arena_next = Arena::new(128 * MEBI)?;\n // SAFETY: Since `prev_tree` refers to `arena_prev`/`arena_next`, from its POV the lifetime\n // is `'static`, requiring us to use `transmute` to circumvent the borrow checker.\n let prev_tree = Tree::new(unsafe { mem::transmute::<&Arena, &Arena>(&arena_next) });\n\n let mut tui = Self {\n arena_prev,\n arena_next,\n prev_tree,\n prev_node_map: Default::default(),\n framebuffer: Framebuffer::new(),\n\n modifier_translations: ModifierTranslations {\n ctrl: \"Ctrl\",\n alt: \"Alt\",\n shift: \"Shift\",\n },\n floater_default_bg: 0,\n floater_default_fg: 0,\n modal_default_bg: 0,\n modal_default_fg: 0,\n\n size: Size { width: 0, height: 0 },\n mouse_position: Point::MIN,\n mouse_down_position: Point::MIN,\n left_mouse_down_target: 0,\n mouse_up_timestamp: std::time::Instant::now(),\n mouse_state: InputMouseState::None,\n mouse_is_drag: false,\n mouse_click_counter: 0,\n mouse_down_node_path: Vec::with_capacity(16),\n first_click_position: Point::MIN,\n first_click_target: 0,\n\n focused_node_path: Vec::with_capacity(16),\n focused_node_for_scrolling: ROOT_ID,\n\n cached_text_buffers: Vec::with_capacity(16),\n\n clipboard: Default::default(),\n\n settling_have: 0,\n settling_want: 0,\n read_timeout: time::Duration::MAX,\n };\n Self::clean_node_path(&mut tui.mouse_down_node_path);\n Self::clean_node_path(&mut tui.focused_node_path);\n Ok(tui)\n }\n\n /// Sets up the framebuffer's color palette.\n pub fn setup_indexed_colors(&mut self, colors: [u32; INDEXED_COLORS_COUNT]) {\n self.framebuffer.set_indexed_colors(colors);\n }\n\n /// Set up translations for Ctrl/Alt/Shift modifiers.\n pub fn setup_modifier_translations(&mut self, translations: ModifierTranslations) {\n self.modifier_translations = translations;\n }\n\n /// Set the default background color for floaters (dropdowns, etc.).\n pub fn set_floater_default_bg(&mut self, color: u32) {\n self.floater_default_bg = color;\n }\n\n /// Set the default foreground color for floaters (dropdowns, etc.).\n pub fn set_floater_default_fg(&mut self, color: u32) {\n self.floater_default_fg = color;\n }\n\n /// Set the default background color for modals.\n pub fn set_modal_default_bg(&mut self, color: u32) {\n self.modal_default_bg = color;\n }\n\n /// Set the default foreground color for modals.\n pub fn set_modal_default_fg(&mut self, color: u32) {\n self.modal_default_fg = color;\n }\n\n /// If the TUI is currently running animations, etc.,\n /// this will return a timeout smaller than [`time::Duration::MAX`].\n pub fn read_timeout(&mut self) -> time::Duration {\n mem::replace(&mut self.read_timeout, time::Duration::MAX)\n }\n\n /// Returns the viewport size.\n pub fn size(&self) -> Size {\n // We don't use the size stored in the framebuffer, because until\n // `render()` is called, the framebuffer will use a stale size.\n self.size\n }\n\n /// Returns an indexed color from the framebuffer.\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.framebuffer.indexed(index)\n }\n\n /// Returns an indexed color from the framebuffer with the given alpha.\n /// See [`Framebuffer::indexed_alpha()`].\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n self.framebuffer.indexed_alpha(index, numerator, denominator)\n }\n\n /// Returns a color in contrast with the given color.\n /// See [`Framebuffer::contrasted()`].\n pub fn contrasted(&self, color: u32) -> u32 {\n self.framebuffer.contrasted(color)\n }\n\n /// Returns the clipboard.\n pub fn clipboard_ref(&self) -> &Clipboard {\n &self.clipboard\n }\n\n /// Returns the clipboard (mutable).\n pub fn clipboard_mut(&mut self) -> &mut Clipboard {\n &mut self.clipboard\n }\n\n /// Starts a new frame and returns a [`Context`] for it.\n pub fn create_context<'a, 'input>(\n &'a mut self,\n input: Option>,\n ) -> Context<'a, 'input> {\n // SAFETY: Since we have a unique `&mut self`, nothing is holding onto `arena_prev`,\n // which will become `arena_next` and get reset. It's safe to reset and reuse its memory.\n mem::swap(&mut self.arena_prev, &mut self.arena_next);\n unsafe { self.arena_next.reset(0) };\n\n // In the input handler below we transformed a mouse up into a release event.\n // Now, a frame later, we must reset it back to none, to stop it from triggering things.\n // Same for Scroll events.\n if self.mouse_state > InputMouseState::Right {\n self.mouse_down_position = Point::MIN;\n self.mouse_down_node_path.clear();\n self.left_mouse_down_target = 0;\n self.mouse_state = InputMouseState::None;\n self.mouse_is_drag = false;\n }\n\n let now = std::time::Instant::now();\n let mut input_text = None;\n let mut input_keyboard = None;\n let mut input_mouse_modifiers = kbmod::NONE;\n let mut input_mouse_click = 0;\n let mut input_scroll_delta = Point { x: 0, y: 0 };\n // `input_consumed` should be `true` if we're in the settling phase which is indicated by\n // `self.needs_settling() == true`. However, there's a possibility for it being true from\n // a previous frame, and we do have fresh new input. In that case want `input_consumed`\n // to be false of course which is ensured by checking for `input.is_none()`.\n let input_consumed = self.needs_settling() && input.is_none();\n\n if self.scroll_to_focused() {\n self.needs_more_settling();\n }\n\n match input {\n None => {}\n Some(Input::Resize(resize)) => {\n assert!(resize.width > 0 && resize.height > 0);\n assert!(resize.width < 32768 && resize.height < 32768);\n self.size = resize;\n }\n Some(Input::Text(text)) => {\n input_text = Some(text);\n // TODO: the .len()==1 check causes us to ignore keyboard inputs that are faster than we process them.\n // For instance, imagine the user presses \"A\" twice and we happen to read it in a single chunk.\n // This causes us to ignore the keyboard input here. We need a way to inform the caller over\n // how much of the input text we actually processed in a single frame. Or perhaps we could use\n // the needs_settling logic?\n if text.len() == 1 {\n let ch = text.as_bytes()[0];\n input_keyboard = InputKey::from_ascii(ch as char)\n }\n }\n Some(Input::Paste(paste)) => {\n let clipboard = self.clipboard_mut();\n clipboard.write(paste);\n clipboard.mark_as_synchronized();\n input_keyboard = Some(kbmod::CTRL | vk::V);\n }\n Some(Input::Keyboard(keyboard)) => {\n input_keyboard = Some(keyboard);\n }\n Some(Input::Mouse(mouse)) => {\n let mut next_state = mouse.state;\n let next_position = mouse.position;\n let next_scroll = mouse.scroll;\n let mouse_down = self.mouse_state == InputMouseState::None\n && next_state != InputMouseState::None;\n let mouse_up = self.mouse_state != InputMouseState::None\n && next_state == InputMouseState::None;\n let is_drag = self.mouse_state == InputMouseState::Left\n && next_state == InputMouseState::Left\n && next_position != self.mouse_position;\n\n let mut hovered_node = None; // Needed for `mouse_down`\n let mut focused_node = None; // Needed for `mouse_down` and `is_click`\n if mouse_down || mouse_up {\n // Roots (aka windows) are ordered in Z order, so we iterate\n // them in reverse order, from topmost to bottommost.\n for root in self.prev_tree.iterate_roots_rev() {\n // Find the node that contains the cursor.\n Tree::visit_all(root, root, true, |node| {\n let n = node.borrow();\n if !n.outer_clipped.contains(next_position) {\n // Skip the entire sub-tree, because it doesn't contain the cursor.\n return VisitControl::SkipChildren;\n }\n hovered_node = Some(node);\n if n.attributes.focusable {\n focused_node = Some(node);\n }\n VisitControl::Continue\n });\n\n // This root/window contains the cursor.\n // We don't care about any lower roots.\n if hovered_node.is_some() {\n break;\n }\n\n // This root is modal and swallows all clicks,\n // no matter whether the click was inside it or not.\n if matches!(root.borrow().content, NodeContent::Modal(_)) {\n break;\n }\n }\n }\n\n if mouse_down {\n // Transition from no mouse input to some mouse input --> Record the mouse down position.\n Self::build_node_path(hovered_node, &mut self.mouse_down_node_path);\n\n // On left-mouse-down we change focus.\n let mut target = 0;\n if next_state == InputMouseState::Left {\n target = focused_node.map_or(0, |n| n.borrow().id);\n Self::build_node_path(focused_node, &mut self.focused_node_path);\n self.needs_more_settling(); // See `needs_more_settling()`.\n }\n\n // Double-/Triple-/Etc.-clicks are triggered on mouse-down,\n // unlike the first initial click, which is triggered on mouse-up.\n if self.mouse_click_counter != 0 {\n if self.first_click_target != target\n || self.first_click_position != next_position\n || (now - self.mouse_up_timestamp)\n > std::time::Duration::from_millis(500)\n {\n // If the cursor moved / the focus changed in between, or if the user did a slow click,\n // we reset the click counter. On mouse-up it'll transition to a regular click.\n self.mouse_click_counter = 0;\n self.first_click_position = Point::MIN;\n self.first_click_target = 0;\n } else {\n self.mouse_click_counter += 1;\n input_mouse_click = self.mouse_click_counter;\n };\n }\n\n // Gets reset at the start of this function.\n self.left_mouse_down_target = target;\n self.mouse_down_position = next_position;\n } else if mouse_up {\n // Transition from some mouse input to no mouse input --> The mouse button was released.\n next_state = InputMouseState::Release;\n\n let target = focused_node.map_or(0, |n| n.borrow().id);\n\n if self.left_mouse_down_target == 0 || self.left_mouse_down_target != target {\n // If `left_mouse_down_target == 0`, then it wasn't a left-click, in which case\n // the target gets reset. Same, if the focus changed in between any clicks.\n self.mouse_click_counter = 0;\n self.first_click_position = Point::MIN;\n self.first_click_target = 0;\n } else if self.mouse_click_counter == 0 {\n // No focus change, and no previous clicks? This is an initial, regular click.\n self.mouse_click_counter = 1;\n self.first_click_position = self.mouse_down_position;\n self.first_click_target = target;\n input_mouse_click = 1;\n }\n\n self.mouse_up_timestamp = now;\n } else if is_drag {\n self.mouse_is_drag = true;\n }\n\n input_mouse_modifiers = mouse.modifiers;\n input_scroll_delta = next_scroll;\n self.mouse_position = next_position;\n self.mouse_state = next_state;\n }\n }\n\n if !input_consumed {\n // Every time there's input, we naturally need to re-render at least once.\n self.settling_have = 0;\n self.settling_want = 1;\n }\n\n // TODO: There should be a way to do this without unsafe.\n // Allocating from the arena borrows the arena, and so allocating the tree here borrows self.\n // This conflicts with us passing a mutable reference to `self` into the struct below.\n let tree = Tree::new(unsafe { mem::transmute::<&Arena, &Arena>(&self.arena_next) });\n\n Context {\n tui: self,\n\n input_text,\n input_keyboard,\n input_mouse_modifiers,\n input_mouse_click,\n input_scroll_delta,\n input_consumed,\n\n tree,\n last_modal: None,\n focused_node: None,\n next_block_id_mixin: 0,\n needs_settling: false,\n\n #[cfg(debug_assertions)]\n seen_ids: HashSet::new(),\n }\n }\n\n fn report_context_completion<'a>(&'a mut self, ctx: &mut Context<'a, '_>) {\n // If this hits, you forgot to block_end() somewhere. The best way to figure\n // out where is to do a binary search of commenting out code in main.rs.\n debug_assert!(\n ctx.tree.current_node.borrow().stack_parent.is_none(),\n \"Dangling parent! Did you miss a block_end?\"\n );\n\n // End the root node.\n ctx.block_end();\n\n // Ensure that focus doesn't escape the active modal.\n if let Some(node) = ctx.last_modal\n && !self.is_subtree_focused(&node.borrow())\n {\n ctx.steal_focus_for(node);\n }\n\n // If nodes have appeared or disappeared, we need to re-render.\n // Same, if the focus has changed (= changes the highlight color, etc.).\n let mut needs_settling = ctx.needs_settling;\n needs_settling |= self.prev_tree.checksum != ctx.tree.checksum;\n\n // Adopt the new tree and recalculate the node hashmap.\n //\n // SAFETY: The memory used by the tree is owned by the `self.arena_next` right now.\n // Stealing the tree here thus doesn't need to copy any memory unless someone resets the arena.\n // (The arena is reset in `reset()` above.)\n unsafe {\n self.prev_tree = mem::transmute_copy(&ctx.tree);\n self.prev_node_map = NodeMap::new(mem::transmute(&self.arena_next), &self.prev_tree);\n }\n\n let mut focus_path_pop_min = 0;\n // If the user pressed Escape, we move the focus to a parent node.\n if !ctx.input_consumed && ctx.consume_shortcut(vk::ESCAPE) {\n focus_path_pop_min = 1;\n }\n\n // Remove any unknown nodes from the focus path.\n // It's important that we do this after the tree has been swapped out,\n // so that pop_focusable_node() has access to the newest version of the tree.\n needs_settling |= self.pop_focusable_node(focus_path_pop_min);\n\n // `needs_more_settling()` depends on the current value\n // of `settling_have` and so we increment it first.\n self.settling_have += 1;\n\n if needs_settling {\n self.needs_more_settling();\n }\n\n // Remove cached text editors that are no longer in use.\n self.cached_text_buffers.retain(|c| c.seen);\n\n for root in Tree::iterate_siblings(Some(self.prev_tree.root_first)) {\n let mut root = root.borrow_mut();\n root.compute_intrinsic_size();\n }\n\n let viewport = self.size.as_rect();\n\n for root in Tree::iterate_siblings(Some(self.prev_tree.root_first)) {\n let mut root = root.borrow_mut();\n let root = &mut *root;\n\n if let Some(float) = &root.attributes.float {\n let mut x = 0;\n let mut y = 0;\n\n if let Some(node) = root.parent {\n let node = node.borrow();\n x = node.outer.left;\n y = node.outer.top;\n }\n\n let size = root.intrinsic_to_outer();\n\n x += (float.offset_x - float.gravity_x * size.width as f32) as CoordType;\n y += (float.offset_y - float.gravity_y * size.height as f32) as CoordType;\n\n root.outer.left = x;\n root.outer.top = y;\n root.outer.right = x + size.width;\n root.outer.bottom = y + size.height;\n root.outer = root.outer.intersect(viewport);\n } else {\n root.outer = viewport;\n }\n\n root.inner = root.outer_to_inner(root.outer);\n root.outer_clipped = root.outer;\n root.inner_clipped = root.inner;\n\n let outer = root.outer;\n root.layout_children(outer);\n }\n }\n\n fn build_node_path(node: Option<&NodeCell>, path: &mut Vec) {\n path.clear();\n if let Some(mut node) = node {\n loop {\n let n = node.borrow();\n path.push(n.id);\n node = match n.parent {\n Some(parent) => parent,\n None => break,\n };\n }\n path.reverse();\n } else {\n path.push(ROOT_ID);\n }\n }\n\n fn clean_node_path(path: &mut Vec) {\n Self::build_node_path(None, path);\n }\n\n /// After you finished processing all input, continue redrawing your UI until this returns false.\n pub fn needs_settling(&mut self) -> bool {\n self.settling_have <= self.settling_want\n }\n\n fn needs_more_settling(&mut self) {\n // If the focus has changed, the new node may need to be re-rendered.\n // Same, every time we encounter a previously unknown node via `get_prev_node`,\n // because that means it likely failed to get crucial information such as the layout size.\n if cfg!(debug_assertions) && self.settling_have == 15 {\n breakpoint();\n }\n self.settling_want = (self.settling_have + 1).min(20);\n }\n\n /// Renders the last frame into the framebuffer and returns the VT output.\n pub fn render<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n self.framebuffer.flip(self.size);\n for child in self.prev_tree.iterate_roots() {\n let mut child = child.borrow_mut();\n self.render_node(&mut child);\n }\n self.framebuffer.render(arena)\n }\n\n /// Recursively renders each node and its children.\n #[allow(clippy::only_used_in_recursion)]\n fn render_node(&mut self, node: &mut Node) {\n let outer_clipped = node.outer_clipped;\n if outer_clipped.is_empty() {\n return;\n }\n\n let scratch = scratch_arena(None);\n\n if node.attributes.bordered {\n // ┌────┐\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('┌');\n fill.push_repeat('─', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('┐');\n self.framebuffer.replace_text(\n outer_clipped.top,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n\n // │ │\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('│');\n fill.push_repeat(' ', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('│');\n\n for y in outer_clipped.top + 1..outer_clipped.bottom - 1 {\n self.framebuffer.replace_text(\n y,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n // └────┘\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('└');\n fill.push_repeat('─', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('┘');\n self.framebuffer.replace_text(\n outer_clipped.bottom - 1,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n if node.attributes.float.is_some() {\n if !node.attributes.bordered {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push_repeat(' ', (outer_clipped.right - outer_clipped.left) as usize);\n\n for y in outer_clipped.top..outer_clipped.bottom {\n self.framebuffer.replace_text(\n y,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n self.framebuffer.replace_attr(outer_clipped, Attributes::All, Attributes::None);\n\n if matches!(node.content, NodeContent::Modal(_)) {\n let rect =\n Rect { left: 0, top: 0, right: self.size.width, bottom: self.size.height };\n let dim = self.indexed_alpha(IndexedColor::Background, 1, 2);\n self.framebuffer.blend_bg(rect, dim);\n self.framebuffer.blend_fg(rect, dim);\n }\n }\n\n self.framebuffer.blend_bg(outer_clipped, node.attributes.bg);\n self.framebuffer.blend_fg(outer_clipped, node.attributes.fg);\n\n if node.attributes.reverse {\n self.framebuffer.reverse(outer_clipped);\n }\n\n let inner = node.inner;\n let inner_clipped = node.inner_clipped;\n if inner_clipped.is_empty() {\n return;\n }\n\n match &mut node.content {\n NodeContent::Modal(title) => {\n if !title.is_empty() {\n self.framebuffer.replace_text(\n node.outer.top,\n node.outer.left + 2,\n node.outer.right - 1,\n title,\n );\n }\n }\n NodeContent::Text(content) => self.render_styled_text(\n inner,\n node.intrinsic_size.width,\n &content.text,\n &content.chunks,\n content.overflow,\n ),\n NodeContent::Textarea(tc) => {\n let mut tb = tc.buffer.borrow_mut();\n let mut destination = Rect {\n left: inner_clipped.left,\n top: inner_clipped.top,\n right: inner_clipped.right,\n bottom: inner_clipped.bottom,\n };\n\n if !tc.single_line {\n // Account for the scrollbar.\n destination.right -= 1;\n }\n\n if let Some(res) =\n tb.render(tc.scroll_offset, destination, tc.has_focus, &mut self.framebuffer)\n {\n tc.scroll_offset_x_max = res.visual_pos_x_max;\n }\n\n if !tc.single_line {\n // Render the scrollbar.\n let track = Rect {\n left: inner_clipped.right - 1,\n top: inner_clipped.top,\n right: inner_clipped.right,\n bottom: inner_clipped.bottom,\n };\n tc.thumb_height = self.framebuffer.draw_scrollbar(\n inner_clipped,\n track,\n tc.scroll_offset.y,\n tb.visual_line_count() + inner.height() - 1,\n );\n }\n }\n NodeContent::Scrollarea(sc) => {\n let content = node.children.first.unwrap().borrow();\n let track = Rect {\n left: inner.right,\n top: inner.top,\n right: inner.right + 1,\n bottom: inner.bottom,\n };\n sc.thumb_height = self.framebuffer.draw_scrollbar(\n outer_clipped,\n track,\n sc.scroll_offset.y,\n content.intrinsic_size.height,\n );\n }\n _ => {}\n }\n\n for child in Tree::iterate_siblings(node.children.first) {\n let mut child = child.borrow_mut();\n self.render_node(&mut child);\n }\n }\n\n fn render_styled_text(\n &mut self,\n target: Rect,\n actual_width: CoordType,\n text: &str,\n chunks: &[StyledTextChunk],\n overflow: Overflow,\n ) {\n let target_width = target.width();\n // The section of `text` that is skipped by the ellipsis.\n let mut skipped = 0..0;\n // The number of columns skipped by the ellipsis.\n let mut skipped_cols = 0;\n\n if overflow == Overflow::Clip || target_width >= actual_width {\n self.framebuffer.replace_text(target.top, target.left, target.right, text);\n } else {\n let bytes = text.as_bytes();\n let mut cfg = unicode::MeasurementConfig::new(&bytes);\n\n match overflow {\n Overflow::Clip => unreachable!(),\n Overflow::TruncateHead => {\n let beg = cfg.goto_visual(Point { x: actual_width - target_width + 1, y: 0 });\n skipped = 0..beg.offset;\n skipped_cols = beg.visual_pos.x - 1;\n }\n Overflow::TruncateMiddle => {\n let mid_beg_x = (target_width - 1) / 2;\n let mid_end_x = actual_width - target_width / 2;\n let beg = cfg.goto_visual(Point { x: mid_beg_x, y: 0 });\n let end = cfg.goto_visual(Point { x: mid_end_x, y: 0 });\n skipped = beg.offset..end.offset;\n skipped_cols = end.visual_pos.x - beg.visual_pos.x - 1;\n }\n Overflow::TruncateTail => {\n let end = cfg.goto_visual(Point { x: target_width - 1, y: 0 });\n skipped_cols = actual_width - end.visual_pos.x - 1;\n skipped = end.offset..text.len();\n }\n }\n\n let scratch = scratch_arena(None);\n\n let mut modified = ArenaString::new_in(&scratch);\n modified.reserve(text.len() + 3);\n modified.push_str(&text[..skipped.start]);\n modified.push('…');\n modified.push_str(&text[skipped.end..]);\n\n self.framebuffer.replace_text(target.top, target.left, target.right, &modified);\n }\n\n if !chunks.is_empty() {\n let bytes = text.as_bytes();\n let mut cfg = unicode::MeasurementConfig::new(&bytes).with_cursor(unicode::Cursor {\n visual_pos: Point { x: target.left, y: 0 },\n ..Default::default()\n });\n\n let mut iter = chunks.iter().peekable();\n\n while let Some(chunk) = iter.next() {\n let beg = chunk.offset;\n let end = iter.peek().map_or(text.len(), |c| c.offset);\n\n if beg >= skipped.start && end <= skipped.end {\n // Chunk is fully inside the text skipped by the ellipsis.\n // We don't need to render it at all.\n continue;\n }\n\n if beg < skipped.start {\n let beg = cfg.goto_offset(beg).visual_pos.x;\n let end = cfg.goto_offset(end.min(skipped.start)).visual_pos.x;\n let rect =\n Rect { left: beg, top: target.top, right: end, bottom: target.bottom };\n self.framebuffer.blend_fg(rect, chunk.fg);\n self.framebuffer.replace_attr(rect, chunk.attr, chunk.attr);\n }\n\n if end > skipped.end {\n let beg = cfg.goto_offset(beg.max(skipped.end)).visual_pos.x - skipped_cols;\n let end = cfg.goto_offset(end).visual_pos.x - skipped_cols;\n let rect =\n Rect { left: beg, top: target.top, right: end, bottom: target.bottom };\n self.framebuffer.blend_fg(rect, chunk.fg);\n self.framebuffer.replace_attr(rect, chunk.attr, chunk.attr);\n }\n }\n }\n }\n\n /// Outputs a debug string of the layout and focus tree.\n pub fn debug_layout<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n let mut result = ArenaString::new_in(arena);\n result.push_str(\"general:\\r\\n- focus_path:\\r\\n\");\n\n for &id in &self.focused_node_path {\n _ = write!(result, \" - {id:016x}\\r\\n\");\n }\n\n result.push_str(\"\\r\\ntree:\\r\\n\");\n\n for root in self.prev_tree.iterate_roots() {\n Tree::visit_all(root, root, true, |node| {\n let node = node.borrow();\n let depth = node.depth;\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \"- id: {:016x}\\r\\n\", node.id);\n\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" classname: {}\\r\\n\", node.classname);\n\n if depth == 0\n && let Some(parent) = node.parent\n {\n let parent = parent.borrow();\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" parent: {:016x}\\r\\n\", parent.id);\n }\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" intrinsic: {{{}, {}}}\\r\\n\",\n node.intrinsic_size.width, node.intrinsic_size.height\n );\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" outer: {{{}, {}, {}, {}}}\\r\\n\",\n node.outer.left, node.outer.top, node.outer.right, node.outer.bottom\n );\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" inner: {{{}, {}, {}, {}}}\\r\\n\",\n node.inner.left, node.inner.top, node.inner.right, node.inner.bottom\n );\n\n if node.attributes.bordered {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" bordered: true\\r\\n\");\n }\n\n if node.attributes.bg != 0 {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" bg: #{:08x}\\r\\n\", node.attributes.bg);\n }\n\n if node.attributes.fg != 0 {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" fg: #{:08x}\\r\\n\", node.attributes.fg);\n }\n\n if self.is_node_focused(node.id) {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" focused: true\\r\\n\");\n }\n\n match &node.content {\n NodeContent::Text(content) => {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" text: \\\"{}\\\"\\r\\n\", &content.text);\n }\n NodeContent::Textarea(content) => {\n let tb = content.buffer.borrow();\n let tb = &*tb;\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" textarea: {tb:p}\\r\\n\");\n }\n NodeContent::Scrollarea(..) => {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" scrollable: true\\r\\n\");\n }\n _ => {}\n }\n\n VisitControl::Continue\n });\n }\n\n result\n }\n\n fn was_mouse_down_on_node(&self, id: u64) -> bool {\n self.mouse_down_node_path.last() == Some(&id)\n }\n\n fn was_mouse_down_on_subtree(&self, node: &Node) -> bool {\n self.mouse_down_node_path.get(node.depth) == Some(&node.id)\n }\n\n fn is_node_focused(&self, id: u64) -> bool {\n // We construct the focused_node_path always with at least 1 element (the root id).\n unsafe { *self.focused_node_path.last().unwrap_unchecked() == id }\n }\n\n fn is_subtree_focused(&self, node: &Node) -> bool {\n self.focused_node_path.get(node.depth) == Some(&node.id)\n }\n\n fn is_subtree_focused_alt(&self, id: u64, depth: usize) -> bool {\n self.focused_node_path.get(depth) == Some(&id)\n }\n\n fn pop_focusable_node(&mut self, pop_minimum: usize) -> bool {\n let last_before = self.focused_node_path.last().cloned().unwrap_or(0);\n\n // Remove `pop_minimum`-many nodes from the end of the focus path.\n let path = &self.focused_node_path[..];\n let path = &path[..path.len().saturating_sub(pop_minimum)];\n let mut len = 0;\n\n for (i, &id) in path.iter().enumerate() {\n // Truncate the path so that it only contains nodes that still exist.\n let Some(node) = self.prev_node_map.get(id) else {\n break;\n };\n\n let n = node.borrow();\n // If the caller requested upward movement, pop out of the current focus void, if any.\n // This is kind of janky, to be fair.\n if pop_minimum != 0 && n.attributes.focus_void {\n break;\n }\n\n // Skip over those that aren't focusable.\n if n.attributes.focusable {\n // At this point `n.depth == i` should be true,\n // but I kind of don't want to rely on that.\n len = i + 1;\n }\n }\n\n self.focused_node_path.truncate(len);\n\n // If it's empty now, push `ROOT_ID` because there must always be >=1 element.\n if self.focused_node_path.is_empty() {\n self.focused_node_path.push(ROOT_ID);\n }\n\n // Return true if the focus path changed.\n let last_after = self.focused_node_path.last().cloned().unwrap_or(0);\n last_before != last_after\n }\n\n // Scroll the focused node(s) into view inside scrollviews\n fn scroll_to_focused(&mut self) -> bool {\n let focused_id = self.focused_node_path.last().cloned().unwrap_or(0);\n if self.focused_node_for_scrolling == focused_id {\n return false;\n }\n\n let Some(node) = self.prev_node_map.get(focused_id) else {\n // Node not found because we're using the old layout tree.\n // Retry in the next rendering loop.\n return true;\n };\n\n let mut node = node.borrow_mut();\n let mut scroll_to = node.outer;\n\n while node.parent.is_some() && node.attributes.float.is_none() {\n let n = &mut *node;\n if let NodeContent::Scrollarea(sc) = &mut n.content {\n let off_y = sc.scroll_offset.y.max(0);\n let mut y = off_y;\n y = y.min(scroll_to.top - n.inner.top + off_y);\n y = y.max(scroll_to.bottom - n.inner.bottom + off_y);\n sc.scroll_offset.y = y;\n scroll_to = n.outer;\n }\n node = node.parent.unwrap().borrow_mut();\n }\n\n self.focused_node_for_scrolling = focused_id;\n true\n }\n}\n\n/// Context is a temporary object that is created for each frame.\n/// Its primary purpose is to build a UI tree.\npub struct Context<'a, 'input> {\n tui: &'a mut Tui,\n\n /// Current text input, if any.\n input_text: Option<&'input str>,\n /// Current keyboard input, if any.\n input_keyboard: Option,\n input_mouse_modifiers: InputKeyMod,\n input_mouse_click: CoordType,\n /// By how much the mouse wheel was scrolled since the last frame.\n input_scroll_delta: Point,\n input_consumed: bool,\n\n tree: Tree<'a>,\n last_modal: Option<&'a NodeCell<'a>>,\n focused_node: Option<&'a NodeCell<'a>>,\n next_block_id_mixin: u64,\n needs_settling: bool,\n\n #[cfg(debug_assertions)]\n seen_ids: HashSet,\n}\n\nimpl<'a> Drop for Context<'a, '_> {\n fn drop(&mut self) {\n let tui: &'a mut Tui = unsafe { mem::transmute(&mut *self.tui) };\n tui.report_context_completion(self);\n }\n}\n\nimpl<'a> Context<'a, '_> {\n /// Get an arena for temporary allocations such as for [`arena_format`].\n pub fn arena(&self) -> &'a Arena {\n // TODO:\n // `Context` borrows `Tui` for lifetime 'a, so `self.tui` should be `&'a Tui`, right?\n // And if I do `&self.tui.arena` then that should be 'a too, right?\n // Searching for and failing to find a workaround for this was _very_ annoying.\n //\n // SAFETY: Both the returned reference and its allocations outlive &self.\n unsafe { mem::transmute::<&'_ Arena, &'a Arena>(&self.tui.arena_next) }\n }\n\n /// Returns the viewport size.\n pub fn size(&self) -> Size {\n self.tui.size()\n }\n\n /// Returns an indexed color from the framebuffer.\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.tui.framebuffer.indexed(index)\n }\n\n /// Returns an indexed color from the framebuffer with the given alpha.\n /// See [`Framebuffer::indexed_alpha()`].\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n self.tui.framebuffer.indexed_alpha(index, numerator, denominator)\n }\n\n /// Returns a color in contrast with the given color.\n /// See [`Framebuffer::contrasted()`].\n pub fn contrasted(&self, color: u32) -> u32 {\n self.tui.framebuffer.contrasted(color)\n }\n\n /// Returns the clipboard.\n pub fn clipboard_ref(&self) -> &Clipboard {\n &self.tui.clipboard\n }\n\n /// Returns the clipboard (mutable).\n pub fn clipboard_mut(&mut self) -> &mut Clipboard {\n &mut self.tui.clipboard\n }\n\n /// Tell the UI framework that your state changed and you need another layout pass.\n pub fn needs_rerender(&mut self) {\n // If this hits, the call stack is responsible is trying to deadlock you.\n debug_assert!(self.tui.settling_have < 15);\n self.needs_settling = true;\n }\n\n /// Begins a generic UI block (container) with a unique ID derived from the given `classname`.\n pub fn block_begin(&mut self, classname: &'static str) {\n let parent = self.tree.current_node;\n\n let mut id = hash_str(parent.borrow().id, classname);\n if self.next_block_id_mixin != 0 {\n id = hash(id, &self.next_block_id_mixin.to_ne_bytes());\n self.next_block_id_mixin = 0;\n }\n\n // If this hits, you have tried to create a block with the same ID as a previous one\n // somewhere up this call stack. Change the classname, or use next_block_id_mixin().\n // TODO: HashMap\n #[cfg(debug_assertions)]\n if !self.seen_ids.insert(id) {\n panic!(\"Duplicate node ID: {id:x}\");\n }\n\n let node = Tree::alloc_node(self.arena());\n {\n let mut n = node.borrow_mut();\n n.id = id;\n n.classname = classname;\n }\n\n self.tree.push_child(node);\n }\n\n /// Ends the current UI block, returning to its parent container.\n pub fn block_end(&mut self) {\n self.tree.pop_stack();\n self.block_end_move_focus();\n }\n\n fn block_end_move_focus(&mut self) {\n // At this point, it's more like \"focus_well?\" instead of \"focus_well!\".\n let focus_well = self.tree.last_node;\n\n // Remember the focused node, if any, because once the code below runs,\n // we need it for the `Tree::visit_all` call.\n if self.is_focused() {\n self.focused_node = Some(focus_well);\n }\n\n // The mere fact that there's a `focused_node` indicates that we're the\n // first `block_end()` call that's a focus well and also contains the focus.\n let Some(focused) = self.focused_node else {\n return;\n };\n\n // Filter down to nodes that are focus wells and contain the focus. They're\n // basically the \"tab container\". We test for the node depth to ensure that\n // we don't accidentally pick a focus well next to or inside the focused node.\n {\n let n = focus_well.borrow();\n if !n.attributes.focus_well || n.depth > focused.borrow().depth {\n return;\n }\n }\n\n // Filter down to Tab/Shift+Tab inputs.\n if self.input_consumed {\n return;\n }\n let Some(input) = self.input_keyboard else {\n return;\n };\n if !matches!(input, SHIFT_TAB | vk::TAB) {\n return;\n }\n\n let forward = input == vk::TAB;\n let mut focused_start = focused;\n let mut focused_next = focused;\n\n // We may be in a focus void right now (= doesn't want to be tabbed into),\n // so first we must go up the tree until we're outside of it.\n loop {\n if ptr::eq(focused_start, focus_well) {\n // If we hit the root / focus well, we weren't in a focus void,\n // and can reset `focused_before` to the current focused node.\n focused_start = focused;\n break;\n }\n\n focused_start = focused_start.borrow().parent.unwrap();\n if focused_start.borrow().attributes.focus_void {\n break;\n }\n }\n\n Tree::visit_all(focus_well, focused_start, forward, |node| {\n let n = node.borrow();\n if n.attributes.focusable && !ptr::eq(node, focused_start) {\n focused_next = node;\n VisitControl::Stop\n } else if n.attributes.focus_void {\n VisitControl::SkipChildren\n } else {\n VisitControl::Continue\n }\n });\n\n if ptr::eq(focused_next, focused_start) {\n return;\n }\n\n Tui::build_node_path(Some(focused_next), &mut self.tui.focused_node_path);\n self.set_input_consumed();\n self.needs_rerender();\n }\n\n /// Mixes in an extra value to the next UI block's ID for uniqueness.\n /// Use this when you build a list of items with the same classname.\n pub fn next_block_id_mixin(&mut self, id: u64) {\n self.next_block_id_mixin = id;\n }\n\n fn attr_focusable(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focusable = true;\n }\n\n /// If this is the first time the current node is being drawn,\n /// it'll steal the active focus.\n pub fn focus_on_first_present(&mut self) {\n let steal = {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focusable = true;\n self.tui.prev_node_map.get(last_node.id).is_none()\n };\n if steal {\n self.steal_focus();\n }\n }\n\n /// Steals the focus unconditionally.\n pub fn steal_focus(&mut self) {\n self.steal_focus_for(self.tree.last_node);\n }\n\n fn steal_focus_for(&mut self, node: &NodeCell<'a>) {\n if !self.tui.is_node_focused(node.borrow().id) {\n Tui::build_node_path(Some(node), &mut self.tui.focused_node_path);\n self.needs_rerender();\n }\n }\n\n /// If the current node owns the focus, it'll be given to the parent.\n pub fn toss_focus_up(&mut self) {\n if self.tui.pop_focusable_node(1) {\n self.needs_rerender();\n }\n }\n\n /// If the parent node owns the focus, it'll be given to the current node.\n pub fn inherit_focus(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n let Some(parent) = last_node.parent else {\n return;\n };\n\n last_node.attributes.focusable = true;\n\n // Mark the parent as focusable, so that if the user presses Escape,\n // and `block_end` bubbles the focus up the tree, it'll stop on our parent,\n // which will then focus us on the next iteration.\n let mut parent = parent.borrow_mut();\n parent.attributes.focusable = true;\n\n if self.tui.is_node_focused(parent.id) {\n self.needs_rerender();\n self.tui.focused_node_path.push(last_node.id);\n }\n }\n\n /// Causes keyboard focus to be unable to escape this node and its children.\n /// It's a \"well\" because if the focus is inside it, it can't escape.\n pub fn attr_focus_well(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focus_well = true;\n }\n\n /// Explicitly sets the intrinsic size of the current node.\n /// The intrinsic size is the size the node ideally wants to be.\n pub fn attr_intrinsic_size(&mut self, size: Size) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.intrinsic_size = size;\n last_node.intrinsic_size_set = true;\n }\n\n /// Turns the current node into a floating node,\n /// like a popup, modal or a tooltip.\n pub fn attr_float(&mut self, spec: FloatSpec) {\n let last_node = self.tree.last_node;\n let anchor = {\n let ln = last_node.borrow();\n match spec.anchor {\n Anchor::Last if ln.siblings.prev.is_some() => ln.siblings.prev,\n Anchor::Last | Anchor::Parent => ln.parent,\n // By not giving such floats a parent, they get the same origin as the original root node,\n // but they also gain their own \"root id\" in the tree. That way, their focus path is totally unique,\n // which means that we can easily check if a modal is open by calling `is_focused()` on the original root.\n Anchor::Root => None,\n }\n };\n\n self.tree.move_node_to_root(last_node, anchor);\n\n let mut ln = last_node.borrow_mut();\n ln.attributes.focus_well = true;\n ln.attributes.float = Some(FloatAttributes {\n gravity_x: spec.gravity_x.clamp(0.0, 1.0),\n gravity_y: spec.gravity_y.clamp(0.0, 1.0),\n offset_x: spec.offset_x,\n offset_y: spec.offset_y,\n });\n ln.attributes.bg = self.tui.floater_default_bg;\n ln.attributes.fg = self.tui.floater_default_fg;\n }\n\n /// Gives the current node a border.\n pub fn attr_border(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.bordered = true;\n }\n\n /// Sets the current node's position inside the parent.\n pub fn attr_position(&mut self, align: Position) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.position = align;\n }\n\n /// Assigns padding to the current node.\n pub fn attr_padding(&mut self, padding: Rect) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.padding = Self::normalize_rect(padding);\n }\n\n fn normalize_rect(rect: Rect) -> Rect {\n Rect {\n left: rect.left.max(0),\n top: rect.top.max(0),\n right: rect.right.max(0),\n bottom: rect.bottom.max(0),\n }\n }\n\n /// Assigns a sRGB background color to the current node.\n pub fn attr_background_rgba(&mut self, bg: u32) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.bg = bg;\n }\n\n /// Assigns a sRGB foreground color to the current node.\n pub fn attr_foreground_rgba(&mut self, fg: u32) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.fg = fg;\n }\n\n /// Applies reverse-video to the current node:\n /// Background and foreground colors are swapped.\n pub fn attr_reverse(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.reverse = true;\n }\n\n /// Checks if the current keyboard input matches the given shortcut,\n /// consumes it if it is and returns true in that case.\n pub fn consume_shortcut(&mut self, shortcut: InputKey) -> bool {\n if !self.input_consumed && self.input_keyboard == Some(shortcut) {\n self.set_input_consumed();\n true\n } else {\n false\n }\n }\n\n /// Returns current keyboard input, if any.\n /// Returns None if the input was already consumed.\n pub fn keyboard_input(&self) -> Option {\n if self.input_consumed { None } else { self.input_keyboard }\n }\n\n #[inline]\n pub fn set_input_consumed(&mut self) {\n debug_assert!(!self.input_consumed);\n self.set_input_consumed_unchecked();\n }\n\n #[inline]\n fn set_input_consumed_unchecked(&mut self) {\n self.input_consumed = true;\n }\n\n /// Returns whether the mouse was pressed down on the current node.\n pub fn was_mouse_down(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.was_mouse_down_on_node(last_node.id)\n }\n\n /// Returns whether the mouse was pressed down on the current node's subtree.\n pub fn contains_mouse_down(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.was_mouse_down_on_subtree(&last_node)\n }\n\n /// Returns whether the current node is focused.\n pub fn is_focused(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.is_node_focused(last_node.id)\n }\n\n /// Returns whether the current node's subtree is focused.\n pub fn contains_focus(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.is_subtree_focused(&last_node)\n }\n\n /// Begins a modal window. Call [`Context::modal_end()`].\n pub fn modal_begin(&mut self, classname: &'static str, title: &str) {\n self.block_begin(classname);\n self.attr_float(FloatSpec {\n anchor: Anchor::Root,\n gravity_x: 0.5,\n gravity_y: 0.5,\n offset_x: self.tui.size.width as f32 * 0.5,\n offset_y: self.tui.size.height as f32 * 0.5,\n });\n self.attr_border();\n self.attr_background_rgba(self.tui.modal_default_bg);\n self.attr_foreground_rgba(self.tui.modal_default_fg);\n self.attr_focus_well();\n self.focus_on_first_present();\n\n let mut last_node = self.tree.last_node.borrow_mut();\n let title = if title.is_empty() {\n ArenaString::new_in(self.arena())\n } else {\n arena_format!(self.arena(), \" {} \", title)\n };\n last_node.content = NodeContent::Modal(title);\n self.last_modal = Some(self.tree.last_node);\n }\n\n /// Ends the current modal window block.\n /// Returns true if the user pressed Escape (a request to close).\n pub fn modal_end(&mut self) -> bool {\n self.block_end();\n\n // Consume the input unconditionally, so that the root (the \"main window\")\n // doesn't accidentally receive any input via `consume_shortcut()`.\n if self.contains_focus() {\n let exit = !self.input_consumed && self.input_keyboard == Some(vk::ESCAPE);\n self.set_input_consumed_unchecked();\n exit\n } else {\n false\n }\n }\n\n /// Begins a table block. Call [`Context::table_end()`].\n /// Tables are the primary way to create a grid layout,\n /// and to layout controls on a single row (= a table with 1 row).\n pub fn table_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.content = NodeContent::Table(TableContent {\n columns: Vec::new_in(self.arena()),\n cell_gap: Default::default(),\n });\n }\n\n /// Assigns widths to the columns of the current table.\n /// By default, the table will left-align all columns.\n pub fn table_set_columns(&mut self, columns: &[CoordType]) {\n let mut last_node = self.tree.last_node.borrow_mut();\n if let NodeContent::Table(spec) = &mut last_node.content {\n spec.columns.clear();\n spec.columns.extend_from_slice(columns);\n } else {\n debug_assert!(false);\n }\n }\n\n /// Assigns the gap between cells in the current table.\n pub fn table_set_cell_gap(&mut self, cell_gap: Size) {\n let mut last_node = self.tree.last_node.borrow_mut();\n if let NodeContent::Table(spec) = &mut last_node.content {\n spec.cell_gap = cell_gap;\n } else {\n debug_assert!(false);\n }\n }\n\n /// Starts the next row in the current table.\n pub fn table_next_row(&mut self) {\n {\n let current_node = self.tree.current_node.borrow();\n\n // If this is the first call to table_next_row() inside a new table, the\n // current_node will refer to the table. Otherwise, it'll refer to the current row.\n if !matches!(current_node.content, NodeContent::Table(_)) {\n let Some(parent) = current_node.parent else {\n return;\n };\n\n let parent = parent.borrow();\n // Neither the current nor its parent nodes are a table?\n // You definitely called this outside of a table block.\n debug_assert!(matches!(parent.content, NodeContent::Table(_)));\n\n self.block_end();\n self.table_end_row();\n\n self.next_block_id_mixin(parent.child_count as u64);\n }\n }\n\n self.block_begin(\"row\");\n }\n\n fn table_end_row(&mut self) {\n self.table_move_focus(vk::LEFT, vk::RIGHT);\n }\n\n /// Ends the current table block.\n pub fn table_end(&mut self) {\n let current_node = self.tree.current_node.borrow();\n\n // If this is the first call to table_next_row() inside a new table, the\n // current_node will refer to the table. Otherwise, it'll refer to the current row.\n if !matches!(current_node.content, NodeContent::Table(_)) {\n self.block_end();\n self.table_end_row();\n }\n\n self.block_end(); // table\n self.table_move_focus(vk::UP, vk::DOWN);\n }\n\n fn table_move_focus(&mut self, prev_key: InputKey, next_key: InputKey) {\n // Filter down to table rows that are focused.\n if !self.contains_focus() {\n return;\n }\n\n // Filter down to our prev/next inputs.\n if self.input_consumed {\n return;\n }\n let Some(input) = self.input_keyboard else {\n return;\n };\n if input != prev_key && input != next_key {\n return;\n }\n\n let container = self.tree.last_node;\n let Some(&focused_id) = self.tui.focused_node_path.get(container.borrow().depth + 1) else {\n return;\n };\n\n let mut prev_next = NodeSiblings { prev: None, next: None };\n let mut focused = None;\n\n // Iterate through the cells in the row / the rows in the table, looking for focused_id.\n // Take note of the previous and next focusable cells / rows around the focused one.\n for cell in Tree::iterate_siblings(container.borrow().children.first) {\n let n = cell.borrow();\n if n.id == focused_id {\n focused = Some(cell);\n } else if n.attributes.focusable {\n if focused.is_none() {\n prev_next.prev = Some(cell);\n } else {\n prev_next.next = Some(cell);\n break;\n }\n }\n }\n\n if focused.is_none() {\n return;\n }\n\n let forward = input == next_key;\n let children_idx = if forward { NodeChildren::FIRST } else { NodeChildren::LAST };\n let siblings_idx = if forward { NodeSiblings::NEXT } else { NodeSiblings::PREV };\n let Some(focused_next) =\n prev_next.get(siblings_idx).or_else(|| container.borrow().children.get(children_idx))\n else {\n return;\n };\n\n Tui::build_node_path(Some(focused_next), &mut self.tui.focused_node_path);\n self.set_input_consumed();\n self.needs_rerender();\n }\n\n /// Creates a simple text label.\n pub fn label(&mut self, classname: &'static str, text: &str) {\n self.styled_label_begin(classname);\n self.styled_label_add_text(text);\n self.styled_label_end();\n }\n\n /// Creates a styled text label.\n ///\n /// # Example\n /// ```\n /// use edit::framebuffer::IndexedColor;\n /// use edit::tui::Context;\n ///\n /// fn draw(ctx: &mut Context) {\n /// ctx.styled_label_begin(\"label\");\n /// // Shows \"Hello\" in the inherited foreground color.\n /// ctx.styled_label_add_text(\"Hello\");\n /// // Shows \", World!\" next to \"Hello\" in red.\n /// ctx.styled_label_set_foreground(ctx.indexed(IndexedColor::Red));\n /// ctx.styled_label_add_text(\", World!\");\n /// }\n /// ```\n pub fn styled_label_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n self.tree.last_node.borrow_mut().content = NodeContent::Text(TextContent {\n text: ArenaString::new_in(self.arena()),\n chunks: Vec::with_capacity_in(4, self.arena()),\n overflow: Overflow::Clip,\n });\n }\n\n /// Changes the active pencil color of the current label.\n pub fn styled_label_set_foreground(&mut self, fg: u32) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n let last = content.chunks.last().unwrap_or(&INVALID_STYLED_TEXT_CHUNK);\n if last.offset != content.text.len() && last.fg != fg {\n content.chunks.push(StyledTextChunk {\n offset: content.text.len(),\n fg,\n attr: last.attr,\n });\n }\n }\n\n /// Changes the active pencil attributes of the current label.\n pub fn styled_label_set_attributes(&mut self, attr: Attributes) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n let last = content.chunks.last().unwrap_or(&INVALID_STYLED_TEXT_CHUNK);\n if last.offset != content.text.len() && last.attr != attr {\n content.chunks.push(StyledTextChunk { offset: content.text.len(), fg: last.fg, attr });\n }\n }\n\n /// Adds text to the current label.\n pub fn styled_label_add_text(&mut self, text: &str) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n content.text.push_str(text);\n }\n\n /// Ends the current label block.\n pub fn styled_label_end(&mut self) {\n {\n let mut last_node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &last_node.content else {\n return;\n };\n\n let cursor = unicode::MeasurementConfig::new(&content.text.as_bytes())\n .goto_visual(Point { x: CoordType::MAX, y: 0 });\n last_node.intrinsic_size.width = cursor.visual_pos.x;\n last_node.intrinsic_size.height = 1;\n last_node.intrinsic_size_set = true;\n }\n\n self.block_end();\n }\n\n /// Sets the overflow behavior of the current label.\n pub fn attr_overflow(&mut self, overflow: Overflow) {\n let mut last_node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut last_node.content else {\n return;\n };\n\n content.overflow = overflow;\n }\n\n /// Creates a button with the given text.\n /// Returns true if the button was activated.\n pub fn button(&mut self, classname: &'static str, text: &str, style: ButtonStyle) -> bool {\n self.button_label(classname, text, style);\n self.attr_focusable();\n if self.is_focused() {\n self.attr_reverse();\n }\n self.button_activated()\n }\n\n /// Creates a checkbox with the given text.\n /// Returns true if the checkbox was activated.\n pub fn checkbox(&mut self, classname: &'static str, text: &str, checked: &mut bool) -> bool {\n self.styled_label_begin(classname);\n self.attr_focusable();\n if self.is_focused() {\n self.attr_reverse();\n }\n self.styled_label_add_text(if *checked { \"[🗹 \" } else { \"[☐ \" });\n self.styled_label_add_text(text);\n self.styled_label_add_text(\"]\");\n self.styled_label_end();\n\n let activated = self.button_activated();\n if activated {\n *checked = !*checked;\n }\n activated\n }\n\n fn button_activated(&mut self) -> bool {\n if !self.input_consumed\n && ((self.input_mouse_click != 0 && self.contains_mouse_down())\n || self.input_keyboard == Some(vk::RETURN)\n || self.input_keyboard == Some(vk::SPACE))\n && self.is_focused()\n {\n self.set_input_consumed();\n true\n } else {\n false\n }\n }\n\n /// Creates a text input field.\n /// Returns true if the text contents changed.\n pub fn editline(&mut self, classname: &'static str, text: &mut dyn WriteableDocument) -> bool {\n self.textarea_internal(classname, TextBufferPayload::Editline(text))\n }\n\n /// Creates a text area.\n pub fn textarea(&mut self, classname: &'static str, tb: RcTextBuffer) {\n self.textarea_internal(classname, TextBufferPayload::Textarea(tb));\n }\n\n fn textarea_internal(&mut self, classname: &'static str, payload: TextBufferPayload) -> bool {\n self.block_begin(classname);\n self.block_end();\n\n let mut node = self.tree.last_node.borrow_mut();\n let node = &mut *node;\n let single_line = match &payload {\n TextBufferPayload::Editline(_) => true,\n TextBufferPayload::Textarea(_) => false,\n };\n\n let buffer = {\n let buffers = &mut self.tui.cached_text_buffers;\n\n let cached = match buffers.iter_mut().find(|t| t.node_id == node.id) {\n Some(cached) => {\n if let TextBufferPayload::Textarea(tb) = &payload {\n cached.editor = tb.clone();\n };\n cached.seen = true;\n cached\n }\n None => {\n // If the node is not in the cache, we need to create a new one.\n buffers.push(CachedTextBuffer {\n node_id: node.id,\n editor: match &payload {\n TextBufferPayload::Editline(_) => TextBuffer::new_rc(true).unwrap(),\n TextBufferPayload::Textarea(tb) => tb.clone(),\n },\n seen: true,\n });\n buffers.last_mut().unwrap()\n }\n };\n\n // SAFETY: *Assuming* that there are no duplicate node IDs in the tree that\n // would cause this cache slot to be overwritten, then this operation is safe.\n // The text buffer cache will keep the buffer alive for us long enough.\n unsafe { mem::transmute(&*cached.editor) }\n };\n\n node.content = NodeContent::Textarea(TextareaContent {\n buffer,\n scroll_offset: Default::default(),\n scroll_offset_y_drag_start: CoordType::MIN,\n scroll_offset_x_max: 0,\n thumb_height: 0,\n preferred_column: 0,\n single_line,\n has_focus: self.tui.is_node_focused(node.id),\n });\n\n let content = match node.content {\n NodeContent::Textarea(ref mut content) => content,\n _ => unreachable!(),\n };\n\n if let TextBufferPayload::Editline(text) = &payload {\n content.buffer.borrow_mut().copy_from_str(*text);\n }\n\n if let Some(node_prev) = self.tui.prev_node_map.get(node.id) {\n let node_prev = node_prev.borrow();\n if let NodeContent::Textarea(content_prev) = &node_prev.content {\n content.scroll_offset = content_prev.scroll_offset;\n content.scroll_offset_y_drag_start = content_prev.scroll_offset_y_drag_start;\n content.scroll_offset_x_max = content_prev.scroll_offset_x_max;\n content.thumb_height = content_prev.thumb_height;\n content.preferred_column = content_prev.preferred_column;\n\n let mut text_width = node_prev.inner.width();\n if !single_line {\n // Subtract -1 to account for the scrollbar.\n text_width -= 1;\n }\n\n let mut make_cursor_visible;\n {\n let mut tb = content.buffer.borrow_mut();\n make_cursor_visible = tb.take_cursor_visibility_request();\n make_cursor_visible |= tb.set_width(text_width);\n }\n\n make_cursor_visible |= self.textarea_handle_input(content, &node_prev, single_line);\n\n if make_cursor_visible {\n self.textarea_make_cursor_visible(content, &node_prev);\n }\n } else {\n debug_assert!(false);\n }\n }\n\n let dirty;\n {\n let mut tb = content.buffer.borrow_mut();\n dirty = tb.is_dirty();\n if dirty && let TextBufferPayload::Editline(text) = payload {\n tb.save_as_string(text);\n }\n }\n\n self.textarea_adjust_scroll_offset(content);\n\n if single_line {\n node.attributes.fg = self.indexed(IndexedColor::Foreground);\n node.attributes.bg = self.indexed(IndexedColor::Background);\n if !content.has_focus {\n node.attributes.fg = self.contrasted(node.attributes.bg);\n node.attributes.bg = self.indexed_alpha(IndexedColor::Background, 1, 2);\n }\n }\n\n node.attributes.focusable = true;\n node.intrinsic_size.height = content.buffer.borrow().visual_line_count();\n node.intrinsic_size_set = true;\n\n dirty\n }\n\n fn textarea_handle_input(\n &mut self,\n tc: &mut TextareaContent,\n node_prev: &Node,\n single_line: bool,\n ) -> bool {\n if self.input_consumed {\n return false;\n }\n\n let mut tb = tc.buffer.borrow_mut();\n let tb = &mut *tb;\n let mut make_cursor_visible = false;\n let mut change_preferred_column = false;\n\n if self.tui.mouse_state != InputMouseState::None\n && self.tui.was_mouse_down_on_node(node_prev.id)\n {\n // Scrolling works even if the node isn't focused.\n if self.tui.mouse_state == InputMouseState::Scroll {\n tc.scroll_offset.x += self.input_scroll_delta.x;\n tc.scroll_offset.y += self.input_scroll_delta.y;\n self.set_input_consumed();\n } else if self.tui.is_node_focused(node_prev.id) {\n let mouse = self.tui.mouse_position;\n let inner = node_prev.inner;\n let text_rect = Rect {\n left: inner.left + tb.margin_width(),\n top: inner.top,\n right: inner.right - !single_line as CoordType,\n bottom: inner.bottom,\n };\n let track_rect = Rect {\n left: text_rect.right,\n top: inner.top,\n right: inner.right,\n bottom: inner.bottom,\n };\n let pos = Point {\n x: mouse.x - inner.left - tb.margin_width() + tc.scroll_offset.x,\n y: mouse.y - inner.top + tc.scroll_offset.y,\n };\n\n if text_rect.contains(self.tui.mouse_down_position) {\n if self.tui.mouse_is_drag {\n tb.selection_update_visual(pos);\n tc.preferred_column = tb.cursor_visual_pos().x;\n\n let height = inner.height();\n\n // If the editor is only 1 line tall we can't possibly scroll up or down.\n if height >= 2 {\n fn calc(min: CoordType, max: CoordType, mouse: CoordType) -> CoordType {\n // Otherwise, the scroll zone is up to 3 lines at the top/bottom.\n let zone_height = ((max - min) / 2).min(3);\n\n // The .y positions where the scroll zones begin:\n // Mouse coordinates above top and below bottom respectively.\n let scroll_min = min + zone_height;\n let scroll_max = max - zone_height - 1;\n\n // Calculate the delta for scrolling up or down.\n let delta_min = (mouse - scroll_min).clamp(-zone_height, 0);\n let delta_max = (mouse - scroll_max).clamp(0, zone_height);\n\n // If I didn't mess up my logic here, only one of the two values can possibly be !=0.\n let idx = 3 + delta_min + delta_max;\n\n const SPEEDS: [CoordType; 7] = [-9, -3, -1, 0, 1, 3, 9];\n let idx = idx.clamp(0, SPEEDS.len() as CoordType) as usize;\n SPEEDS[idx]\n }\n\n let delta_x = calc(text_rect.left, text_rect.right, mouse.x);\n let delta_y = calc(text_rect.top, text_rect.bottom, mouse.y);\n\n tc.scroll_offset.x += delta_x;\n tc.scroll_offset.y += delta_y;\n\n if delta_x != 0 || delta_y != 0 {\n self.tui.read_timeout = time::Duration::from_millis(25);\n }\n }\n } else {\n match self.input_mouse_click {\n 5.. => {}\n 4 => tb.select_all(),\n 3 => tb.select_line(),\n 2 => tb.select_word(),\n _ => match self.tui.mouse_state {\n InputMouseState::Left => {\n if self.input_mouse_modifiers.contains(kbmod::SHIFT) {\n // TODO: Untested because Windows Terminal surprisingly doesn't support Shift+Click.\n tb.selection_update_visual(pos);\n } else {\n tb.cursor_move_to_visual(pos);\n }\n tc.preferred_column = tb.cursor_visual_pos().x;\n make_cursor_visible = true;\n }\n _ => return false,\n },\n }\n }\n } else if track_rect.contains(self.tui.mouse_down_position) {\n if self.tui.mouse_state == InputMouseState::Release {\n tc.scroll_offset_y_drag_start = CoordType::MIN;\n } else if self.tui.mouse_is_drag {\n if tc.scroll_offset_y_drag_start == CoordType::MIN {\n tc.scroll_offset_y_drag_start = tc.scroll_offset.y;\n }\n\n // The textarea supports 1 height worth of \"scrolling beyond the end\".\n // `track_height` is the same as the viewport height.\n let scrollable_height = tb.visual_line_count() - 1;\n\n if scrollable_height > 0 {\n let trackable = track_rect.height() - tc.thumb_height;\n let delta_y = mouse.y - self.tui.mouse_down_position.y;\n tc.scroll_offset.y = tc.scroll_offset_y_drag_start\n + (delta_y as i64 * scrollable_height as i64 / trackable as i64)\n as CoordType;\n }\n }\n }\n\n self.set_input_consumed();\n }\n\n return make_cursor_visible;\n }\n\n if !tc.has_focus {\n return false;\n }\n\n let mut write: &[u8] = &[];\n\n if let Some(input) = &self.input_text {\n write = input.as_bytes();\n } else if let Some(input) = &self.input_keyboard {\n let key = input.key();\n let modifiers = input.modifiers();\n\n make_cursor_visible = true;\n\n match key {\n vk::BACK => {\n let granularity = if modifiers == kbmod::CTRL {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n tb.delete(granularity, -1);\n }\n vk::TAB => {\n if single_line {\n // If this is just a simple input field, don't consume Tab (= early return).\n return false;\n }\n tb.indent_change(if modifiers == kbmod::SHIFT { -1 } else { 1 });\n }\n vk::RETURN => {\n if single_line {\n // If this is just a simple input field, don't consume Enter (= early return).\n return false;\n }\n write = b\"\\n\";\n }\n vk::ESCAPE => {\n // If there was a selection, clear it and show the cursor (= fallthrough).\n if !tb.clear_selection() {\n if single_line {\n // If this is just a simple input field, don't consume the escape key\n // (early return) and don't show the cursor (= return false).\n return false;\n }\n\n // If this is a textarea, don't show the cursor if\n // the escape key was pressed and nothing happened.\n make_cursor_visible = false;\n }\n }\n vk::PRIOR => {\n let height = node_prev.inner.height() - 1;\n\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if tb.cursor_visual_pos().y == 0 {\n tc.preferred_column = 0;\n }\n\n if modifiers == kbmod::SHIFT {\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - height,\n });\n } else {\n tb.cursor_move_to_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - height,\n });\n }\n }\n vk::NEXT => {\n let height = node_prev.inner.height() - 1;\n\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if tb.cursor_visual_pos().y >= tb.visual_line_count() - 1 {\n tc.preferred_column = CoordType::MAX;\n }\n\n if modifiers == kbmod::SHIFT {\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + height,\n });\n } else {\n tb.cursor_move_to_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + height,\n });\n }\n\n if tc.preferred_column == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n vk::END => {\n let logical_before = tb.cursor_logical_pos();\n let destination = if modifiers.contains(kbmod::CTRL) {\n Point::MAX\n } else {\n Point { x: CoordType::MAX, y: tb.cursor_visual_pos().y }\n };\n\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_visual(destination);\n } else {\n tb.cursor_move_to_visual(destination);\n }\n\n if !modifiers.contains(kbmod::CTRL) {\n let logical_after = tb.cursor_logical_pos();\n\n // If word-wrap is enabled and the user presses End the first time,\n // it moves to the start of the visual line. The second time they\n // press it, it moves to the start of the logical line.\n if tb.is_word_wrap_enabled() && logical_after == logical_before {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(Point {\n x: CoordType::MAX,\n y: tb.cursor_logical_pos().y,\n });\n } else {\n tb.cursor_move_to_logical(Point {\n x: CoordType::MAX,\n y: tb.cursor_logical_pos().y,\n });\n }\n }\n }\n }\n vk::HOME => {\n let logical_before = tb.cursor_logical_pos();\n let destination = if modifiers.contains(kbmod::CTRL) {\n Default::default()\n } else {\n Point { x: 0, y: tb.cursor_visual_pos().y }\n };\n\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_visual(destination);\n } else {\n tb.cursor_move_to_visual(destination);\n }\n\n if !modifiers.contains(kbmod::CTRL) {\n let mut logical_after = tb.cursor_logical_pos();\n\n // If word-wrap is enabled and the user presses Home the first time,\n // it moves to the start of the visual line. The second time they\n // press it, it moves to the start of the logical line.\n if tb.is_word_wrap_enabled() && logical_after == logical_before {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(Point {\n x: 0,\n y: tb.cursor_logical_pos().y,\n });\n } else {\n tb.cursor_move_to_logical(Point {\n x: 0,\n y: tb.cursor_logical_pos().y,\n });\n }\n logical_after = tb.cursor_logical_pos();\n }\n\n // If the line has some indentation and the user pressed Home,\n // the first time it'll stop at the indentation. The second time\n // they press it, it'll move to the true start of the line.\n //\n // If the cursor is already at the start of the line,\n // we move it back to the end of the indentation.\n if logical_after.x == 0\n && let indent_end = tb.indent_end_logical_pos()\n && (logical_before > indent_end || logical_before.x == 0)\n {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(indent_end);\n } else {\n tb.cursor_move_to_logical(indent_end);\n }\n }\n }\n }\n vk::LEFT => {\n let granularity = if modifiers.contains(KBMOD_FOR_WORD_NAV) {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_delta(granularity, -1);\n } else if let Some((beg, _)) = tb.selection_range() {\n unsafe { tb.set_cursor(beg) };\n } else {\n tb.cursor_move_delta(granularity, -1);\n }\n }\n vk::UP => {\n if single_line {\n return false;\n }\n match modifiers {\n kbmod::NONE => {\n let mut x = tc.preferred_column;\n let mut y = tb.cursor_visual_pos().y - 1;\n\n // If there's a selection we put the cursor above it.\n if let Some((beg, _)) = tb.selection_range() {\n x = beg.visual_pos.x;\n y = beg.visual_pos.y - 1;\n tc.preferred_column = x;\n }\n\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if y < 0 {\n x = 0;\n tc.preferred_column = 0;\n }\n\n tb.cursor_move_to_visual(Point { x, y });\n }\n kbmod::CTRL => {\n tc.scroll_offset.y -= 1;\n make_cursor_visible = false;\n }\n kbmod::SHIFT => {\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if tb.cursor_visual_pos().y == 0 {\n tc.preferred_column = 0;\n }\n\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - 1,\n });\n }\n kbmod::ALT => tb.move_selected_lines(MoveLineDirection::Up),\n kbmod::CTRL_ALT => {\n // TODO: Add cursor above\n }\n _ => return false,\n }\n }\n vk::RIGHT => {\n let granularity = if modifiers.contains(KBMOD_FOR_WORD_NAV) {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_delta(granularity, 1);\n } else if let Some((_, end)) = tb.selection_range() {\n unsafe { tb.set_cursor(end) };\n } else {\n tb.cursor_move_delta(granularity, 1);\n }\n }\n vk::DOWN => {\n if single_line {\n return false;\n }\n match modifiers {\n kbmod::NONE => {\n let mut x = tc.preferred_column;\n let mut y = tb.cursor_visual_pos().y + 1;\n\n // If there's a selection we put the cursor below it.\n if let Some((_, end)) = tb.selection_range() {\n x = end.visual_pos.x;\n y = end.visual_pos.y + 1;\n tc.preferred_column = x;\n }\n\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if y >= tb.visual_line_count() {\n x = CoordType::MAX;\n }\n\n tb.cursor_move_to_visual(Point { x, y });\n\n // If we fell into the `if y >= tb.get_visual_line_count()` above, we wanted to\n // update the `preferred_column` but didn't know yet what it was. Now we know!\n if x == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n kbmod::CTRL => {\n tc.scroll_offset.y += 1;\n make_cursor_visible = false;\n }\n kbmod::SHIFT => {\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if tb.cursor_visual_pos().y >= tb.visual_line_count() - 1 {\n tc.preferred_column = CoordType::MAX;\n }\n\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + 1,\n });\n\n if tc.preferred_column == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n kbmod::ALT => tb.move_selected_lines(MoveLineDirection::Down),\n kbmod::CTRL_ALT => {\n // TODO: Add cursor above\n }\n _ => return false,\n }\n }\n vk::INSERT => match modifiers {\n kbmod::SHIFT => tb.paste(self.clipboard_ref()),\n kbmod::CTRL => tb.copy(self.clipboard_mut()),\n _ => tb.set_overtype(!tb.is_overtype()),\n },\n vk::DELETE => match modifiers {\n kbmod::SHIFT => tb.cut(self.clipboard_mut()),\n kbmod::CTRL => tb.delete(CursorMovement::Word, 1),\n _ => tb.delete(CursorMovement::Grapheme, 1),\n },\n vk::A => match modifiers {\n kbmod::CTRL => tb.select_all(),\n _ => return false,\n },\n vk::B => match modifiers {\n kbmod::ALT if cfg!(target_os = \"macos\") => {\n // On macOS, terminals commonly emit the Emacs style\n // Alt+B (ESC b) sequence for Alt+Left.\n tb.cursor_move_delta(CursorMovement::Word, -1);\n }\n _ => return false,\n },\n vk::F => match modifiers {\n kbmod::ALT if cfg!(target_os = \"macos\") => {\n // On macOS, terminals commonly emit the Emacs style\n // Alt+F (ESC f) sequence for Alt+Right.\n tb.cursor_move_delta(CursorMovement::Word, 1);\n }\n _ => return false,\n },\n vk::H => match modifiers {\n kbmod::CTRL => tb.delete(CursorMovement::Word, -1),\n _ => return false,\n },\n vk::L => match modifiers {\n kbmod::CTRL => tb.select_line(),\n _ => return false,\n },\n vk::X => match modifiers {\n kbmod::CTRL => tb.cut(self.clipboard_mut()),\n _ => return false,\n },\n vk::C => match modifiers {\n kbmod::CTRL => tb.copy(self.clipboard_mut()),\n _ => return false,\n },\n vk::V => match modifiers {\n kbmod::CTRL => tb.paste(self.clipboard_ref()),\n _ => return false,\n },\n vk::Y => match modifiers {\n kbmod::CTRL => tb.redo(),\n _ => return false,\n },\n vk::Z => match modifiers {\n kbmod::CTRL => tb.undo(),\n kbmod::CTRL_SHIFT => tb.redo(),\n kbmod::ALT => tb.set_word_wrap(!tb.is_word_wrap_enabled()),\n _ => return false,\n },\n _ => return false,\n }\n\n change_preferred_column = !matches!(key, vk::PRIOR | vk::NEXT | vk::UP | vk::DOWN);\n } else {\n return false;\n }\n\n if single_line && !write.is_empty() {\n let (end, _) = simd::lines_fwd(write, 0, 0, 1);\n write = unicode::strip_newline(&write[..end]);\n }\n if !write.is_empty() {\n tb.write_canon(write);\n change_preferred_column = true;\n make_cursor_visible = true;\n }\n\n if change_preferred_column {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n\n self.set_input_consumed();\n make_cursor_visible\n }\n\n fn textarea_make_cursor_visible(&self, tc: &mut TextareaContent, node_prev: &Node) {\n let tb = tc.buffer.borrow();\n let mut scroll_x = tc.scroll_offset.x;\n let mut scroll_y = tc.scroll_offset.y;\n\n let text_width = tb.text_width();\n let cursor_x = tb.cursor_visual_pos().x;\n scroll_x = scroll_x.min(cursor_x - 10);\n scroll_x = scroll_x.max(cursor_x - text_width + 10);\n\n let viewport_height = node_prev.inner.height();\n let cursor_y = tb.cursor_visual_pos().y;\n // Scroll up if the cursor is above the visible area.\n scroll_y = scroll_y.min(cursor_y);\n // Scroll down if the cursor is below the visible area.\n scroll_y = scroll_y.max(cursor_y - viewport_height + 1);\n\n tc.scroll_offset.x = scroll_x;\n tc.scroll_offset.y = scroll_y;\n }\n\n fn textarea_adjust_scroll_offset(&self, tc: &mut TextareaContent) {\n let tb = tc.buffer.borrow();\n let mut scroll_x = tc.scroll_offset.x;\n let mut scroll_y = tc.scroll_offset.y;\n\n scroll_x = scroll_x.min(tc.scroll_offset_x_max.max(tb.cursor_visual_pos().x) - 10);\n scroll_x = scroll_x.max(0);\n scroll_y = scroll_y.clamp(0, tb.visual_line_count() - 1);\n\n if tb.is_word_wrap_enabled() {\n scroll_x = 0;\n }\n\n tc.scroll_offset.x = scroll_x;\n tc.scroll_offset.y = scroll_y;\n }\n\n /// Creates a scrollable area.\n pub fn scrollarea_begin(&mut self, classname: &'static str, intrinsic_size: Size) {\n self.block_begin(classname);\n\n let container_node = self.tree.last_node;\n {\n let mut container = self.tree.last_node.borrow_mut();\n container.content = NodeContent::Scrollarea(ScrollareaContent {\n scroll_offset: Point::MIN,\n scroll_offset_y_drag_start: CoordType::MIN,\n thumb_height: 0,\n });\n\n if intrinsic_size.width > 0 || intrinsic_size.height > 0 {\n container.intrinsic_size.width = intrinsic_size.width.max(0);\n container.intrinsic_size.height = intrinsic_size.height.max(0);\n container.intrinsic_size_set = true;\n }\n }\n\n self.block_begin(\"content\");\n self.inherit_focus();\n\n // Ensure that attribute modifications apply to the outer container.\n self.tree.last_node = container_node;\n }\n\n /// Scrolls the current scrollable area to the given position.\n pub fn scrollarea_scroll_to(&mut self, pos: Point) {\n let mut container = self.tree.last_node.borrow_mut();\n if let NodeContent::Scrollarea(sc) = &mut container.content {\n sc.scroll_offset = pos;\n } else {\n debug_assert!(false);\n }\n }\n\n /// Ends the current scrollarea block.\n pub fn scrollarea_end(&mut self) {\n self.block_end(); // content block\n self.block_end(); // outer container\n\n let mut container = self.tree.last_node.borrow_mut();\n let container_id = container.id;\n let container_depth = container.depth;\n let Some(prev_container) = self.tui.prev_node_map.get(container_id) else {\n return;\n };\n\n let prev_container = prev_container.borrow();\n let NodeContent::Scrollarea(sc) = &mut container.content else {\n unreachable!();\n };\n\n if sc.scroll_offset == Point::MIN\n && let NodeContent::Scrollarea(sc_prev) = &prev_container.content\n {\n *sc = sc_prev.clone();\n }\n\n if !self.input_consumed {\n if self.tui.mouse_state != InputMouseState::None {\n let container_rect = prev_container.inner;\n\n match self.tui.mouse_state {\n InputMouseState::Left => {\n if self.tui.mouse_is_drag {\n // We don't need to look up the previous track node,\n // since it has a fixed size based on the container size.\n let track_rect = Rect {\n left: container_rect.right,\n top: container_rect.top,\n right: container_rect.right + 1,\n bottom: container_rect.bottom,\n };\n if track_rect.contains(self.tui.mouse_down_position) {\n if sc.scroll_offset_y_drag_start == CoordType::MIN {\n sc.scroll_offset_y_drag_start = sc.scroll_offset.y;\n }\n\n let content = prev_container.children.first.unwrap().borrow();\n let content_rect = content.inner;\n let content_height = content_rect.height();\n let track_height = track_rect.height();\n let scrollable_height = content_height - track_height;\n\n if scrollable_height > 0 {\n let trackable = track_height - sc.thumb_height;\n let delta_y =\n self.tui.mouse_position.y - self.tui.mouse_down_position.y;\n sc.scroll_offset.y = sc.scroll_offset_y_drag_start\n + (delta_y as i64 * scrollable_height as i64\n / trackable as i64)\n as CoordType;\n }\n\n self.set_input_consumed();\n }\n }\n }\n InputMouseState::Release => {\n sc.scroll_offset_y_drag_start = CoordType::MIN;\n }\n InputMouseState::Scroll => {\n if container_rect.contains(self.tui.mouse_position) {\n sc.scroll_offset.x += self.input_scroll_delta.x;\n sc.scroll_offset.y += self.input_scroll_delta.y;\n self.set_input_consumed();\n }\n }\n _ => {}\n }\n } else if self.tui.is_subtree_focused_alt(container_id, container_depth)\n && let Some(key) = self.input_keyboard\n {\n match key {\n vk::PRIOR => sc.scroll_offset.y -= prev_container.inner_clipped.height(),\n vk::NEXT => sc.scroll_offset.y += prev_container.inner_clipped.height(),\n vk::END => sc.scroll_offset.y = CoordType::MAX,\n vk::HOME => sc.scroll_offset.y = 0,\n _ => return,\n }\n self.set_input_consumed();\n }\n }\n }\n\n /// Creates a list where exactly one item is selected.\n pub fn list_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n self.attr_focusable();\n\n let mut last_node = self.tree.last_node.borrow_mut();\n let content = self\n .tui\n .prev_node_map\n .get(last_node.id)\n .and_then(|node| match &node.borrow().content {\n NodeContent::List(content) => {\n Some(ListContent { selected: content.selected, selected_node: None })\n }\n _ => None,\n })\n .unwrap_or(ListContent { selected: 0, selected_node: None });\n\n last_node.attributes.focus_void = true;\n last_node.content = NodeContent::List(content);\n }\n\n /// Creates a list item with the given text.\n pub fn list_item(&mut self, select: bool, text: &str) -> ListSelection {\n self.styled_list_item_begin();\n self.styled_label_add_text(text);\n self.styled_list_item_end(select)\n }\n\n /// Creates a list item consisting of a styled label.\n /// See [`Context::styled_label_begin`].\n pub fn styled_list_item_begin(&mut self) {\n let list = self.tree.current_node;\n let idx = list.borrow().child_count;\n\n self.next_block_id_mixin(idx as u64);\n self.styled_label_begin(\"item\");\n self.styled_label_add_text(\" \");\n self.attr_focusable();\n }\n\n /// Ends the current styled list item.\n pub fn styled_list_item_end(&mut self, select: bool) -> ListSelection {\n self.styled_label_end();\n\n let list = self.tree.current_node;\n\n let selected_before;\n let selected_now;\n let focused;\n {\n let mut list = list.borrow_mut();\n let content = match &mut list.content {\n NodeContent::List(content) => content,\n _ => unreachable!(),\n };\n\n let item = self.tree.last_node.borrow();\n let item_id = item.id;\n selected_before = content.selected == item_id;\n focused = self.is_focused();\n\n // Inherit the default selection & Click changes selection\n selected_now = selected_before || (select && content.selected == 0) || focused;\n\n // Note down the selected node for keyboard navigation.\n if selected_now {\n content.selected_node = Some(self.tree.last_node);\n if !selected_before {\n content.selected = item_id;\n self.needs_rerender();\n }\n }\n }\n\n // Clicking an item activates it\n let clicked =\n !self.input_consumed && (self.input_mouse_click == 2 && self.was_mouse_down());\n // Pressing Enter on a selected item activates it as well\n let entered = focused\n && selected_before\n && !self.input_consumed\n && matches!(self.input_keyboard, Some(vk::RETURN));\n let activated = clicked || entered;\n if activated {\n self.set_input_consumed();\n }\n\n if selected_before && activated {\n ListSelection::Activated\n } else if selected_now && !selected_before {\n ListSelection::Selected\n } else {\n ListSelection::Unchanged\n }\n }\n\n /// [`Context::steal_focus`], but for a list view.\n ///\n /// This exists, because didn't want to figure out how to get\n /// [`Context::styled_list_item_end`] to recognize a regular,\n /// programmatic focus steal.\n pub fn list_item_steal_focus(&mut self) {\n self.steal_focus();\n\n match &mut self.tree.current_node.borrow_mut().content {\n NodeContent::List(content) => {\n content.selected = self.tree.last_node.borrow().id;\n content.selected_node = Some(self.tree.last_node);\n }\n _ => unreachable!(),\n }\n }\n\n /// Ends the current list block.\n pub fn list_end(&mut self) {\n self.block_end();\n\n let contains_focus;\n let selected_now;\n let mut selected_next;\n {\n let list = self.tree.last_node.borrow();\n\n contains_focus = self.tui.is_subtree_focused(&list);\n selected_now = match &list.content {\n NodeContent::List(content) => content.selected_node,\n _ => unreachable!(),\n };\n selected_next = match selected_now.or(list.children.first) {\n Some(node) => node,\n None => return,\n };\n }\n\n if contains_focus\n && !self.input_consumed\n && let Some(key) = self.input_keyboard\n && let Some(selected_now) = selected_now\n {\n let list = self.tree.last_node.borrow();\n\n if let Some(prev_container) = self.tui.prev_node_map.get(list.id) {\n let mut consumed = true;\n\n match key {\n vk::PRIOR => {\n selected_next = selected_now;\n for _ in 0..prev_container.borrow().inner_clipped.height() - 1 {\n let node = selected_next.borrow();\n selected_next = match node.siblings.prev {\n Some(node) => node,\n None => break,\n };\n }\n }\n vk::NEXT => {\n selected_next = selected_now;\n for _ in 0..prev_container.borrow().inner_clipped.height() - 1 {\n let node = selected_next.borrow();\n selected_next = match node.siblings.next {\n Some(node) => node,\n None => break,\n };\n }\n }\n vk::END => {\n selected_next = list.children.last.unwrap_or(selected_next);\n }\n vk::HOME => {\n selected_next = list.children.first.unwrap_or(selected_next);\n }\n vk::UP => {\n selected_next = selected_now\n .borrow()\n .siblings\n .prev\n .or(list.children.last)\n .unwrap_or(selected_next);\n }\n vk::DOWN => {\n selected_next = selected_now\n .borrow()\n .siblings\n .next\n .or(list.children.first)\n .unwrap_or(selected_next);\n }\n _ => consumed = false,\n }\n\n if consumed {\n self.set_input_consumed();\n }\n }\n }\n\n // Now that we know which item is selected we can mark it as such.\n if !opt_ptr_eq(selected_now, Some(selected_next))\n && let NodeContent::List(content) = &mut self.tree.last_node.borrow_mut().content\n {\n content.selected_node = Some(selected_next);\n }\n\n // Now that we know which item is selected we can mark it as such.\n if let NodeContent::Text(content) = &mut selected_next.borrow_mut().content {\n unsafe {\n content.text.as_bytes_mut()[0] = b'>';\n }\n }\n\n // If the list has focus, we also delegate focus to the selected item and colorize it.\n if contains_focus {\n {\n let mut node = selected_next.borrow_mut();\n node.attributes.bg = self.indexed(IndexedColor::Green);\n node.attributes.fg = self.contrasted(self.indexed(IndexedColor::Green));\n }\n self.steal_focus_for(selected_next);\n }\n }\n\n /// Creates a menubar, to be shown at the top of the screen.\n pub fn menubar_begin(&mut self) {\n self.table_begin(\"menubar\");\n self.attr_focus_well();\n self.table_next_row();\n }\n\n /// Appends a menu to the current menubar.\n ///\n /// Returns true if the menu is open. Continue appending items to it in that case.\n pub fn menubar_menu_begin(&mut self, text: &str, accelerator: char) -> bool {\n let accelerator = if cfg!(target_os = \"macos\") { '\\0' } else { accelerator };\n let mixin = self.tree.current_node.borrow().child_count as u64;\n self.next_block_id_mixin(mixin);\n\n self.button_label(\n \"menu_button\",\n text,\n ButtonStyle::default().accelerator(accelerator).bracketed(false),\n );\n self.attr_focusable();\n self.attr_padding(Rect::two(0, 1));\n\n let contains_focus = self.contains_focus();\n let keyboard_focus = accelerator != '\\0'\n && !contains_focus\n && self.consume_shortcut(kbmod::ALT | InputKey::new(accelerator as u32));\n\n if contains_focus || keyboard_focus {\n self.attr_background_rgba(self.tui.floater_default_bg);\n self.attr_foreground_rgba(self.tui.floater_default_fg);\n\n if self.is_focused() {\n self.attr_background_rgba(self.indexed(IndexedColor::Green));\n self.attr_foreground_rgba(self.contrasted(self.indexed(IndexedColor::Green)));\n }\n\n self.next_block_id_mixin(mixin);\n self.table_begin(\"flyout\");\n self.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 0.0,\n offset_x: 0.0,\n offset_y: 1.0,\n });\n self.attr_border();\n self.attr_focus_well();\n\n if keyboard_focus {\n self.steal_focus();\n }\n\n true\n } else {\n false\n }\n }\n\n /// Appends a button to the current menu.\n pub fn menubar_menu_button(\n &mut self,\n text: &str,\n accelerator: char,\n shortcut: InputKey,\n ) -> bool {\n self.menubar_menu_checkbox(text, accelerator, shortcut, false)\n }\n\n /// Appends a checkbox to the current menu.\n /// Returns true if the checkbox was activated.\n pub fn menubar_menu_checkbox(\n &mut self,\n text: &str,\n accelerator: char,\n shortcut: InputKey,\n checked: bool,\n ) -> bool {\n self.table_next_row();\n self.attr_focusable();\n\n // First menu item? Steal focus.\n if self.tree.current_node.borrow_mut().siblings.prev.is_none() {\n self.inherit_focus();\n }\n\n if self.is_focused() {\n self.attr_background_rgba(self.indexed(IndexedColor::Green));\n self.attr_foreground_rgba(self.contrasted(self.indexed(IndexedColor::Green)));\n }\n\n let clicked =\n self.button_activated() || self.consume_shortcut(InputKey::new(accelerator as u32));\n\n self.button_label(\n \"menu_checkbox\",\n text,\n ButtonStyle::default().bracketed(false).checked(checked).accelerator(accelerator),\n );\n self.menubar_shortcut(shortcut);\n\n if clicked {\n // TODO: This should reassign the previous focused path.\n self.needs_rerender();\n Tui::clean_node_path(&mut self.tui.focused_node_path);\n }\n\n clicked\n }\n\n /// Ends the current menu.\n pub fn menubar_menu_end(&mut self) {\n self.table_end();\n\n if !self.input_consumed\n && let Some(key) = self.input_keyboard\n && matches!(key, vk::ESCAPE | vk::UP | vk::DOWN)\n {\n if matches!(key, vk::UP | vk::DOWN) {\n // If the focus is on the menubar, and the user presses up/down,\n // focus the first/last item of the flyout respectively.\n let ln = self.tree.last_node.borrow();\n if self.tui.is_node_focused(ln.parent.map_or(0, |n| n.borrow().id)) {\n let selected_next =\n if key == vk::UP { ln.children.last } else { ln.children.first };\n if let Some(selected_next) = selected_next {\n self.steal_focus_for(selected_next);\n self.set_input_consumed();\n }\n }\n } else if self.contains_focus() {\n // Otherwise, if the menu is the focused one and the\n // user presses Escape, pass focus back to the menubar.\n self.tui.pop_focusable_node(1);\n }\n }\n }\n\n /// Ends the current menubar.\n pub fn menubar_end(&mut self) {\n self.table_end();\n }\n\n /// Renders a button label with an optional accelerator character\n /// May also renders a checkbox or square brackets for inline buttons\n fn button_label(&mut self, classname: &'static str, text: &str, style: ButtonStyle) {\n // Label prefix\n self.styled_label_begin(classname);\n if style.bracketed {\n self.styled_label_add_text(\"[\");\n }\n if let Some(checked) = style.checked {\n self.styled_label_add_text(if checked { \"🗹 \" } else { \" \" });\n }\n // Label text\n match style.accelerator {\n Some(accelerator) if accelerator.is_ascii_uppercase() => {\n // Complex case:\n // Locate the offset of the accelerator character in the label text\n let mut off = text.len();\n for (i, c) in text.bytes().enumerate() {\n // Perfect match (uppercase character) --> stop\n if c as char == accelerator {\n off = i;\n break;\n }\n // Inexact match (lowercase character) --> use first hit\n if (c & !0x20) as char == accelerator && off == text.len() {\n off = i;\n }\n }\n\n if off < text.len() {\n // Add an underline to the accelerator.\n self.styled_label_add_text(&text[..off]);\n self.styled_label_set_attributes(Attributes::Underlined);\n self.styled_label_add_text(&text[off..off + 1]);\n self.styled_label_set_attributes(Attributes::None);\n self.styled_label_add_text(&text[off + 1..]);\n } else {\n // Add the accelerator in parentheses and underline it.\n let ch = accelerator as u8;\n self.styled_label_add_text(text);\n self.styled_label_add_text(\"(\");\n self.styled_label_set_attributes(Attributes::Underlined);\n self.styled_label_add_text(unsafe { str_from_raw_parts(&ch, 1) });\n self.styled_label_set_attributes(Attributes::None);\n self.styled_label_add_text(\")\");\n }\n }\n _ => {\n // Simple case:\n // no accelerator character\n self.styled_label_add_text(text);\n }\n }\n // Label postfix\n if style.bracketed {\n self.styled_label_add_text(\"]\");\n }\n self.styled_label_end();\n }\n\n fn menubar_shortcut(&mut self, shortcut: InputKey) {\n let shortcut_letter = shortcut.value() as u8 as char;\n if shortcut_letter.is_ascii_uppercase() {\n let mut shortcut_text = ArenaString::new_in(self.arena());\n if shortcut.modifiers_contains(kbmod::CTRL) {\n shortcut_text.push_str(self.tui.modifier_translations.ctrl);\n shortcut_text.push('+');\n }\n if shortcut.modifiers_contains(kbmod::ALT) {\n shortcut_text.push_str(self.tui.modifier_translations.alt);\n shortcut_text.push('+');\n }\n if shortcut.modifiers_contains(kbmod::SHIFT) {\n shortcut_text.push_str(self.tui.modifier_translations.shift);\n shortcut_text.push('+');\n }\n shortcut_text.push(shortcut_letter);\n\n self.label(\"shortcut\", &shortcut_text);\n } else {\n self.block_begin(\"shortcut\");\n self.block_end();\n }\n self.attr_padding(Rect { left: 2, top: 0, right: 2, bottom: 0 });\n }\n}\n\n/// See [`Tree::visit_all`].\n#[derive(Clone, Copy)]\nenum VisitControl {\n Continue,\n SkipChildren,\n Stop,\n}\n\n/// Stores the root of the \"DOM\" tree of the UI.\nstruct Tree<'a> {\n tail: &'a NodeCell<'a>,\n root_first: &'a NodeCell<'a>,\n root_last: &'a NodeCell<'a>,\n last_node: &'a NodeCell<'a>,\n current_node: &'a NodeCell<'a>,\n\n count: usize,\n checksum: u64,\n}\n\nimpl<'a> Tree<'a> {\n /// Creates a new tree inside the given arena.\n /// A single root node is added for the main contents.\n fn new(arena: &'a Arena) -> Self {\n let root = Self::alloc_node(arena);\n {\n let mut r = root.borrow_mut();\n r.id = ROOT_ID;\n r.classname = \"root\";\n r.attributes.focusable = true;\n r.attributes.focus_well = true;\n }\n Self {\n tail: root,\n root_first: root,\n root_last: root,\n last_node: root,\n current_node: root,\n count: 1,\n checksum: ROOT_ID,\n }\n }\n\n fn alloc_node(arena: &'a Arena) -> &'a NodeCell<'a> {\n arena.alloc_uninit().write(Default::default())\n }\n\n /// Appends a child node to the current node.\n fn push_child(&mut self, node: &'a NodeCell<'a>) {\n let mut n = node.borrow_mut();\n n.parent = Some(self.current_node);\n n.stack_parent = Some(self.current_node);\n\n {\n let mut p = self.current_node.borrow_mut();\n n.siblings.prev = p.children.last;\n n.depth = p.depth + 1;\n\n if let Some(child_last) = p.children.last {\n let mut child_last = child_last.borrow_mut();\n child_last.siblings.next = Some(node);\n }\n if p.children.first.is_none() {\n p.children.first = Some(node);\n }\n p.children.last = Some(node);\n p.child_count += 1;\n }\n\n n.prev = Some(self.tail);\n {\n let mut tail = self.tail.borrow_mut();\n tail.next = Some(node);\n }\n self.tail = node;\n\n self.last_node = node;\n self.current_node = node;\n self.count += 1;\n // wymix is weak, but both checksum and node.id are proper random, so... it's not *that* bad.\n self.checksum = wymix(self.checksum, n.id);\n }\n\n /// Removes the current node from its parent and appends it as a new root.\n /// Used for [`Context::attr_float`].\n fn move_node_to_root(&mut self, node: &'a NodeCell<'a>, anchor: Option<&'a NodeCell<'a>>) {\n let mut n = node.borrow_mut();\n let Some(parent) = n.parent else {\n return;\n };\n\n if let Some(sibling_prev) = n.siblings.prev {\n let mut sibling_prev = sibling_prev.borrow_mut();\n sibling_prev.siblings.next = n.siblings.next;\n }\n if let Some(sibling_next) = n.siblings.next {\n let mut sibling_next = sibling_next.borrow_mut();\n sibling_next.siblings.prev = n.siblings.prev;\n }\n\n {\n let mut p = parent.borrow_mut();\n if opt_ptr_eq(p.children.first, Some(node)) {\n p.children.first = n.siblings.next;\n }\n if opt_ptr_eq(p.children.last, Some(node)) {\n p.children.last = n.siblings.prev;\n }\n p.child_count -= 1;\n }\n\n n.parent = anchor;\n n.depth = anchor.map_or(0, |n| n.borrow().depth + 1);\n n.siblings.prev = Some(self.root_last);\n n.siblings.next = None;\n\n self.root_last.borrow_mut().siblings.next = Some(node);\n self.root_last = node;\n }\n\n /// Completes the current node and moves focus to the parent.\n fn pop_stack(&mut self) {\n let current_node = self.current_node.borrow();\n if let Some(stack_parent) = current_node.stack_parent {\n self.last_node = self.current_node;\n self.current_node = stack_parent;\n }\n }\n\n fn iterate_siblings(\n mut node: Option<&'a NodeCell<'a>>,\n ) -> impl Iterator> + use<'a> {\n iter::from_fn(move || {\n let n = node?;\n node = n.borrow().siblings.next;\n Some(n)\n })\n }\n\n fn iterate_siblings_rev(\n mut node: Option<&'a NodeCell<'a>>,\n ) -> impl Iterator> + use<'a> {\n iter::from_fn(move || {\n let n = node?;\n node = n.borrow().siblings.prev;\n Some(n)\n })\n }\n\n fn iterate_roots(&self) -> impl Iterator> + use<'a> {\n Self::iterate_siblings(Some(self.root_first))\n }\n\n fn iterate_roots_rev(&self) -> impl Iterator> + use<'a> {\n Self::iterate_siblings_rev(Some(self.root_last))\n }\n\n /// Visits all nodes under and including `root` in depth order.\n /// Starts with node `start`.\n ///\n /// WARNING: Breaks in hilarious ways if `start` is not within `root`.\n fn visit_all) -> VisitControl>(\n root: &'a NodeCell<'a>,\n start: &'a NodeCell<'a>,\n forward: bool,\n mut cb: T,\n ) {\n let root_depth = root.borrow().depth;\n let mut node = start;\n let children_idx = if forward { NodeChildren::FIRST } else { NodeChildren::LAST };\n let siblings_idx = if forward { NodeSiblings::NEXT } else { NodeSiblings::PREV };\n\n while {\n 'traverse: {\n match cb(node) {\n VisitControl::Continue => {\n // Depth first search: It has a child? Go there.\n if let Some(child) = node.borrow().children.get(children_idx) {\n node = child;\n break 'traverse;\n }\n }\n VisitControl::SkipChildren => {}\n VisitControl::Stop => return,\n }\n\n loop {\n // If we hit the root while going up, we restart the traversal at\n // `root` going down again until we hit `start` again.\n let n = node.borrow();\n if n.depth <= root_depth {\n break 'traverse;\n }\n\n // Go to the parent's next sibling. --> Next subtree.\n if let Some(sibling) = n.siblings.get(siblings_idx) {\n node = sibling;\n break;\n }\n\n // Out of children? Go back to the parent.\n node = n.parent.unwrap();\n }\n }\n\n // We're done once we wrapped around to the `start`.\n !ptr::eq(node, start)\n } {}\n }\n}\n\n/// A hashmap of node IDs to nodes.\n///\n/// This map uses a simple open addressing scheme with linear probing.\n/// It's fast, simple, and sufficient for the small number of nodes we have.\nstruct NodeMap<'a> {\n slots: &'a [Option<&'a NodeCell<'a>>],\n shift: usize,\n mask: u64,\n}\n\nimpl Default for NodeMap<'static> {\n fn default() -> Self {\n Self { slots: &[None, None], shift: 63, mask: 0 }\n }\n}\n\nimpl<'a> NodeMap<'a> {\n /// Creates a new node map for the given tree.\n fn new(arena: &'a Arena, tree: &Tree<'a>) -> Self {\n // Since we aren't expected to have millions of nodes,\n // we allocate 4x the number of slots for a 25% fill factor.\n let width = (4 * tree.count + 1).ilog2().max(1) as usize;\n let slots = 1 << width;\n let shift = 64 - width;\n let mask = (slots - 1) as u64;\n\n let slots = arena.alloc_uninit_slice(slots).write_filled(None);\n let mut node = tree.root_first;\n\n loop {\n let n = node.borrow();\n let mut slot = n.id >> shift;\n\n loop {\n if slots[slot as usize].is_none() {\n slots[slot as usize] = Some(node);\n break;\n }\n slot = (slot + 1) & mask;\n }\n\n node = match n.next {\n Some(node) => node,\n None => break,\n };\n }\n\n Self { slots, shift, mask }\n }\n\n /// Gets a node by its ID.\n fn get(&mut self, id: u64) -> Option<&'a NodeCell<'a>> {\n let shift = self.shift;\n let mask = self.mask;\n let mut slot = id >> shift;\n\n loop {\n let node = self.slots[slot as usize]?;\n if node.borrow().id == id {\n return Some(node);\n }\n slot = (slot + 1) & mask;\n }\n }\n}\n\nstruct FloatAttributes {\n // Specifies the origin of the container relative to the container size. [0, 1]\n gravity_x: f32,\n gravity_y: f32,\n // Specifies an offset from the origin in cells.\n offset_x: f32,\n offset_y: f32,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeAttributes {\n float: Option,\n position: Position,\n padding: Rect,\n bg: u32,\n fg: u32,\n reverse: bool,\n bordered: bool,\n focusable: bool,\n focus_well: bool, // Prevents focus from leaving via Tab\n focus_void: bool, // Prevents focus from entering via Tab\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct ListContent<'a> {\n selected: u64,\n // Points to the Node that holds this ListContent instance, if any>.\n selected_node: Option<&'a NodeCell<'a>>,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct TableContent<'a> {\n columns: Vec,\n cell_gap: Size,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct StyledTextChunk {\n offset: usize,\n fg: u32,\n attr: Attributes,\n}\n\nconst INVALID_STYLED_TEXT_CHUNK: StyledTextChunk =\n StyledTextChunk { offset: usize::MAX, fg: 0, attr: Attributes::None };\n\n/// NOTE: Must not contain items that require drop().\nstruct TextContent<'a> {\n text: ArenaString<'a>,\n chunks: Vec,\n overflow: Overflow,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct TextareaContent<'a> {\n buffer: &'a TextBufferCell,\n\n // Carries over between frames.\n scroll_offset: Point,\n scroll_offset_y_drag_start: CoordType,\n scroll_offset_x_max: CoordType,\n thumb_height: CoordType,\n preferred_column: CoordType,\n\n single_line: bool,\n has_focus: bool,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Clone)]\nstruct ScrollareaContent {\n scroll_offset: Point,\n scroll_offset_y_drag_start: CoordType,\n thumb_height: CoordType,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nenum NodeContent<'a> {\n #[default]\n None,\n List(ListContent<'a>),\n Modal(ArenaString<'a>), // title\n Table(TableContent<'a>),\n Text(TextContent<'a>),\n Textarea(TextareaContent<'a>),\n Scrollarea(ScrollareaContent),\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeSiblings<'a> {\n prev: Option<&'a NodeCell<'a>>,\n next: Option<&'a NodeCell<'a>>,\n}\n\nimpl<'a> NodeSiblings<'a> {\n const PREV: usize = 0;\n const NEXT: usize = 1;\n\n fn get(&self, off: usize) -> Option<&'a NodeCell<'a>> {\n match off & 1 {\n 0 => self.prev,\n 1 => self.next,\n _ => unreachable!(),\n }\n }\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeChildren<'a> {\n first: Option<&'a NodeCell<'a>>,\n last: Option<&'a NodeCell<'a>>,\n}\n\nimpl<'a> NodeChildren<'a> {\n const FIRST: usize = 0;\n const LAST: usize = 1;\n\n fn get(&self, off: usize) -> Option<&'a NodeCell<'a>> {\n match off & 1 {\n 0 => self.first,\n 1 => self.last,\n _ => unreachable!(),\n }\n }\n}\n\ntype NodeCell<'a> = SemiRefCell>;\n\n/// A node in the UI tree.\n///\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct Node<'a> {\n prev: Option<&'a NodeCell<'a>>,\n next: Option<&'a NodeCell<'a>>,\n stack_parent: Option<&'a NodeCell<'a>>,\n\n id: u64,\n classname: &'static str,\n parent: Option<&'a NodeCell<'a>>,\n depth: usize,\n siblings: NodeSiblings<'a>,\n children: NodeChildren<'a>,\n child_count: usize,\n\n attributes: NodeAttributes,\n content: NodeContent<'a>,\n\n intrinsic_size: Size,\n intrinsic_size_set: bool,\n outer: Rect, // in screen-space, calculated during layout\n inner: Rect, // in screen-space, calculated during layout\n outer_clipped: Rect, // in screen-space, calculated during layout, restricted to the viewport\n inner_clipped: Rect, // in screen-space, calculated during layout, restricted to the viewport\n}\n\nimpl Node<'_> {\n /// Given an outer rectangle (including padding and borders) of this node,\n /// this returns the inner rectangle (excluding padding and borders).\n fn outer_to_inner(&self, mut outer: Rect) -> Rect {\n let l = self.attributes.bordered;\n let t = self.attributes.bordered;\n let r = self.attributes.bordered || matches!(self.content, NodeContent::Scrollarea(..));\n let b = self.attributes.bordered;\n\n outer.left += self.attributes.padding.left + l as CoordType;\n outer.top += self.attributes.padding.top + t as CoordType;\n outer.right -= self.attributes.padding.right + r as CoordType;\n outer.bottom -= self.attributes.padding.bottom + b as CoordType;\n outer\n }\n\n /// Given an intrinsic size (excluding padding and borders) of this node,\n /// this returns the outer size (including padding and borders).\n fn intrinsic_to_outer(&self) -> Size {\n let l = self.attributes.bordered;\n let t = self.attributes.bordered;\n let r = self.attributes.bordered || matches!(self.content, NodeContent::Scrollarea(..));\n let b = self.attributes.bordered;\n\n let mut size = self.intrinsic_size;\n size.width += self.attributes.padding.left\n + self.attributes.padding.right\n + l as CoordType\n + r as CoordType;\n size.height += self.attributes.padding.top\n + self.attributes.padding.bottom\n + t as CoordType\n + b as CoordType;\n size\n }\n\n /// Computes the intrinsic size of this node and its children.\n fn compute_intrinsic_size(&mut self) {\n match &mut self.content {\n NodeContent::Table(spec) => {\n // Calculate each row's height and the maximum width of each of its columns.\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n let mut row_height = 0;\n\n for (column, cell) in Tree::iterate_siblings(row.children.first).enumerate() {\n let mut cell = cell.borrow_mut();\n cell.compute_intrinsic_size();\n\n let size = cell.intrinsic_to_outer();\n\n // If the spec.columns[] value is positive, it's an absolute width.\n // Otherwise, it's a fraction of the remaining space.\n //\n // TODO: The latter is computed incorrectly.\n // Example: If the items are \"a\",\"b\",\"c\" then the intrinsic widths are [1,1,1].\n // If the column spec is [0,-3,-1], then this code assigns an intrinsic row\n // width of 3, but it should be 5 (1+1+3), because the spec says that the\n // last column (flexible 1/1) must be 3 times as wide as the 2nd one (1/3rd).\n // It's not a big deal yet, because such functionality isn't needed just yet.\n if column >= spec.columns.len() {\n spec.columns.push(0);\n }\n spec.columns[column] = spec.columns[column].max(size.width);\n\n row_height = row_height.max(size.height);\n }\n\n row.intrinsic_size.height = row_height;\n }\n\n // Assuming each column has the width of the widest cell in that column,\n // calculate the total width of the table.\n let total_gap_width =\n spec.cell_gap.width * spec.columns.len().saturating_sub(1) as CoordType;\n let total_inner_width = spec.columns.iter().sum::() + total_gap_width;\n let mut total_width = 0;\n let mut total_height = 0;\n\n // Assign the total width to each row.\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n row.intrinsic_size.width = total_inner_width;\n row.intrinsic_size_set = true;\n\n let size = row.intrinsic_to_outer();\n total_width = total_width.max(size.width);\n total_height += size.height;\n }\n\n let total_gap_height =\n spec.cell_gap.height * self.child_count.saturating_sub(1) as CoordType;\n total_height += total_gap_height;\n\n // Assign the total width/height to the table.\n if !self.intrinsic_size_set {\n self.intrinsic_size.width = total_width;\n self.intrinsic_size.height = total_height;\n self.intrinsic_size_set = true;\n }\n }\n _ => {\n let mut max_width = 0;\n let mut total_height = 0;\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n child.compute_intrinsic_size();\n\n let size = child.intrinsic_to_outer();\n max_width = max_width.max(size.width);\n total_height += size.height;\n }\n\n if !self.intrinsic_size_set {\n self.intrinsic_size.width = max_width;\n self.intrinsic_size.height = total_height;\n self.intrinsic_size_set = true;\n }\n }\n }\n }\n\n /// Lays out the children of this node.\n /// The clip rect restricts \"rendering\" to a certain area (the viewport).\n fn layout_children(&mut self, clip: Rect) {\n if self.children.first.is_none() || self.inner.is_empty() {\n return;\n }\n\n match &mut self.content {\n NodeContent::Table(spec) => {\n let width = self.inner.right - self.inner.left;\n let mut x = self.inner.left;\n let mut y = self.inner.top;\n\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n let mut size = row.intrinsic_to_outer();\n size.width = width;\n row.outer.left = x;\n row.outer.top = y;\n row.outer.right = x + size.width;\n row.outer.bottom = y + size.height;\n row.outer = row.outer.intersect(self.inner);\n row.inner = row.outer_to_inner(row.outer);\n row.outer_clipped = row.outer.intersect(clip);\n row.inner_clipped = row.inner.intersect(clip);\n\n let mut row_height = 0;\n\n for (column, cell) in Tree::iterate_siblings(row.children.first).enumerate() {\n let mut cell = cell.borrow_mut();\n let mut size = cell.intrinsic_to_outer();\n size.width = spec.columns[column];\n cell.outer.left = x;\n cell.outer.top = y;\n cell.outer.right = x + size.width;\n cell.outer.bottom = y + size.height;\n cell.outer = cell.outer.intersect(self.inner);\n cell.inner = cell.outer_to_inner(cell.outer);\n cell.outer_clipped = cell.outer.intersect(clip);\n cell.inner_clipped = cell.inner.intersect(clip);\n\n x += size.width + spec.cell_gap.width;\n row_height = row_height.max(size.height);\n\n cell.layout_children(clip);\n }\n\n x = self.inner.left;\n y += row_height + spec.cell_gap.height;\n }\n }\n NodeContent::Scrollarea(sc) => {\n let mut content = self.children.first.unwrap().borrow_mut();\n\n // content available viewport size (-1 for the track)\n let sx = self.inner.right - self.inner.left;\n let sy = self.inner.bottom - self.inner.top;\n // actual content size\n let cx = sx;\n let cy = content.intrinsic_size.height.max(sy);\n // scroll offset\n let ox = 0;\n let oy = sc.scroll_offset.y.clamp(0, cy - sy);\n\n sc.scroll_offset.x = ox;\n sc.scroll_offset.y = oy;\n\n content.outer.left = self.inner.left - ox;\n content.outer.top = self.inner.top - oy;\n content.outer.right = content.outer.left + cx;\n content.outer.bottom = content.outer.top + cy;\n content.inner = content.outer_to_inner(content.outer);\n content.outer_clipped = content.outer.intersect(self.inner_clipped);\n content.inner_clipped = content.inner.intersect(self.inner_clipped);\n\n let clip = content.inner_clipped;\n content.layout_children(clip);\n }\n _ => {\n let width = self.inner.right - self.inner.left;\n let x = self.inner.left;\n let mut y = self.inner.top;\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n let size = child.intrinsic_to_outer();\n let remaining = (width - size.width).max(0);\n\n child.outer.left = x + match child.attributes.position {\n Position::Stretch | Position::Left => 0,\n Position::Center => remaining / 2,\n Position::Right => remaining,\n };\n child.outer.right = child.outer.left\n + match child.attributes.position {\n Position::Stretch => width,\n _ => size.width,\n };\n child.outer.top = y;\n child.outer.bottom = y + size.height;\n\n child.outer = child.outer.intersect(self.inner);\n child.inner = child.outer_to_inner(child.outer);\n child.outer_clipped = child.outer.intersect(clip);\n child.inner_clipped = child.inner.intersect(clip);\n\n y += size.height;\n }\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n child.layout_children(clip);\n }\n }\n }\n }\n}\n"], ["/edit/src/buffer/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! A text buffer for a text editor.\n//!\n//! Implements a Unicode-aware, layout-aware text buffer for terminals.\n//! It's based on a gap buffer. It has no line cache and instead relies\n//! on the performance of the ucd module for fast text navigation.\n//!\n//! ---\n//!\n//! If the project ever outgrows a basic gap buffer (e.g. to add time travel)\n//! an ideal, alternative architecture would be a piece table with immutable trees.\n//! The tree nodes can be allocated on the same arena allocator as the added chunks,\n//! making lifetime management fairly easy. The algorithm is described here:\n//! * \n//! * \n//!\n//! The downside is that text navigation & search takes a performance hit due to small chunks.\n//! The solution to the former is to keep line caches, which further complicates the architecture.\n//! There's no solution for the latter. However, there's a chance that the performance will still be sufficient.\n\nmod gap_buffer;\nmod navigation;\n\nuse std::borrow::Cow;\nuse std::cell::UnsafeCell;\nuse std::collections::LinkedList;\nuse std::fmt::Write as _;\nuse std::fs::File;\nuse std::io::{Read as _, Write as _};\nuse std::mem::{self, MaybeUninit};\nuse std::ops::Range;\nuse std::rc::Rc;\nuse std::str;\n\npub use gap_buffer::GapBuffer;\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::cell::SemiRefCell;\nuse crate::clipboard::Clipboard;\nuse crate::document::{ReadableDocument, WriteableDocument};\nuse crate::framebuffer::{Framebuffer, IndexedColor};\nuse crate::helpers::*;\nuse crate::oklab::oklab_blend;\nuse crate::simd::memchr2;\nuse crate::unicode::{self, Cursor, MeasurementConfig, Utf8Chars};\nuse crate::{apperr, icu, simd};\n\n/// The margin template is used for line numbers.\n/// The max. line number we should ever expect is probably 64-bit,\n/// and so this template fits 19 digits, followed by \" │ \".\nconst MARGIN_TEMPLATE: &str = \" │ \";\n/// Just a bunch of whitespace you can use for turning tabs into spaces.\n/// Happens to reuse MARGIN_TEMPLATE, because it has sufficient whitespace.\nconst TAB_WHITESPACE: &str = MARGIN_TEMPLATE;\nconst VISUAL_SPACE: &str = \"・\";\nconst VISUAL_SPACE_PREFIX_ADD: usize = '・'.len_utf8() - 1;\nconst VISUAL_TAB: &str = \"→ \";\nconst VISUAL_TAB_PREFIX_ADD: usize = '→'.len_utf8() - 1;\n\n/// Stores statistics about the whole document.\n#[derive(Copy, Clone)]\npub struct TextBufferStatistics {\n logical_lines: CoordType,\n visual_lines: CoordType,\n}\n\n/// Stores the active text selection anchors.\n///\n/// The two points are not sorted. Instead, `beg` refers to where the selection\n/// started being made and `end` refers to the currently being updated position.\n#[derive(Copy, Clone)]\nstruct TextBufferSelection {\n beg: Point,\n end: Point,\n}\n\n/// In order to group actions into a single undo step,\n/// we need to know the type of action that was performed.\n/// This stores the action type.\n#[derive(Copy, Clone, Eq, PartialEq)]\nenum HistoryType {\n Other,\n Write,\n Delete,\n}\n\n/// An undo/redo entry.\nstruct HistoryEntry {\n /// [`TextBuffer::cursor`] position before the change was made.\n cursor_before: Point,\n /// [`TextBuffer::selection`] before the change was made.\n selection_before: Option,\n /// [`TextBuffer::stats`] before the change was made.\n stats_before: TextBufferStatistics,\n /// [`GapBuffer::generation`] before the change was made.\n ///\n /// **NOTE:** Entries with the same generation are grouped together.\n generation_before: u32,\n /// Logical cursor position where the change took place.\n /// The position is at the start of the changed range.\n cursor: Point,\n /// Text that was deleted from the buffer.\n deleted: Vec,\n /// Text that was added to the buffer.\n added: Vec,\n}\n\n/// Caches an ICU search operation.\nstruct ActiveSearch {\n /// The search pattern.\n pattern: String,\n /// The search options.\n options: SearchOptions,\n /// The ICU `UText` object.\n text: icu::Text,\n /// The ICU `URegularExpression` object.\n regex: icu::Regex,\n /// [`GapBuffer::generation`] when the search was created.\n /// This is used to detect if we need to refresh the\n /// [`ActiveSearch::regex`] object.\n buffer_generation: u32,\n /// [`TextBuffer::selection_generation`] when the search was\n /// created. When the user manually selects text, we need to\n /// refresh the [`ActiveSearch::pattern`] with it.\n selection_generation: u32,\n /// Stores the text buffer offset in between searches.\n next_search_offset: usize,\n /// If we know there were no hits, we can skip searching.\n no_matches: bool,\n}\n\n/// Options for a search operation.\n#[derive(Default, Clone, Copy, Eq, PartialEq)]\npub struct SearchOptions {\n /// If true, the search is case-sensitive.\n pub match_case: bool,\n /// If true, the search matches whole words.\n pub whole_word: bool,\n /// If true, the search uses regex.\n pub use_regex: bool,\n}\n\nenum RegexReplacement<'a> {\n Group(i32),\n Text(Vec),\n}\n\n/// Caches the start and length of the active edit line for a single edit.\n/// This helps us avoid having to remeasure the buffer after an edit.\nstruct ActiveEditLineInfo {\n /// Points to the start of the currently being edited line.\n safe_start: Cursor,\n /// Number of visual rows of the line that starts\n /// at [`ActiveEditLineInfo::safe_start`].\n line_height_in_rows: CoordType,\n /// Byte distance from the start of the line at\n /// [`ActiveEditLineInfo::safe_start`] to the next line.\n distance_next_line_start: usize,\n}\n\n/// Undo/redo grouping works by recording a set of \"overrides\",\n/// which are then applied in [`TextBuffer::edit_begin()`].\n/// This allows us to create a group of edits that all share a\n/// common `generation_before` and can be undone/redone together.\n/// This struct stores those overrides.\nstruct ActiveEditGroupInfo {\n /// [`TextBuffer::cursor`] position before the change was made.\n cursor_before: Point,\n /// [`TextBuffer::selection`] before the change was made.\n selection_before: Option,\n /// [`TextBuffer::stats`] before the change was made.\n stats_before: TextBufferStatistics,\n /// [`GapBuffer::generation`] before the change was made.\n ///\n /// **NOTE:** Entries with the same generation are grouped together.\n generation_before: u32,\n}\n\n/// Char- or word-wise navigation? Your choice.\npub enum CursorMovement {\n Grapheme,\n Word,\n}\n\n/// See [`TextBuffer::move_selected_lines`].\npub enum MoveLineDirection {\n Up,\n Down,\n}\n\n/// The result of a call to [`TextBuffer::render()`].\npub struct RenderResult {\n /// The maximum visual X position we encountered during rendering.\n pub visual_pos_x_max: CoordType,\n}\n\n/// A [`TextBuffer`] with inner mutability.\npub type TextBufferCell = SemiRefCell;\n\n/// A [`TextBuffer`] inside an [`Rc`].\n///\n/// We need this because the TUI system needs to borrow\n/// the given text buffer(s) until after the layout process.\npub type RcTextBuffer = Rc;\n\n/// A text buffer for a text editor.\npub struct TextBuffer {\n buffer: GapBuffer,\n\n undo_stack: LinkedList>,\n redo_stack: LinkedList>,\n last_history_type: HistoryType,\n last_save_generation: u32,\n\n active_edit_group: Option,\n active_edit_line_info: Option,\n active_edit_depth: i32,\n active_edit_off: usize,\n\n stats: TextBufferStatistics,\n cursor: Cursor,\n // When scrolling significant amounts of text away from the cursor,\n // rendering will naturally slow down proportionally to the distance.\n // To avoid this, we cache the cursor position for rendering.\n // Must be cleared on every edit or reflow.\n cursor_for_rendering: Option,\n selection: Option,\n selection_generation: u32,\n search: Option>,\n\n width: CoordType,\n margin_width: CoordType,\n margin_enabled: bool,\n word_wrap_column: CoordType,\n word_wrap_enabled: bool,\n tab_size: CoordType,\n indent_with_tabs: bool,\n line_highlight_enabled: bool,\n ruler: CoordType,\n encoding: &'static str,\n newlines_are_crlf: bool,\n insert_final_newline: bool,\n overtype: bool,\n\n wants_cursor_visibility: bool,\n}\n\nimpl TextBuffer {\n /// Creates a new text buffer inside an [`Rc`].\n /// See [`TextBuffer::new()`].\n pub fn new_rc(small: bool) -> apperr::Result {\n let buffer = Self::new(small)?;\n Ok(Rc::new(SemiRefCell::new(buffer)))\n }\n\n /// Creates a new text buffer. With `small` you can control\n /// if the buffer is optimized for <1MiB contents.\n pub fn new(small: bool) -> apperr::Result {\n Ok(Self {\n buffer: GapBuffer::new(small)?,\n\n undo_stack: LinkedList::new(),\n redo_stack: LinkedList::new(),\n last_history_type: HistoryType::Other,\n last_save_generation: 0,\n\n active_edit_group: None,\n active_edit_line_info: None,\n active_edit_depth: 0,\n active_edit_off: 0,\n\n stats: TextBufferStatistics { logical_lines: 1, visual_lines: 1 },\n cursor: Default::default(),\n cursor_for_rendering: None,\n selection: None,\n selection_generation: 0,\n search: None,\n\n width: 0,\n margin_width: 0,\n margin_enabled: false,\n word_wrap_column: 0,\n word_wrap_enabled: false,\n tab_size: 4,\n indent_with_tabs: false,\n line_highlight_enabled: false,\n ruler: 0,\n encoding: \"UTF-8\",\n newlines_are_crlf: cfg!(windows), // Windows users want CRLF\n insert_final_newline: false,\n overtype: false,\n\n wants_cursor_visibility: false,\n })\n }\n\n /// Length of the document in bytes.\n pub fn text_length(&self) -> usize {\n self.buffer.len()\n }\n\n /// Number of logical lines in the document,\n /// that is, lines separated by newlines.\n pub fn logical_line_count(&self) -> CoordType {\n self.stats.logical_lines\n }\n\n /// Number of visual lines in the document,\n /// that is, the number of lines after layout.\n pub fn visual_line_count(&self) -> CoordType {\n self.stats.visual_lines\n }\n\n /// Does the buffer need to be saved?\n pub fn is_dirty(&self) -> bool {\n self.last_save_generation != self.buffer.generation()\n }\n\n /// The buffer generation changes on every edit.\n /// With this you can check if it has changed since\n /// the last time you called this function.\n pub fn generation(&self) -> u32 {\n self.buffer.generation()\n }\n\n /// Force the buffer to be dirty.\n pub fn mark_as_dirty(&mut self) {\n self.last_save_generation = self.buffer.generation().wrapping_sub(1);\n }\n\n fn mark_as_clean(&mut self) {\n self.last_save_generation = self.buffer.generation();\n }\n\n /// The encoding used during reading/writing. \"UTF-8\" is the default.\n pub fn encoding(&self) -> &'static str {\n self.encoding\n }\n\n /// Set the encoding used during reading/writing.\n pub fn set_encoding(&mut self, encoding: &'static str) {\n if self.encoding != encoding {\n self.encoding = encoding;\n self.mark_as_dirty();\n }\n }\n\n /// The newline type used in the document. LF or CRLF.\n pub fn is_crlf(&self) -> bool {\n self.newlines_are_crlf\n }\n\n /// Changes the newline type without normalizing the document.\n pub fn set_crlf(&mut self, crlf: bool) {\n self.newlines_are_crlf = crlf;\n }\n\n /// Changes the newline type used in the document.\n ///\n /// NOTE: Cannot be undone.\n pub fn normalize_newlines(&mut self, crlf: bool) {\n let newline: &[u8] = if crlf { b\"\\r\\n\" } else { b\"\\n\" };\n let mut off = 0;\n\n let mut cursor_offset = self.cursor.offset;\n let mut cursor_for_rendering_offset =\n self.cursor_for_rendering.map_or(cursor_offset, |c| c.offset);\n\n #[cfg(debug_assertions)]\n let mut adjusted_newlines = 0;\n\n 'outer: loop {\n // Seek to the offset of the next line start.\n loop {\n let chunk = self.read_forward(off);\n if chunk.is_empty() {\n break 'outer;\n }\n\n let (delta, line) = simd::lines_fwd(chunk, 0, 0, 1);\n off += delta;\n if line == 1 {\n break;\n }\n }\n\n // Get the preceding newline.\n let chunk = self.read_backward(off);\n let chunk_newline_len = if chunk.ends_with(b\"\\r\\n\") { 2 } else { 1 };\n let chunk_newline = &chunk[chunk.len() - chunk_newline_len..];\n\n if chunk_newline != newline {\n // If this newline is still before our cursor position, then it still has an effect on its offset.\n // Any newline adjustments past that cursor position are irrelevant.\n let delta = newline.len() as isize - chunk_newline_len as isize;\n if off <= cursor_offset {\n cursor_offset = cursor_offset.saturating_add_signed(delta);\n #[cfg(debug_assertions)]\n {\n adjusted_newlines += 1;\n }\n }\n if off <= cursor_for_rendering_offset {\n cursor_for_rendering_offset =\n cursor_for_rendering_offset.saturating_add_signed(delta);\n }\n\n // Replace the newline.\n off -= chunk_newline_len;\n self.buffer.replace(off..off + chunk_newline_len, newline);\n off += newline.len();\n }\n }\n\n // If this fails, the cursor offset calculation above is wrong.\n #[cfg(debug_assertions)]\n debug_assert_eq!(adjusted_newlines, self.cursor.logical_pos.y);\n\n self.cursor.offset = cursor_offset;\n if let Some(cursor) = &mut self.cursor_for_rendering {\n cursor.offset = cursor_for_rendering_offset;\n }\n\n self.newlines_are_crlf = crlf;\n }\n\n /// If enabled, automatically insert a final newline\n /// when typing at the end of the file.\n pub fn set_insert_final_newline(&mut self, enabled: bool) {\n self.insert_final_newline = enabled;\n }\n\n /// Whether to insert or overtype text when writing.\n pub fn is_overtype(&self) -> bool {\n self.overtype\n }\n\n /// Set the overtype mode.\n pub fn set_overtype(&mut self, overtype: bool) {\n self.overtype = overtype;\n }\n\n /// Gets the logical cursor position, that is,\n /// the position in lines and graphemes per line.\n pub fn cursor_logical_pos(&self) -> Point {\n self.cursor.logical_pos\n }\n\n /// Gets the visual cursor position, that is,\n /// the position in laid out rows and columns.\n pub fn cursor_visual_pos(&self) -> Point {\n self.cursor.visual_pos\n }\n\n /// Gets the width of the left margin.\n pub fn margin_width(&self) -> CoordType {\n self.margin_width\n }\n\n /// Is the left margin enabled?\n pub fn set_margin_enabled(&mut self, enabled: bool) -> bool {\n if self.margin_enabled == enabled {\n false\n } else {\n self.margin_enabled = enabled;\n self.reflow();\n true\n }\n }\n\n /// Gets the width of the text contents for layout.\n pub fn text_width(&self) -> CoordType {\n self.width - self.margin_width\n }\n\n /// Ask the TUI system to scroll the buffer and make the cursor visible.\n ///\n /// TODO: This function shows that [`TextBuffer`] is poorly abstracted\n /// away from the TUI system. The only reason this exists is so that\n /// if someone outside the TUI code enables word-wrap, the TUI code\n /// recognizes this and scrolls the cursor into view. But outside of this\n /// scrolling, views, etc., are all UI concerns = this should not be here.\n pub fn make_cursor_visible(&mut self) {\n self.wants_cursor_visibility = true;\n }\n\n /// For the TUI code to retrieve a prior [`TextBuffer::make_cursor_visible()`] request.\n pub fn take_cursor_visibility_request(&mut self) -> bool {\n mem::take(&mut self.wants_cursor_visibility)\n }\n\n /// Is word-wrap enabled?\n ///\n /// Technically, this is a misnomer, because it's line-wrapping.\n pub fn is_word_wrap_enabled(&self) -> bool {\n self.word_wrap_enabled\n }\n\n /// Enable or disable word-wrap.\n ///\n /// NOTE: It's expected that the tui code calls `set_width()` sometime after this.\n /// This will then trigger the actual recalculation of the cursor position.\n pub fn set_word_wrap(&mut self, enabled: bool) {\n if self.word_wrap_enabled != enabled {\n self.word_wrap_enabled = enabled;\n self.width = 0; // Force a reflow.\n self.make_cursor_visible();\n }\n }\n\n /// Set the width available for layout.\n ///\n /// Ideally this would be a pure UI concern, but the text buffer needs this\n /// so that it can abstract away visual cursor movement such as \"go a line up\".\n /// What would that even mean if it didn't know how wide a line is?\n pub fn set_width(&mut self, width: CoordType) -> bool {\n if width <= 0 || width == self.width {\n false\n } else {\n self.width = width;\n self.reflow();\n true\n }\n }\n\n /// Set the tab width. Could be anything, but is expected to be 1-8.\n pub fn tab_size(&self) -> CoordType {\n self.tab_size\n }\n\n /// Set the tab size. Clamped to 1-8.\n pub fn set_tab_size(&mut self, width: CoordType) -> bool {\n let width = width.clamp(1, 8);\n if width == self.tab_size {\n false\n } else {\n self.tab_size = width;\n self.reflow();\n true\n }\n }\n\n /// Calculates the amount of spaces a tab key press would insert at the given column.\n /// This also equals the visual width of an actual tab character.\n ///\n /// This exists because Rust doesn't have range constraints yet, and without\n /// them assembly blows up in size by 7x. It's a recurring issue with Rust.\n #[inline]\n fn tab_size_eval(&self, column: CoordType) -> CoordType {\n // SAFETY: `set_tab_size` clamps `self.tab_size` to 1-8.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1 && self.tab_size <= 8) };\n self.tab_size - (column % self.tab_size)\n }\n\n /// If the cursor is at an indentation of `column`, this returns\n /// the column to which a backspace key press would delete to.\n #[inline]\n fn tab_size_prev_column(&self, column: CoordType) -> CoordType {\n // SAFETY: `set_tab_size` clamps `self.tab_size` to 1-8.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1 && self.tab_size <= 8) };\n (column - 1).max(0) / self.tab_size * self.tab_size\n }\n\n /// Returns whether tabs are used for indentation.\n pub fn indent_with_tabs(&self) -> bool {\n self.indent_with_tabs\n }\n\n /// Sets whether tabs or spaces are used for indentation.\n pub fn set_indent_with_tabs(&mut self, indent_with_tabs: bool) {\n self.indent_with_tabs = indent_with_tabs;\n }\n\n /// Sets whether the line the cursor is on should be highlighted.\n pub fn set_line_highlight_enabled(&mut self, enabled: bool) {\n self.line_highlight_enabled = enabled;\n }\n\n /// Sets a ruler column, e.g. 80.\n pub fn set_ruler(&mut self, column: CoordType) {\n self.ruler = column;\n }\n\n pub fn reflow(&mut self) {\n self.reflow_internal(true);\n }\n\n fn recalc_after_content_changed(&mut self) {\n self.reflow_internal(false);\n }\n\n fn reflow_internal(&mut self, force: bool) {\n let word_wrap_column_before = self.word_wrap_column;\n\n {\n // +1 onto logical_lines, because line numbers are 1-based.\n // +1 onto log10, because we want the digit width and not the actual log10.\n // +3 onto log10, because we append \" | \" to the line numbers to form the margin.\n self.margin_width = if self.margin_enabled {\n self.stats.logical_lines.ilog10() as CoordType + 4\n } else {\n 0\n };\n\n let text_width = self.text_width();\n // 2 columns are required, because otherwise wide glyphs wouldn't ever fit.\n self.word_wrap_column =\n if self.word_wrap_enabled && text_width >= 2 { text_width } else { 0 };\n }\n\n self.cursor_for_rendering = None;\n\n if force || self.word_wrap_column != word_wrap_column_before {\n // Recalculate the cursor position.\n self.cursor = self.cursor_move_to_logical_internal(\n if self.word_wrap_column > 0 {\n Default::default()\n } else {\n self.goto_line_start(self.cursor, self.cursor.logical_pos.y)\n },\n self.cursor.logical_pos,\n );\n\n // Recalculate the line statistics.\n if self.word_wrap_column > 0 {\n let end = self.cursor_move_to_logical_internal(self.cursor, Point::MAX);\n self.stats.visual_lines = end.visual_pos.y + 1;\n } else {\n self.stats.visual_lines = self.stats.logical_lines;\n }\n }\n }\n\n /// Replaces the entire buffer contents with the given `text`.\n /// Assumes that the line count doesn't change.\n pub fn copy_from_str(&mut self, text: &dyn ReadableDocument) {\n if self.buffer.copy_from(text) {\n self.recalc_after_content_swap();\n self.cursor_move_to_logical(Point { x: CoordType::MAX, y: 0 });\n\n let delete = self.buffer.len() - self.cursor.offset;\n if delete != 0 {\n self.buffer.allocate_gap(self.cursor.offset, 0, delete);\n }\n }\n }\n\n fn recalc_after_content_swap(&mut self) {\n // If the buffer was changed, nothing we previously saved can be relied upon.\n self.undo_stack.clear();\n self.redo_stack.clear();\n self.last_history_type = HistoryType::Other;\n self.cursor = Default::default();\n self.set_selection(None);\n self.mark_as_clean();\n self.reflow();\n }\n\n /// Copies the contents of the buffer into a string.\n pub fn save_as_string(&mut self, dst: &mut dyn WriteableDocument) {\n self.buffer.copy_into(dst);\n self.mark_as_clean();\n }\n\n /// Reads a file from disk into the text buffer, detecting encoding and BOM.\n pub fn read_file(\n &mut self,\n file: &mut File,\n encoding: Option<&'static str>,\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let mut buf = scratch.alloc_uninit().transpose();\n let mut first_chunk_len = 0;\n let mut read = 0;\n\n // Read enough bytes to detect the BOM.\n while first_chunk_len < BOM_MAX_LEN {\n read = file_read_uninit(file, &mut buf[first_chunk_len..])?;\n if read == 0 {\n break;\n }\n first_chunk_len += read;\n }\n\n if let Some(encoding) = encoding {\n self.encoding = encoding;\n } else {\n let bom = detect_bom(unsafe { buf[..first_chunk_len].assume_init_ref() });\n self.encoding = bom.unwrap_or(\"UTF-8\");\n }\n\n // TODO: Since reading the file can fail, we should ensure that we also reset the cursor here.\n // I don't do it, so that `recalc_after_content_swap()` works.\n self.buffer.clear();\n\n let done = read == 0;\n if self.encoding == \"UTF-8\" {\n self.read_file_as_utf8(file, &mut buf, first_chunk_len, done)?;\n } else {\n self.read_file_with_icu(file, &mut buf, first_chunk_len, done)?;\n }\n\n // Figure out\n // * the logical line count\n // * the newline type (LF or CRLF)\n // * the indentation type (tabs or spaces)\n // * whether there's a final newline\n {\n let chunk = self.read_forward(0);\n let mut offset = 0;\n let mut lines = 0;\n // Number of lines ending in CRLF.\n let mut crlf_count = 0;\n // Number of lines starting with a tab.\n let mut tab_indentations = 0;\n // Number of lines starting with a space.\n let mut space_indentations = 0;\n // Histogram of the indentation depth of lines starting with between 2 and 8 spaces.\n // In other words, `space_indentation_sizes[0]` is the number of lines starting with 2 spaces.\n let mut space_indentation_sizes = [0; 7];\n\n loop {\n // Check if the line starts with a tab.\n if offset < chunk.len() && chunk[offset] == b'\\t' {\n tab_indentations += 1;\n } else {\n // Otherwise, check how many spaces the line starts with. Searching for >8 spaces\n // allows us to reject lines that have more than 1 level of indentation.\n let space_indentation =\n chunk[offset..].iter().take(9).take_while(|&&c| c == b' ').count();\n\n // We'll also reject lines starting with 1 space, because that's too fickle as a heuristic.\n if (2..=8).contains(&space_indentation) {\n space_indentations += 1;\n\n // If we encounter an indentation depth of 6, it may either be a 6-space indentation,\n // two 3-space indentation or 3 2-space indentations. To make this work, we increment\n // all 3 possible histogram slots.\n // 2 -> 2\n // 3 -> 3\n // 4 -> 4 2\n // 5 -> 5\n // 6 -> 6 3 2\n // 7 -> 7\n // 8 -> 8 4 2\n space_indentation_sizes[space_indentation - 2] += 1;\n if space_indentation & 4 != 0 {\n space_indentation_sizes[0] += 1;\n }\n if space_indentation == 6 || space_indentation == 8 {\n space_indentation_sizes[space_indentation / 2 - 2] += 1;\n }\n }\n }\n\n (offset, lines) = simd::lines_fwd(chunk, offset, lines, lines + 1);\n\n // Check if the preceding line ended in CRLF.\n if offset >= 2 && &chunk[offset - 2..offset] == b\"\\r\\n\" {\n crlf_count += 1;\n }\n\n // We'll limit our heuristics to the first 1000 lines.\n // That should hopefully be enough in practice.\n if offset >= chunk.len() || lines >= 1000 {\n break;\n }\n }\n\n // We'll assume CRLF if more than half of the lines end in CRLF.\n let newlines_are_crlf = crlf_count >= lines / 2;\n\n // We'll assume tabs if there are more lines starting with tabs than with spaces.\n let indent_with_tabs = tab_indentations > space_indentations;\n let tab_size = if indent_with_tabs {\n // Tabs will get a visual size of 4 spaces by default.\n 4\n } else {\n // Otherwise, we'll assume the most common indentation depth.\n // If there are conflicting indentation depths, we'll prefer the maximum, because in the loop\n // above we incremented the histogram slot for 2-spaces when encountering 4-spaces and so on.\n let mut max = 1;\n let mut tab_size = 4;\n for (i, &count) in space_indentation_sizes.iter().enumerate() {\n if count >= max {\n max = count;\n tab_size = i as CoordType + 2;\n }\n }\n tab_size\n };\n\n // If the file has more than 1000 lines, figure out how many are remaining.\n if offset < chunk.len() {\n (_, lines) = simd::lines_fwd(chunk, offset, lines, CoordType::MAX);\n }\n\n let final_newline = chunk.ends_with(b\"\\n\");\n\n // Add 1, because the last line doesn't end in a newline (it ends in the literal end).\n self.stats.logical_lines = lines + 1;\n self.stats.visual_lines = self.stats.logical_lines;\n self.newlines_are_crlf = newlines_are_crlf;\n self.insert_final_newline = final_newline;\n self.indent_with_tabs = indent_with_tabs;\n self.tab_size = tab_size;\n }\n\n self.recalc_after_content_swap();\n Ok(())\n }\n\n fn read_file_as_utf8(\n &mut self,\n file: &mut File,\n buf: &mut [MaybeUninit; 4 * KIBI],\n first_chunk_len: usize,\n done: bool,\n ) -> apperr::Result<()> {\n {\n let mut first_chunk = unsafe { buf[..first_chunk_len].assume_init_ref() };\n if first_chunk.starts_with(b\"\\xEF\\xBB\\xBF\") {\n first_chunk = &first_chunk[3..];\n self.encoding = \"UTF-8 BOM\";\n }\n\n self.buffer.replace(0..0, first_chunk);\n }\n\n if done {\n return Ok(());\n }\n\n // If we don't have file metadata, the input may be a pipe or a socket.\n // Every read will have the same size until we hit the end.\n let mut chunk_size = 128 * KIBI;\n let mut extra_chunk_size = 128 * KIBI;\n\n if let Ok(m) = file.metadata() {\n // Usually the next read of size `chunk_size` will read the entire file,\n // but if the size has changed for some reason, then `extra_chunk_size`\n // should be large enough to read the rest of the file.\n // 4KiB is not too large and not too slow.\n let len = m.len() as usize;\n chunk_size = len.saturating_sub(first_chunk_len);\n extra_chunk_size = 4 * KIBI;\n }\n\n loop {\n let gap = self.buffer.allocate_gap(self.text_length(), chunk_size, 0);\n if gap.is_empty() {\n break;\n }\n\n let read = file.read(gap)?;\n if read == 0 {\n break;\n }\n\n self.buffer.commit_gap(read);\n chunk_size = extra_chunk_size;\n }\n\n Ok(())\n }\n\n fn read_file_with_icu(\n &mut self,\n file: &mut File,\n buf: &mut [MaybeUninit; 4 * KIBI],\n first_chunk_len: usize,\n mut done: bool,\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let pivot_buffer = scratch.alloc_uninit_slice(4 * KIBI);\n let mut c = icu::Converter::new(pivot_buffer, self.encoding, \"UTF-8\")?;\n let mut first_chunk = unsafe { buf[..first_chunk_len].assume_init_ref() };\n\n while !first_chunk.is_empty() {\n let off = self.text_length();\n let gap = self.buffer.allocate_gap(off, 8 * KIBI, 0);\n let (input_advance, mut output_advance) =\n c.convert(first_chunk, slice_as_uninit_mut(gap))?;\n\n // Remove the BOM from the file, if this is the first chunk.\n // Our caller ensures to only call us once the BOM has been identified,\n // which means that if there's a BOM it must be wholly contained in this chunk.\n if off == 0 {\n let written = &mut gap[..output_advance];\n if written.starts_with(b\"\\xEF\\xBB\\xBF\") {\n written.copy_within(3.., 0);\n output_advance -= 3;\n }\n }\n\n self.buffer.commit_gap(output_advance);\n first_chunk = &first_chunk[input_advance..];\n }\n\n let mut buf_len = 0;\n\n loop {\n if !done {\n let read = file_read_uninit(file, &mut buf[buf_len..])?;\n buf_len += read;\n done = read == 0;\n }\n\n let gap = self.buffer.allocate_gap(self.text_length(), 8 * KIBI, 0);\n if gap.is_empty() {\n break;\n }\n\n let read = unsafe { buf[..buf_len].assume_init_ref() };\n let (input_advance, output_advance) = c.convert(read, slice_as_uninit_mut(gap))?;\n\n self.buffer.commit_gap(output_advance);\n\n let flush = done && buf_len == 0;\n buf_len -= input_advance;\n buf.copy_within(input_advance.., 0);\n\n if flush {\n break;\n }\n }\n\n Ok(())\n }\n\n /// Writes the text buffer contents to a file, handling BOM and encoding.\n pub fn write_file(&mut self, file: &mut File) -> apperr::Result<()> {\n let mut offset = 0;\n\n if self.encoding.starts_with(\"UTF-8\") {\n if self.encoding == \"UTF-8 BOM\" {\n file.write_all(b\"\\xEF\\xBB\\xBF\")?;\n }\n loop {\n let chunk = self.read_forward(offset);\n if chunk.is_empty() {\n break;\n }\n file.write_all(chunk)?;\n offset += chunk.len();\n }\n } else {\n self.write_file_with_icu(file)?;\n }\n\n self.mark_as_clean();\n Ok(())\n }\n\n fn write_file_with_icu(&mut self, file: &mut File) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let pivot_buffer = scratch.alloc_uninit_slice(4 * KIBI);\n let buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut c = icu::Converter::new(pivot_buffer, \"UTF-8\", self.encoding)?;\n let mut offset = 0;\n\n // Write the BOM for the encodings we know need it.\n if self.encoding.starts_with(\"UTF-16\")\n || self.encoding.starts_with(\"UTF-32\")\n || self.encoding == \"GB18030\"\n {\n let (_, output_advance) = c.convert(b\"\\xEF\\xBB\\xBF\", buf)?;\n let chunk = unsafe { buf[..output_advance].assume_init_ref() };\n file.write_all(chunk)?;\n }\n\n loop {\n let chunk = self.read_forward(offset);\n let (input_advance, output_advance) = c.convert(chunk, buf)?;\n let chunk = unsafe { buf[..output_advance].assume_init_ref() };\n\n file.write_all(chunk)?;\n offset += input_advance;\n\n if chunk.is_empty() {\n break;\n }\n }\n\n Ok(())\n }\n\n /// Returns the current selection.\n pub fn has_selection(&self) -> bool {\n self.selection.is_some()\n }\n\n fn set_selection(&mut self, selection: Option) -> u32 {\n self.selection = selection.filter(|s| s.beg != s.end);\n self.selection_generation = self.selection_generation.wrapping_add(1);\n self.selection_generation\n }\n\n /// Moves the cursor by `offset` and updates the selection to contain it.\n pub fn selection_update_offset(&mut self, offset: usize) {\n self.set_cursor_for_selection(self.cursor_move_to_offset_internal(self.cursor, offset));\n }\n\n /// Moves the cursor to `visual_pos` and updates the selection to contain it.\n pub fn selection_update_visual(&mut self, visual_pos: Point) {\n self.set_cursor_for_selection(self.cursor_move_to_visual_internal(self.cursor, visual_pos));\n }\n\n /// Moves the cursor to `logical_pos` and updates the selection to contain it.\n pub fn selection_update_logical(&mut self, logical_pos: Point) {\n self.set_cursor_for_selection(\n self.cursor_move_to_logical_internal(self.cursor, logical_pos),\n );\n }\n\n /// Moves the cursor by `delta` and updates the selection to contain it.\n pub fn selection_update_delta(&mut self, granularity: CursorMovement, delta: CoordType) {\n self.set_cursor_for_selection(self.cursor_move_delta_internal(\n self.cursor,\n granularity,\n delta,\n ));\n }\n\n /// Select the current word.\n pub fn select_word(&mut self) {\n let Range { start, end } = navigation::word_select(&self.buffer, self.cursor.offset);\n let beg = self.cursor_move_to_offset_internal(self.cursor, start);\n let end = self.cursor_move_to_offset_internal(beg, end);\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Select the current line.\n pub fn select_line(&mut self) {\n let beg = self.cursor_move_to_logical_internal(\n self.cursor,\n Point { x: 0, y: self.cursor.logical_pos.y },\n );\n let end = self\n .cursor_move_to_logical_internal(beg, Point { x: 0, y: self.cursor.logical_pos.y + 1 });\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Select the entire document.\n pub fn select_all(&mut self) {\n let beg = Default::default();\n let end = self.cursor_move_to_logical_internal(beg, Point::MAX);\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Starts a new selection, if there's none already.\n pub fn start_selection(&mut self) {\n if self.selection.is_none() {\n self.set_selection(Some(TextBufferSelection {\n beg: self.cursor.logical_pos,\n end: self.cursor.logical_pos,\n }));\n }\n }\n\n /// Destroy the current selection.\n pub fn clear_selection(&mut self) -> bool {\n let had_selection = self.selection.is_some();\n self.set_selection(None);\n had_selection\n }\n\n /// Find the next occurrence of the given `pattern` and select it.\n pub fn find_and_select(&mut self, pattern: &str, options: SearchOptions) -> apperr::Result<()> {\n if let Some(search) = &mut self.search {\n let search = search.get_mut();\n // When the search input changes we must reset the search.\n if search.pattern != pattern || search.options != options {\n self.search = None;\n }\n\n // When transitioning from some search to no search, we must clear the selection.\n if pattern.is_empty()\n && let Some(TextBufferSelection { beg, .. }) = self.selection\n {\n self.cursor_move_to_logical(beg);\n }\n }\n\n if pattern.is_empty() {\n return Ok(());\n }\n\n let search = match &self.search {\n Some(search) => unsafe { &mut *search.get() },\n None => {\n let search = self.find_construct_search(pattern, options)?;\n self.search = Some(UnsafeCell::new(search));\n unsafe { &mut *self.search.as_ref().unwrap().get() }\n }\n };\n\n // If we previously searched through the entire document and found 0 matches,\n // then we can avoid searching again.\n if search.no_matches {\n return Ok(());\n }\n\n // If the user moved the cursor since the last search, but the needle remained the same,\n // we still need to move the start of the search to the new cursor position.\n let next_search_offset = match self.selection {\n Some(TextBufferSelection { beg, end }) => {\n if self.selection_generation == search.selection_generation {\n search.next_search_offset\n } else {\n self.cursor_move_to_logical_internal(self.cursor, beg.min(end)).offset\n }\n }\n _ => self.cursor.offset,\n };\n\n self.find_select_next(search, next_search_offset, true);\n Ok(())\n }\n\n /// Find the next occurrence of the given `pattern` and replace it with `replacement`.\n pub fn find_and_replace(\n &mut self,\n pattern: &str,\n options: SearchOptions,\n replacement: &[u8],\n ) -> apperr::Result<()> {\n // Editors traditionally replace the previous search hit, not the next possible one.\n if let (Some(search), Some(..)) = (&self.search, &self.selection) {\n let search = unsafe { &mut *search.get() };\n if search.selection_generation == self.selection_generation {\n let scratch = scratch_arena(None);\n let parsed_replacements =\n Self::find_parse_replacement(&scratch, &mut *search, replacement);\n let replacement =\n self.find_fill_replacement(&mut *search, replacement, &parsed_replacements);\n self.write(&replacement, self.cursor, true);\n }\n }\n\n self.find_and_select(pattern, options)\n }\n\n /// Find all occurrences of the given `pattern` and replace them with `replacement`.\n pub fn find_and_replace_all(\n &mut self,\n pattern: &str,\n options: SearchOptions,\n replacement: &[u8],\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let mut search = self.find_construct_search(pattern, options)?;\n let mut offset = 0;\n let parsed_replacements = Self::find_parse_replacement(&scratch, &mut search, replacement);\n\n loop {\n self.find_select_next(&mut search, offset, false);\n if !self.has_selection() {\n break;\n }\n\n let replacement =\n self.find_fill_replacement(&mut search, replacement, &parsed_replacements);\n self.write(&replacement, self.cursor, true);\n offset = self.cursor.offset;\n }\n\n Ok(())\n }\n\n fn find_construct_search(\n &self,\n pattern: &str,\n options: SearchOptions,\n ) -> apperr::Result {\n if pattern.is_empty() {\n return Err(apperr::Error::Icu(1)); // U_ILLEGAL_ARGUMENT_ERROR\n }\n\n let sanitized_pattern = if options.whole_word && options.use_regex {\n Cow::Owned(format!(r\"\\b(?:{pattern})\\b\"))\n } else if options.whole_word {\n let mut p = String::with_capacity(pattern.len() + 16);\n p.push_str(r\"\\b\");\n\n // Escape regex special characters.\n let b = unsafe { p.as_mut_vec() };\n for &byte in pattern.as_bytes() {\n match byte {\n b'*' | b'?' | b'+' | b'[' | b'(' | b')' | b'{' | b'}' | b'^' | b'$' | b'|'\n | b'\\\\' | b'.' => {\n b.push(b'\\\\');\n b.push(byte);\n }\n _ => b.push(byte),\n }\n }\n\n p.push_str(r\"\\b\");\n Cow::Owned(p)\n } else {\n Cow::Borrowed(pattern)\n };\n\n let mut flags = icu::Regex::MULTILINE;\n if !options.match_case {\n flags |= icu::Regex::CASE_INSENSITIVE;\n }\n if !options.use_regex && !options.whole_word {\n flags |= icu::Regex::LITERAL;\n }\n\n // Move the start of the search to the start of the selection,\n // or otherwise to the current cursor position.\n\n let text = unsafe { icu::Text::new(self)? };\n let regex = unsafe { icu::Regex::new(&sanitized_pattern, flags, &text)? };\n\n Ok(ActiveSearch {\n pattern: pattern.to_string(),\n options,\n text,\n regex,\n buffer_generation: self.buffer.generation(),\n selection_generation: 0,\n next_search_offset: 0,\n no_matches: false,\n })\n }\n\n fn find_select_next(&mut self, search: &mut ActiveSearch, offset: usize, wrap: bool) {\n if search.buffer_generation != self.buffer.generation() {\n unsafe { search.regex.set_text(&mut search.text, offset) };\n search.buffer_generation = self.buffer.generation();\n search.next_search_offset = offset;\n } else if search.next_search_offset != offset {\n search.next_search_offset = offset;\n search.regex.reset(offset);\n }\n\n let mut hit = search.regex.next();\n\n // If we hit the end of the buffer, and we know that there's something to find,\n // start the search again from the beginning (= wrap around).\n if wrap && hit.is_none() && search.next_search_offset != 0 {\n search.next_search_offset = 0;\n search.regex.reset(0);\n hit = search.regex.next();\n }\n\n search.selection_generation = if let Some(range) = hit {\n // Now the search offset is no more at the start of the buffer.\n search.next_search_offset = range.end;\n\n let beg = self.cursor_move_to_offset_internal(self.cursor, range.start);\n let end = self.cursor_move_to_offset_internal(beg, range.end);\n\n unsafe { self.set_cursor(end) };\n self.make_cursor_visible();\n\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }))\n } else {\n // Avoid searching through the entire document again if we know there's nothing to find.\n search.no_matches = true;\n self.set_selection(None)\n };\n }\n\n fn find_parse_replacement<'a>(\n arena: &'a Arena,\n search: &mut ActiveSearch,\n replacement: &[u8],\n ) -> Vec, &'a Arena> {\n let mut res = Vec::new_in(arena);\n\n if !search.options.use_regex {\n return res;\n }\n\n let group_count = search.regex.group_count();\n let mut text = Vec::new_in(arena);\n let mut text_beg = 0;\n\n loop {\n let mut off = memchr2(b'$', b'\\\\', replacement, text_beg);\n\n // Push the raw, unescaped text, if any.\n if text_beg < off {\n text.extend_from_slice(&replacement[text_beg..off]);\n }\n\n // Unescape any escaped characters.\n while off < replacement.len() && replacement[off] == b'\\\\' {\n off += 2;\n\n // If this backslash is the last character (e.g. because\n // `replacement` is just 1 byte long, holding just b\"\\\\\"),\n // we can't unescape it. In that case, we map it to `b'\\\\'` here.\n // This results in us appending a literal backslash to the text.\n let ch = replacement.get(off - 1).map_or(b'\\\\', |&c| c);\n\n // Unescape and append the character.\n text.push(match ch {\n b'n' => b'\\n',\n b'r' => b'\\r',\n b't' => b'\\t',\n ch => ch,\n });\n }\n\n // Parse out a group number, if any.\n let mut group = -1;\n if off < replacement.len() && replacement[off] == b'$' {\n let mut beg = off;\n let mut end = off + 1;\n let mut acc = 0i32;\n let mut acc_bad = true;\n\n if end < replacement.len() {\n let ch = replacement[end];\n\n if ch == b'$' {\n // Translate \"$$\" to \"$\".\n beg += 1;\n end += 1;\n } else if ch.is_ascii_digit() {\n // Parse \"$1234\" into 1234i32.\n // If the number is larger than the group count,\n // we flag `acc_bad` which causes us to treat it as text.\n acc_bad = false;\n while {\n acc =\n acc.wrapping_mul(10).wrapping_add((replacement[end] - b'0') as i32);\n acc_bad |= acc > group_count;\n end += 1;\n end < replacement.len() && replacement[end].is_ascii_digit()\n } {}\n }\n }\n\n if !acc_bad {\n group = acc;\n } else {\n text.extend_from_slice(&replacement[beg..end]);\n }\n\n off = end;\n }\n\n if !text.is_empty() {\n res.push(RegexReplacement::Text(text));\n text = Vec::new_in(arena);\n }\n if group >= 0 {\n res.push(RegexReplacement::Group(group));\n }\n\n text_beg = off;\n if text_beg >= replacement.len() {\n break;\n }\n }\n\n res\n }\n\n fn find_fill_replacement<'a>(\n &self,\n search: &mut ActiveSearch,\n replacement: &'a [u8],\n parsed_replacements: &[RegexReplacement],\n ) -> Cow<'a, [u8]> {\n if !search.options.use_regex {\n Cow::Borrowed(replacement)\n } else {\n let mut res = Vec::new();\n\n for replacement in parsed_replacements {\n match replacement {\n RegexReplacement::Text(text) => res.extend_from_slice(text),\n RegexReplacement::Group(group) => {\n if let Some(range) = search.regex.group(*group) {\n self.buffer.extract_raw(range, &mut res, usize::MAX);\n }\n }\n }\n }\n\n Cow::Owned(res)\n }\n }\n\n fn measurement_config(&self) -> MeasurementConfig<'_> {\n MeasurementConfig::new(&self.buffer)\n .with_word_wrap_column(self.word_wrap_column)\n .with_tab_size(self.tab_size)\n }\n\n fn goto_line_start(&self, cursor: Cursor, y: CoordType) -> Cursor {\n let mut result = cursor;\n let mut seek_to_line_start = true;\n\n if y > result.logical_pos.y {\n while y > result.logical_pos.y {\n let chunk = self.read_forward(result.offset);\n if chunk.is_empty() {\n break;\n }\n\n let (delta, line) = simd::lines_fwd(chunk, 0, result.logical_pos.y, y);\n result.offset += delta;\n result.logical_pos.y = line;\n }\n\n // If we're at the end of the buffer, we could either be there because the last\n // character in the buffer is genuinely a newline, or because the buffer ends in a\n // line of text without trailing newline. The only way to make sure is to seek\n // backwards to the line start again. But otherwise we can skip that.\n seek_to_line_start =\n result.offset == self.text_length() && result.offset != cursor.offset;\n }\n\n if seek_to_line_start {\n loop {\n let chunk = self.read_backward(result.offset);\n if chunk.is_empty() {\n break;\n }\n\n let (delta, line) = simd::lines_bwd(chunk, chunk.len(), result.logical_pos.y, y);\n result.offset -= chunk.len() - delta;\n result.logical_pos.y = line;\n if delta > 0 {\n break;\n }\n }\n }\n\n if result.offset == cursor.offset {\n return result;\n }\n\n result.logical_pos.x = 0;\n result.visual_pos.x = 0;\n result.visual_pos.y = result.logical_pos.y;\n result.column = 0;\n result.wrap_opp = false;\n\n if self.word_wrap_column > 0 {\n let upward = result.offset < cursor.offset;\n let (top, bottom) = if upward { (result, cursor) } else { (cursor, result) };\n\n let mut bottom_remeasured =\n self.measurement_config().with_cursor(top).goto_logical(bottom.logical_pos);\n\n // The second problem is that visual positions can be ambiguous. A single logical position\n // can map to two visual positions: One at the end of the preceding line in front of\n // a word wrap, and another at the start of the next line after the same word wrap.\n //\n // This, however, only applies if we go upwards, because only then `bottom ≅ cursor`,\n // and thus only then this `bottom` is ambiguous. Otherwise, `bottom ≅ result`\n // and `result` is at a line start which is never ambiguous.\n if upward {\n let a = bottom_remeasured.visual_pos.x;\n let b = bottom.visual_pos.x;\n bottom_remeasured.visual_pos.y = bottom_remeasured.visual_pos.y\n + (a != 0 && b == 0) as CoordType\n - (a == 0 && b != 0) as CoordType;\n }\n\n let mut delta = bottom_remeasured.visual_pos.y - top.visual_pos.y;\n if upward {\n delta = -delta;\n }\n\n result.visual_pos.y = cursor.visual_pos.y + delta;\n }\n\n result\n }\n\n fn cursor_move_to_offset_internal(&self, mut cursor: Cursor, offset: usize) -> Cursor {\n if offset == cursor.offset {\n return cursor;\n }\n\n // goto_line_start() is fast for seeking across lines _if_ line wrapping is disabled.\n // For backward seeking we have to use it either way, so we're covered there.\n // This implements the forward seeking portion, if it's approx. worth doing so.\n if self.word_wrap_column <= 0 && offset.saturating_sub(cursor.offset) > 1024 {\n // Replacing this with a more optimal, direct memchr() loop appears\n // to improve performance only marginally by another 2% or so.\n // Still, it's kind of \"meh\" looking at how poorly this is implemented...\n loop {\n let next = self.goto_line_start(cursor, cursor.logical_pos.y + 1);\n // Stop when we either ran past the target offset,\n // or when we hit the end of the buffer and `goto_line_start` backtracked to the line start.\n if next.offset > offset || next.offset <= cursor.offset {\n break;\n }\n cursor = next;\n }\n }\n\n while offset < cursor.offset {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y - 1);\n }\n\n self.measurement_config().with_cursor(cursor).goto_offset(offset)\n }\n\n fn cursor_move_to_logical_internal(&self, mut cursor: Cursor, pos: Point) -> Cursor {\n let pos = Point { x: pos.x.max(0), y: pos.y.max(0) };\n\n if pos == cursor.logical_pos {\n return cursor;\n }\n\n // goto_line_start() is the fastest way for seeking across lines. As such we always\n // use it if the requested `.y` position is different. We still need to use it if the\n // `.x` position is smaller, but only because `goto_logical()` cannot seek backwards.\n if pos.y != cursor.logical_pos.y || pos.x < cursor.logical_pos.x {\n cursor = self.goto_line_start(cursor, pos.y);\n }\n\n self.measurement_config().with_cursor(cursor).goto_logical(pos)\n }\n\n fn cursor_move_to_visual_internal(&self, mut cursor: Cursor, pos: Point) -> Cursor {\n let pos = Point { x: pos.x.max(0), y: pos.y.max(0) };\n\n if pos == cursor.visual_pos {\n return cursor;\n }\n\n if self.word_wrap_column <= 0 {\n // Identical to the fast-pass in `cursor_move_to_logical_internal()`.\n if pos.y != cursor.visual_pos.y || pos.x < cursor.visual_pos.x {\n cursor = self.goto_line_start(cursor, pos.y);\n }\n } else {\n // `goto_visual()` can only seek forward, so we need to seek backward here if needed.\n // NOTE that this intentionally doesn't use the `Eq` trait of `Point`, because if\n // `pos.y == cursor.visual_pos.y` we don't need to go to `cursor.logical_pos.y - 1`.\n while pos.y < cursor.visual_pos.y {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y - 1);\n }\n if pos.y == cursor.visual_pos.y && pos.x < cursor.visual_pos.x {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y);\n }\n }\n\n self.measurement_config().with_cursor(cursor).goto_visual(pos)\n }\n\n fn cursor_move_delta_internal(\n &self,\n mut cursor: Cursor,\n granularity: CursorMovement,\n mut delta: CoordType,\n ) -> Cursor {\n if delta == 0 {\n return cursor;\n }\n\n let sign = if delta > 0 { 1 } else { -1 };\n\n match granularity {\n CursorMovement::Grapheme => {\n let start_x = if delta > 0 { 0 } else { CoordType::MAX };\n\n loop {\n let target_x = cursor.logical_pos.x + delta;\n\n cursor = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: target_x, y: cursor.logical_pos.y },\n );\n\n // We can stop if we ran out of remaining delta\n // (or perhaps ran past the goal; in either case the sign would've changed),\n // or if we hit the beginning or end of the buffer.\n delta = target_x - cursor.logical_pos.x;\n if delta.signum() != sign\n || (delta < 0 && cursor.offset == 0)\n || (delta > 0 && cursor.offset >= self.text_length())\n {\n break;\n }\n\n cursor = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: start_x, y: cursor.logical_pos.y + sign },\n );\n\n // We crossed a newline which counts for 1 grapheme cluster.\n // So, we also need to run the same check again.\n delta -= sign;\n if delta.signum() != sign\n || cursor.offset == 0\n || cursor.offset >= self.text_length()\n {\n break;\n }\n }\n }\n CursorMovement::Word => {\n let doc = &self.buffer as &dyn ReadableDocument;\n let mut offset = self.cursor.offset;\n\n while delta != 0 {\n if delta < 0 {\n offset = navigation::word_backward(doc, offset);\n } else {\n offset = navigation::word_forward(doc, offset);\n }\n delta -= sign;\n }\n\n cursor = self.cursor_move_to_offset_internal(cursor, offset);\n }\n }\n\n cursor\n }\n\n /// Moves the cursor to the given offset.\n pub fn cursor_move_to_offset(&mut self, offset: usize) {\n unsafe { self.set_cursor(self.cursor_move_to_offset_internal(self.cursor, offset)) }\n }\n\n /// Moves the cursor to the given logical position.\n pub fn cursor_move_to_logical(&mut self, pos: Point) {\n unsafe { self.set_cursor(self.cursor_move_to_logical_internal(self.cursor, pos)) }\n }\n\n /// Moves the cursor to the given visual position.\n pub fn cursor_move_to_visual(&mut self, pos: Point) {\n unsafe { self.set_cursor(self.cursor_move_to_visual_internal(self.cursor, pos)) }\n }\n\n /// Moves the cursor by the given delta.\n pub fn cursor_move_delta(&mut self, granularity: CursorMovement, delta: CoordType) {\n unsafe { self.set_cursor(self.cursor_move_delta_internal(self.cursor, granularity, delta)) }\n }\n\n /// Sets the cursor to the given position, and clears the selection.\n ///\n /// # Safety\n ///\n /// This function performs no checks that the cursor is valid. \"Valid\" in this case means\n /// that the TextBuffer has not been modified since you received the cursor from this class.\n pub unsafe fn set_cursor(&mut self, cursor: Cursor) {\n self.set_cursor_internal(cursor);\n self.last_history_type = HistoryType::Other;\n self.set_selection(None);\n }\n\n fn set_cursor_for_selection(&mut self, cursor: Cursor) {\n let beg = match self.selection {\n Some(TextBufferSelection { beg, .. }) => beg,\n None => self.cursor.logical_pos,\n };\n\n self.set_cursor_internal(cursor);\n self.last_history_type = HistoryType::Other;\n\n let end = self.cursor.logical_pos;\n self.set_selection(if beg == end { None } else { Some(TextBufferSelection { beg, end }) });\n }\n\n fn set_cursor_internal(&mut self, cursor: Cursor) {\n debug_assert!(\n cursor.offset <= self.text_length()\n && cursor.logical_pos.x >= 0\n && cursor.logical_pos.y >= 0\n && cursor.logical_pos.y <= self.stats.logical_lines\n && cursor.visual_pos.x >= 0\n && (self.word_wrap_column <= 0 || cursor.visual_pos.x <= self.word_wrap_column)\n && cursor.visual_pos.y >= 0\n && cursor.visual_pos.y <= self.stats.visual_lines\n );\n self.cursor = cursor;\n }\n\n /// Extracts a rectangular region of the text buffer and writes it to the framebuffer.\n /// The `destination` rect is framebuffer coordinates. The extracted region within this\n /// text buffer has the given `origin` and the same size as the `destination` rect.\n pub fn render(\n &mut self,\n origin: Point,\n destination: Rect,\n focused: bool,\n fb: &mut Framebuffer,\n ) -> Option {\n if destination.is_empty() {\n return None;\n }\n\n let scratch = scratch_arena(None);\n let width = destination.width();\n let height = destination.height();\n let line_number_width = self.margin_width.max(3) as usize - 3;\n let text_width = width - self.margin_width;\n let mut visualizer_buf = [0xE2, 0x90, 0x80]; // U+2400 in UTF8\n let mut line = ArenaString::new_in(&scratch);\n let mut visual_pos_x_max = 0;\n\n // Pick the cursor closer to the `origin.y`.\n let mut cursor = {\n let a = self.cursor;\n let b = self.cursor_for_rendering.unwrap_or_default();\n let da = (a.visual_pos.y - origin.y).abs();\n let db = (b.visual_pos.y - origin.y).abs();\n if da < db { a } else { b }\n };\n\n let [selection_beg, selection_end] = match self.selection {\n None => [Point::MIN, Point::MIN],\n Some(TextBufferSelection { beg, end }) => minmax(beg, end),\n };\n\n line.reserve(width as usize * 2);\n\n for y in 0..height {\n line.clear();\n\n let visual_line = origin.y + y;\n let mut cursor_beg =\n self.cursor_move_to_visual_internal(cursor, Point { x: origin.x, y: visual_line });\n let cursor_end = self.cursor_move_to_visual_internal(\n cursor_beg,\n Point { x: origin.x + text_width, y: visual_line },\n );\n\n // Accelerate the next render pass by remembering where we started off.\n if y == 0 {\n self.cursor_for_rendering = Some(cursor_beg);\n }\n\n if line_number_width != 0 {\n if visual_line >= self.stats.visual_lines {\n // Past the end of the buffer? Place \" | \" in the margin.\n // Since we know that we won't see line numbers greater than i64::MAX (9223372036854775807)\n // any time soon, we can use a static string as the template (`MARGIN`) and slice it,\n // because `line_number_width` can't possibly be larger than 19.\n let off = 19 - line_number_width;\n unsafe { std::hint::assert_unchecked(off < MARGIN_TEMPLATE.len()) };\n line.push_str(&MARGIN_TEMPLATE[off..]);\n } else if self.word_wrap_column <= 0 || cursor_beg.logical_pos.x == 0 {\n // Regular line? Place \"123 | \" in the margin.\n _ = write!(line, \"{:1$} │ \", cursor_beg.logical_pos.y + 1, line_number_width);\n } else {\n // Wrapped line? Place \" ... | \" in the margin.\n let number_width = (cursor_beg.logical_pos.y + 1).ilog10() as usize + 1;\n _ = write!(\n line,\n \"{0:1$}{0:∙<2$} │ \",\n \"\",\n line_number_width - number_width,\n number_width\n );\n // Blending in the background color will \"dim\" the indicator dots.\n let left = destination.left;\n let top = destination.top + y;\n fb.blend_fg(\n Rect {\n left,\n top,\n right: left + line_number_width as CoordType,\n bottom: top + 1,\n },\n fb.indexed_alpha(IndexedColor::Background, 1, 2),\n );\n }\n }\n\n let mut selection_off = 0..0;\n\n // Figure out the selection range on this line, if any.\n if cursor_beg.visual_pos.y == visual_line\n && selection_beg <= cursor_end.logical_pos\n && selection_end >= cursor_beg.logical_pos\n {\n let mut cursor = cursor_beg;\n\n // By default, we assume the entire line is selected.\n let mut selection_pos_beg = 0;\n let mut selection_pos_end = COORD_TYPE_SAFE_MAX;\n selection_off.start = cursor_beg.offset;\n selection_off.end = cursor_end.offset;\n\n // The start of the selection is within this line. We need to update selection_beg.\n if selection_beg <= cursor_end.logical_pos\n && selection_beg >= cursor_beg.logical_pos\n {\n cursor = self.cursor_move_to_logical_internal(cursor, selection_beg);\n selection_off.start = cursor.offset;\n selection_pos_beg = cursor.visual_pos.x;\n }\n\n // The end of the selection is within this line. We need to update selection_end.\n if selection_end <= cursor_end.logical_pos\n && selection_end >= cursor_beg.logical_pos\n {\n cursor = self.cursor_move_to_logical_internal(cursor, selection_end);\n selection_off.end = cursor.offset;\n selection_pos_end = cursor.visual_pos.x;\n }\n\n let left = destination.left + self.margin_width - origin.x;\n let top = destination.top + y;\n let rect = Rect {\n left: left + selection_pos_beg.max(origin.x),\n top,\n right: left + selection_pos_end.min(origin.x + text_width),\n bottom: top + 1,\n };\n\n let mut bg = oklab_blend(\n fb.indexed(IndexedColor::Foreground),\n fb.indexed_alpha(IndexedColor::BrightBlue, 1, 2),\n );\n if !focused {\n bg = oklab_blend(bg, fb.indexed_alpha(IndexedColor::Background, 1, 2))\n };\n let fg = fb.contrasted(bg);\n fb.blend_bg(rect, bg);\n fb.blend_fg(rect, fg);\n }\n\n // Nothing to do if the entire line is empty.\n if cursor_beg.offset != cursor_end.offset {\n // If we couldn't reach the left edge, we may have stopped short due to a wide glyph.\n // In that case we'll try to find the next character and then compute by how many\n // columns it overlaps the left edge (can be anything between 1 and 7).\n if cursor_beg.visual_pos.x < origin.x {\n let cursor_next = self.cursor_move_to_logical_internal(\n cursor_beg,\n Point { x: cursor_beg.logical_pos.x + 1, y: cursor_beg.logical_pos.y },\n );\n\n if cursor_next.visual_pos.x > origin.x {\n let overlap = cursor_next.visual_pos.x - origin.x;\n debug_assert!((1..=7).contains(&overlap));\n line.push_str(&TAB_WHITESPACE[..overlap as usize]);\n cursor_beg = cursor_next;\n }\n }\n\n let mut global_off = cursor_beg.offset;\n let mut cursor_line = cursor_beg;\n\n while global_off < cursor_end.offset {\n let chunk = self.read_forward(global_off);\n let chunk = &chunk[..chunk.len().min(cursor_end.offset - global_off)];\n let mut it = Utf8Chars::new(chunk, 0);\n\n // TODO: Looping char-by-char is bad for performance.\n // >25% of the total rendering time is spent here.\n loop {\n let chunk_off = it.offset();\n let global_off = global_off + chunk_off;\n let Some(ch) = it.next() else {\n break;\n };\n\n if ch == ' ' || ch == '\\t' {\n let is_tab = ch == '\\t';\n let visualize = selection_off.contains(&global_off);\n let mut whitespace = TAB_WHITESPACE;\n let mut prefix_add = 0;\n\n if is_tab || visualize {\n // We need the character's visual position in order to either compute the tab size,\n // or set the foreground color of the visualizer, respectively.\n // TODO: Doing this char-by-char is of course also bad for performance.\n cursor_line =\n self.cursor_move_to_offset_internal(cursor_line, global_off);\n }\n\n let tab_size =\n if is_tab { self.tab_size_eval(cursor_line.column) } else { 1 };\n\n if visualize {\n // If the whitespace is part of the selection,\n // we replace \" \" with \"・\" and \"\\t\" with \"→\".\n (whitespace, prefix_add) = if is_tab {\n (VISUAL_TAB, VISUAL_TAB_PREFIX_ADD)\n } else {\n (VISUAL_SPACE, VISUAL_SPACE_PREFIX_ADD)\n };\n\n // Make the visualized characters slightly gray.\n let visualizer_rect = {\n let left = destination.left\n + self.margin_width\n + cursor_line.visual_pos.x\n - origin.x;\n let top = destination.top + cursor_line.visual_pos.y - origin.y;\n Rect { left, top, right: left + 1, bottom: top + 1 }\n };\n fb.blend_fg(\n visualizer_rect,\n fb.indexed_alpha(IndexedColor::Foreground, 1, 2),\n );\n }\n\n line.push_str(&whitespace[..prefix_add + tab_size as usize]);\n } else if ch <= '\\x1f' || ('\\u{7f}'..='\\u{9f}').contains(&ch) {\n // Append a Unicode representation of the C0 or C1 control character.\n visualizer_buf[2] = if ch <= '\\x1f' {\n 0x80 | ch as u8 // U+2400..=U+241F\n } else if ch == '\\x7f' {\n 0xA1 // U+2421\n } else {\n 0xA6 // U+2426, because there are no pictures for C1 control characters.\n };\n\n // Our manually constructed UTF8 is never going to be invalid. Trust.\n line.push_str(unsafe { str::from_utf8_unchecked(&visualizer_buf) });\n\n // Highlight the control character yellow.\n cursor_line =\n self.cursor_move_to_offset_internal(cursor_line, global_off);\n let visualizer_rect = {\n let left =\n destination.left + self.margin_width + cursor_line.visual_pos.x\n - origin.x;\n let top = destination.top + cursor_line.visual_pos.y - origin.y;\n Rect { left, top, right: left + 1, bottom: top + 1 }\n };\n let bg = fb.indexed(IndexedColor::Yellow);\n let fg = fb.contrasted(bg);\n fb.blend_bg(visualizer_rect, bg);\n fb.blend_fg(visualizer_rect, fg);\n } else {\n line.push(ch);\n }\n }\n\n global_off += chunk.len();\n }\n\n visual_pos_x_max = visual_pos_x_max.max(cursor_end.visual_pos.x);\n }\n\n fb.replace_text(destination.top + y, destination.left, destination.right, &line);\n\n cursor = cursor_end;\n }\n\n // Colorize the margin that we wrote above.\n if self.margin_width > 0 {\n let margin = Rect {\n left: destination.left,\n top: destination.top,\n right: destination.left + self.margin_width,\n bottom: destination.bottom,\n };\n fb.blend_fg(margin, 0x7f3f3f3f);\n }\n\n if self.ruler > 0 {\n let left = destination.left + self.margin_width + (self.ruler - origin.x).max(0);\n let right = destination.right;\n if left < right {\n fb.blend_bg(\n Rect { left, top: destination.top, right, bottom: destination.bottom },\n fb.indexed_alpha(IndexedColor::BrightRed, 1, 4),\n );\n }\n }\n\n if focused {\n let mut x = self.cursor.visual_pos.x;\n let mut y = self.cursor.visual_pos.y;\n\n if self.word_wrap_column > 0 && x >= self.word_wrap_column {\n // The line the cursor is on wraps exactly on the word wrap column which\n // means the cursor is invisible. We need to move it to the next line.\n x = 0;\n y += 1;\n }\n\n // Move the cursor into screen space.\n x += destination.left - origin.x + self.margin_width;\n y += destination.top - origin.y;\n\n let cursor = Point { x, y };\n let text = Rect {\n left: destination.left + self.margin_width,\n top: destination.top,\n right: destination.right,\n bottom: destination.bottom,\n };\n\n if text.contains(cursor) {\n fb.set_cursor(cursor, self.overtype);\n\n if self.line_highlight_enabled && selection_beg >= selection_end {\n fb.blend_bg(\n Rect {\n left: destination.left,\n top: cursor.y,\n right: destination.right,\n bottom: cursor.y + 1,\n },\n 0x50282828,\n );\n }\n }\n }\n\n Some(RenderResult { visual_pos_x_max })\n }\n\n pub fn cut(&mut self, clipboard: &mut Clipboard) {\n self.cut_copy(clipboard, true);\n }\n\n pub fn copy(&mut self, clipboard: &mut Clipboard) {\n self.cut_copy(clipboard, false);\n }\n\n fn cut_copy(&mut self, clipboard: &mut Clipboard, cut: bool) {\n let line_copy = !self.has_selection();\n let selection = self.extract_selection(cut);\n clipboard.write(selection);\n clipboard.write_was_line_copy(line_copy);\n }\n\n pub fn paste(&mut self, clipboard: &Clipboard) {\n let data = clipboard.read();\n if data.is_empty() {\n return;\n }\n\n let pos = self.cursor_logical_pos();\n let at = if clipboard.is_line_copy() {\n self.goto_line_start(self.cursor, pos.y)\n } else {\n self.cursor\n };\n\n self.write(data, at, true);\n\n if clipboard.is_line_copy() {\n self.cursor_move_to_logical(Point { x: pos.x, y: pos.y + 1 });\n }\n }\n\n /// Inserts the user input `text` at the current cursor position.\n /// Replaces tabs with whitespace if needed, etc.\n pub fn write_canon(&mut self, text: &[u8]) {\n self.write(text, self.cursor, false);\n }\n\n /// Inserts `text` as-is at the current cursor position.\n /// The only transformation applied is that newlines are normalized.\n pub fn write_raw(&mut self, text: &[u8]) {\n self.write(text, self.cursor, true);\n }\n\n fn write(&mut self, text: &[u8], at: Cursor, raw: bool) {\n let history_type = if raw { HistoryType::Other } else { HistoryType::Write };\n let mut edit_begun = false;\n\n // If we have an active selection, writing an empty `text`\n // will still delete the selection. As such, we check this first.\n if let Some((beg, end)) = self.selection_range_internal(false) {\n self.edit_begin(history_type, beg);\n self.edit_delete(end);\n self.set_selection(None);\n edit_begun = true;\n }\n\n // If the text is empty the remaining code won't do anything,\n // allowing us to exit early.\n if text.is_empty() {\n // ...we still need to end any active edit session though.\n if edit_begun {\n self.edit_end();\n }\n return;\n }\n\n if !edit_begun {\n self.edit_begin(history_type, at);\n }\n\n let mut offset = 0;\n let scratch = scratch_arena(None);\n let mut newline_buffer = ArenaString::new_in(&scratch);\n\n loop {\n // Can't use `unicode::newlines_forward` because bracketed paste uses CR instead of LF/CRLF.\n let offset_next = memchr2(b'\\r', b'\\n', text, offset);\n let line = &text[offset..offset_next];\n let column_before = self.cursor.logical_pos.x;\n\n // Write the contents of the line into the buffer.\n let mut line_off = 0;\n while line_off < line.len() {\n // Split the line into chunks of non-tabs and tabs.\n let mut plain = line;\n if !raw && !self.indent_with_tabs {\n let end = memchr2(b'\\t', b'\\t', line, line_off);\n plain = &line[line_off..end];\n }\n\n // Non-tabs are written as-is, because the outer loop already handles newline translation.\n self.edit_write(plain);\n line_off += plain.len();\n\n // Now replace tabs with spaces.\n while line_off < line.len() && line[line_off] == b'\\t' {\n let spaces = self.tab_size_eval(self.cursor.column);\n let spaces = &TAB_WHITESPACE.as_bytes()[..spaces as usize];\n self.edit_write(spaces);\n line_off += 1;\n }\n }\n\n if !raw && self.overtype {\n let delete = self.cursor.logical_pos.x - column_before;\n let end = self.cursor_move_to_logical_internal(\n self.cursor,\n Point { x: self.cursor.logical_pos.x + delete, y: self.cursor.logical_pos.y },\n );\n self.edit_delete(end);\n }\n\n offset += line.len();\n if offset >= text.len() {\n break;\n }\n\n // First, write the newline.\n newline_buffer.clear();\n newline_buffer.push_str(if self.newlines_are_crlf { \"\\r\\n\" } else { \"\\n\" });\n\n if !raw {\n // We'll give the next line the same indentation as the previous one.\n // This block figures out how much that is. We can't reuse that value,\n // because \" a\\n a\\n\" should give the 3rd line a total indentation of 4.\n // Assuming your terminal has bracketed paste, this won't be a concern though.\n // (If it doesn't, use a different terminal.)\n let line_beg = self.goto_line_start(self.cursor, self.cursor.logical_pos.y);\n let limit = self.cursor.offset;\n let mut off = line_beg.offset;\n let mut newline_indentation = 0;\n\n 'outer: while off < limit {\n let chunk = self.read_forward(off);\n let chunk = &chunk[..chunk.len().min(limit - off)];\n\n for &c in chunk {\n if c == b' ' {\n newline_indentation += 1;\n } else if c == b'\\t' {\n newline_indentation += self.tab_size_eval(newline_indentation);\n } else {\n break 'outer;\n }\n }\n\n off += chunk.len();\n }\n\n // If tabs are enabled, add as many tabs as we can.\n if self.indent_with_tabs {\n let tab_count = newline_indentation / self.tab_size;\n newline_buffer.push_repeat('\\t', tab_count as usize);\n newline_indentation -= tab_count * self.tab_size;\n }\n\n // If tabs are disabled, or if the indentation wasn't a multiple of the tab size,\n // add spaces to make up the difference.\n newline_buffer.push_repeat(' ', newline_indentation as usize);\n }\n\n self.edit_write(newline_buffer.as_bytes());\n\n // Skip one CR/LF/CRLF.\n if offset >= text.len() {\n break;\n }\n if text[offset] == b'\\r' {\n offset += 1;\n }\n if offset >= text.len() {\n break;\n }\n if text[offset] == b'\\n' {\n offset += 1;\n }\n if offset >= text.len() {\n break;\n }\n }\n\n // POSIX mandates that all valid lines end in a newline.\n // This isn't all that common on Windows and so we have\n // `self.final_newline` to control this.\n //\n // In order to not annoy people with this, we only add a\n // newline if you just edited the very end of the buffer.\n if self.insert_final_newline\n && self.cursor.offset > 0\n && self.cursor.offset == self.text_length()\n && self.cursor.logical_pos.x > 0\n {\n let cursor = self.cursor;\n self.edit_write(if self.newlines_are_crlf { b\"\\r\\n\" } else { b\"\\n\" });\n self.set_cursor_internal(cursor);\n }\n\n self.edit_end();\n }\n\n /// Deletes 1 grapheme cluster from the buffer.\n /// `cursor_movements` is expected to be -1 for backspace and 1 for delete.\n /// If there's a current selection, it will be deleted and `cursor_movements` ignored.\n /// The selection is cleared after the call.\n /// Deletes characters from the buffer based on a delta from the cursor.\n pub fn delete(&mut self, granularity: CursorMovement, delta: CoordType) {\n if delta == 0 {\n return;\n }\n\n let mut beg;\n let mut end;\n\n if let Some(r) = self.selection_range_internal(false) {\n (beg, end) = r;\n } else {\n if (delta < 0 && self.cursor.offset == 0)\n || (delta > 0 && self.cursor.offset >= self.text_length())\n {\n // Nothing to delete.\n return;\n }\n\n beg = self.cursor;\n end = self.cursor_move_delta_internal(beg, granularity, delta);\n if beg.offset == end.offset {\n return;\n }\n if beg.offset > end.offset {\n mem::swap(&mut beg, &mut end);\n }\n }\n\n self.edit_begin(HistoryType::Delete, beg);\n self.edit_delete(end);\n self.edit_end();\n\n self.set_selection(None);\n }\n\n /// Returns the logical position of the first character on this line.\n /// Return `.x == 0` if there are no non-whitespace characters.\n pub fn indent_end_logical_pos(&self) -> Point {\n let cursor = self.goto_line_start(self.cursor, self.cursor.logical_pos.y);\n let (chars, _) = self.measure_indent_internal(cursor.offset, CoordType::MAX);\n Point { x: chars, y: cursor.logical_pos.y }\n }\n\n /// Indents/unindents the current selection or line.\n pub fn indent_change(&mut self, direction: CoordType) {\n let selection = self.selection;\n let mut selection_beg = self.cursor.logical_pos;\n let mut selection_end = selection_beg;\n\n if let Some(TextBufferSelection { beg, end }) = &selection {\n selection_beg = *beg;\n selection_end = *end;\n }\n\n if direction >= 0 && self.selection.is_none_or(|sel| sel.beg.y == sel.end.y) {\n self.write_canon(b\"\\t\");\n return;\n }\n\n self.edit_begin_grouping();\n\n for y in selection_beg.y.min(selection_end.y)..=selection_beg.y.max(selection_end.y) {\n self.cursor_move_to_logical(Point { x: 0, y });\n\n let line_start_offset = self.cursor.offset;\n let (curr_chars, curr_columns) =\n self.measure_indent_internal(line_start_offset, CoordType::MAX);\n\n self.cursor_move_to_logical(Point { x: curr_chars, y: self.cursor.logical_pos.y });\n\n let delta;\n\n if direction < 0 {\n // Unindent the line. If there's no indentation, skip.\n if curr_columns <= 0 {\n continue;\n }\n\n let (prev_chars, _) = self.measure_indent_internal(\n line_start_offset,\n self.tab_size_prev_column(curr_columns),\n );\n\n delta = prev_chars - curr_chars;\n self.delete(CursorMovement::Grapheme, delta);\n } else {\n // Indent the line. `self.cursor` is already at the level of indentation.\n delta = self.tab_size_eval(curr_columns);\n self.write_canon(b\"\\t\");\n }\n\n // As the lines get unindented, the selection should shift with them.\n if y == selection_beg.y {\n selection_beg.x += delta;\n }\n if y == selection_end.y {\n selection_end.x += delta;\n }\n }\n self.edit_end_grouping();\n\n // Move the cursor to the new end of the selection.\n self.set_cursor_internal(self.cursor_move_to_logical_internal(self.cursor, selection_end));\n\n // NOTE: If the selection was previously `None`,\n // it should continue to be `None` after this.\n self.set_selection(\n selection.map(|_| TextBufferSelection { beg: selection_beg, end: selection_end }),\n );\n }\n\n fn measure_indent_internal(\n &self,\n mut offset: usize,\n max_columns: CoordType,\n ) -> (CoordType, CoordType) {\n let mut chars = 0;\n let mut columns = 0;\n\n 'outer: loop {\n let chunk = self.read_forward(offset);\n if chunk.is_empty() {\n break;\n }\n\n for &c in chunk {\n let next = match c {\n b' ' => columns + 1,\n b'\\t' => columns + self.tab_size_eval(columns),\n _ => break 'outer,\n };\n if next > max_columns {\n break 'outer;\n }\n chars += 1;\n columns = next;\n }\n\n offset += chunk.len();\n\n // No need to do another round if we\n // already got the exact right amount.\n if columns >= max_columns {\n break;\n }\n }\n\n (chars, columns)\n }\n\n /// Displaces the current, cursor or the selection, line(s) in the given direction.\n pub fn move_selected_lines(&mut self, direction: MoveLineDirection) {\n let selection = self.selection;\n let cursor = self.cursor;\n\n // If there's no selection, we move the line the cursor is on instead.\n let [beg, end] = match self.selection {\n Some(s) => minmax(s.beg.y, s.end.y),\n None => [cursor.logical_pos.y, cursor.logical_pos.y],\n };\n\n // Check if this would be a no-op.\n if match direction {\n MoveLineDirection::Up => beg <= 0,\n MoveLineDirection::Down => end >= self.stats.logical_lines - 1,\n } {\n return;\n }\n\n let delta = match direction {\n MoveLineDirection::Up => -1,\n MoveLineDirection::Down => 1,\n };\n let (cut, paste) = match direction {\n MoveLineDirection::Up => (beg - 1, end),\n MoveLineDirection::Down => (end + 1, beg),\n };\n\n self.edit_begin_grouping();\n {\n // Let's say this is `MoveLineDirection::Up`.\n // In that case, we'll cut (remove) the line above the selection here...\n self.cursor_move_to_logical(Point { x: 0, y: cut });\n let line = self.extract_selection(true);\n\n // ...and paste it below the selection. This will then\n // appear to the user as if the selection was moved up.\n self.cursor_move_to_logical(Point { x: 0, y: paste });\n self.edit_begin(HistoryType::Write, self.cursor);\n // The `extract_selection` call can return an empty `Vec`),\n // if the `cut` line was at the end of the file. Since we want to\n // paste the line somewhere it needs a trailing newline at the minimum.\n //\n // Similarly, if the `paste` line is at the end of the file\n // and there's no trailing newline, we'll have failed to reach\n // that end in which case `logical_pos.y != past`.\n if line.is_empty() || self.cursor.logical_pos.y != paste {\n self.write_canon(b\"\\n\");\n }\n if !line.is_empty() {\n self.write_raw(&line);\n }\n self.edit_end();\n }\n self.edit_end_grouping();\n\n // Shift the cursor and selection together with the moved lines.\n self.cursor_move_to_logical(Point {\n x: cursor.logical_pos.x,\n y: cursor.logical_pos.y + delta,\n });\n self.set_selection(selection.map(|mut s| {\n s.beg.y += delta;\n s.end.y += delta;\n s\n }));\n }\n\n /// Extracts the contents of the current selection.\n /// May optionally delete it, if requested. This is meant to be used for Ctrl+X.\n fn extract_selection(&mut self, delete: bool) -> Vec {\n let line_copy = !self.has_selection();\n let Some((beg, end)) = self.selection_range_internal(true) else {\n return Vec::new();\n };\n\n let mut out = Vec::new();\n self.buffer.extract_raw(beg.offset..end.offset, &mut out, 0);\n\n if delete && !out.is_empty() {\n self.edit_begin(HistoryType::Delete, beg);\n self.edit_delete(end);\n self.edit_end();\n self.set_selection(None);\n }\n\n // Line copies (= Ctrl+C when there's no selection) always end with a newline.\n if line_copy && !out.ends_with(b\"\\n\") {\n out.replace_range(out.len().., if self.newlines_are_crlf { b\"\\r\\n\" } else { b\"\\n\" });\n }\n\n out\n }\n\n /// Extracts the contents of the current selection the user made.\n /// This differs from [`TextBuffer::extract_selection()`] in that\n /// it does nothing if the selection was made by searching.\n pub fn extract_user_selection(&mut self, delete: bool) -> Option> {\n if !self.has_selection() {\n return None;\n }\n\n if let Some(search) = &self.search {\n let search = unsafe { &*search.get() };\n if search.selection_generation == self.selection_generation {\n return None;\n }\n }\n\n Some(self.extract_selection(delete))\n }\n\n /// Returns the current selection anchors, or `None` if there\n /// is no selection. The returned logical positions are sorted.\n pub fn selection_range(&self) -> Option<(Cursor, Cursor)> {\n self.selection_range_internal(false)\n }\n\n /// Returns the current selection anchors.\n ///\n /// If there's no selection and `line_fallback` is `true`,\n /// the start/end of the current line are returned.\n /// This is meant to be used for Ctrl+C / Ctrl+X.\n fn selection_range_internal(&self, line_fallback: bool) -> Option<(Cursor, Cursor)> {\n let [beg, end] = match self.selection {\n None if !line_fallback => return None,\n None => [\n Point { x: 0, y: self.cursor.logical_pos.y },\n Point { x: 0, y: self.cursor.logical_pos.y + 1 },\n ],\n Some(TextBufferSelection { beg, end }) => minmax(beg, end),\n };\n\n let beg = self.cursor_move_to_logical_internal(self.cursor, beg);\n let end = self.cursor_move_to_logical_internal(beg, end);\n\n if beg.offset < end.offset { Some((beg, end)) } else { None }\n }\n\n fn edit_begin_grouping(&mut self) {\n self.active_edit_group = Some(ActiveEditGroupInfo {\n cursor_before: self.cursor.logical_pos,\n selection_before: self.selection,\n stats_before: self.stats,\n generation_before: self.buffer.generation(),\n });\n }\n\n fn edit_end_grouping(&mut self) {\n self.active_edit_group = None;\n }\n\n /// Starts a new edit operation.\n /// This is used for tracking the undo/redo history.\n fn edit_begin(&mut self, history_type: HistoryType, cursor: Cursor) {\n self.active_edit_depth += 1;\n if self.active_edit_depth > 1 {\n return;\n }\n\n let cursor_before = self.cursor;\n self.set_cursor_internal(cursor);\n\n // If both the last and this are a Write/Delete operation, we skip allocating a new undo history item.\n if cursor_before.offset != cursor.offset\n || history_type != self.last_history_type\n || !matches!(history_type, HistoryType::Write | HistoryType::Delete)\n {\n self.redo_stack.clear();\n while self.undo_stack.len() > 1000 {\n self.undo_stack.pop_front();\n }\n\n self.last_history_type = history_type;\n self.undo_stack.push_back(SemiRefCell::new(HistoryEntry {\n cursor_before: cursor_before.logical_pos,\n selection_before: self.selection,\n stats_before: self.stats,\n generation_before: self.buffer.generation(),\n cursor: cursor.logical_pos,\n deleted: Vec::new(),\n added: Vec::new(),\n }));\n\n if let Some(info) = &self.active_edit_group\n && let Some(entry) = self.undo_stack.back()\n {\n let mut entry = entry.borrow_mut();\n entry.cursor_before = info.cursor_before;\n entry.selection_before = info.selection_before;\n entry.stats_before = info.stats_before;\n entry.generation_before = info.generation_before;\n }\n }\n\n self.active_edit_off = cursor.offset;\n\n // If word-wrap is enabled, the visual layout of all logical lines affected by the write\n // may have changed. This includes even text before the insertion point up to the line\n // start, because this write may have joined with a word before the initial cursor.\n // See other uses of `word_wrap_cursor_next_line` in this function.\n if self.word_wrap_column > 0 {\n let safe_start = self.goto_line_start(cursor, cursor.logical_pos.y);\n let next_line = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: 0, y: cursor.logical_pos.y + 1 },\n );\n self.active_edit_line_info = Some(ActiveEditLineInfo {\n safe_start,\n line_height_in_rows: next_line.visual_pos.y - safe_start.visual_pos.y,\n distance_next_line_start: next_line.offset - cursor.offset,\n });\n }\n }\n\n /// Writes `text` into the buffer at the current cursor position.\n /// It records the change in the undo stack.\n fn edit_write(&mut self, text: &[u8]) {\n let logical_y_before = self.cursor.logical_pos.y;\n\n // Copy the written portion into the undo entry.\n {\n let mut undo = self.undo_stack.back_mut().unwrap().borrow_mut();\n undo.added.extend_from_slice(text);\n }\n\n // Write!\n self.buffer.replace(self.active_edit_off..self.active_edit_off, text);\n\n // Move self.cursor to the end of the newly written text. Can't use `self.set_cursor_internal`,\n // because we're still in the progress of recalculating the line stats.\n self.active_edit_off += text.len();\n self.cursor = self.cursor_move_to_offset_internal(self.cursor, self.active_edit_off);\n self.stats.logical_lines += self.cursor.logical_pos.y - logical_y_before;\n }\n\n /// Deletes the text between the current cursor position and `to`.\n /// It records the change in the undo stack.\n fn edit_delete(&mut self, to: Cursor) {\n debug_assert!(to.offset >= self.active_edit_off);\n\n let logical_y_before = self.cursor.logical_pos.y;\n let off = self.active_edit_off;\n let mut out_off = usize::MAX;\n\n let mut undo = self.undo_stack.back_mut().unwrap().borrow_mut();\n\n // If this is a continued backspace operation,\n // we need to prepend the deleted portion to the undo entry.\n if self.cursor.logical_pos < undo.cursor {\n out_off = 0;\n undo.cursor = self.cursor.logical_pos;\n }\n\n // Copy the deleted portion into the undo entry.\n let deleted = &mut undo.deleted;\n self.buffer.extract_raw(off..to.offset, deleted, out_off);\n\n // Delete the portion from the buffer by enlarging the gap.\n let count = to.offset - off;\n self.buffer.allocate_gap(off, 0, count);\n\n self.stats.logical_lines += logical_y_before - to.logical_pos.y;\n }\n\n /// Finalizes the current edit operation\n /// and recalculates the line statistics.\n fn edit_end(&mut self) {\n self.active_edit_depth -= 1;\n debug_assert!(self.active_edit_depth >= 0);\n if self.active_edit_depth > 0 {\n return;\n }\n\n #[cfg(debug_assertions)]\n {\n let entry = self.undo_stack.back_mut().unwrap().borrow_mut();\n debug_assert!(!entry.deleted.is_empty() || !entry.added.is_empty());\n }\n\n if let Some(info) = self.active_edit_line_info.take() {\n let deleted_count = self.undo_stack.back_mut().unwrap().borrow_mut().deleted.len();\n let target = self.cursor.logical_pos;\n\n // From our safe position we can measure the actual visual position of the cursor.\n self.set_cursor_internal(self.cursor_move_to_logical_internal(info.safe_start, target));\n\n // If content is added at the insertion position, that's not a problem:\n // We can just remeasure the height of this one line and calculate the delta.\n // `deleted_count` is 0 in this case.\n //\n // The problem is when content is deleted, because it may affect lines\n // beyond the end of the `next_line`. In that case we have to measure\n // the entire buffer contents until the end to compute `self.stats.visual_lines`.\n if deleted_count < info.distance_next_line_start {\n // Now we can measure how many more visual rows this logical line spans.\n let next_line = self\n .cursor_move_to_logical_internal(self.cursor, Point { x: 0, y: target.y + 1 });\n let lines_before = info.line_height_in_rows;\n let lines_after = next_line.visual_pos.y - info.safe_start.visual_pos.y;\n self.stats.visual_lines += lines_after - lines_before;\n } else {\n let end = self.cursor_move_to_logical_internal(self.cursor, Point::MAX);\n self.stats.visual_lines = end.visual_pos.y + 1;\n }\n } else {\n // If word-wrap is disabled the visual line count always matches the logical one.\n self.stats.visual_lines = self.stats.logical_lines;\n }\n\n self.recalc_after_content_changed();\n }\n\n /// Undo the last edit operation.\n pub fn undo(&mut self) {\n self.undo_redo(true);\n }\n\n /// Redo the last undo operation.\n pub fn redo(&mut self) {\n self.undo_redo(false);\n }\n\n fn undo_redo(&mut self, undo: bool) {\n let buffer_generation = self.buffer.generation();\n let mut entry_buffer_generation = None;\n\n loop {\n // Transfer the last entry from the undo stack to the redo stack or vice versa.\n {\n let (from, to) = if undo {\n (&mut self.undo_stack, &mut self.redo_stack)\n } else {\n (&mut self.redo_stack, &mut self.undo_stack)\n };\n\n if let Some(g) = entry_buffer_generation\n && from.back().is_none_or(|c| c.borrow().generation_before != g)\n {\n break;\n }\n\n let Some(list) = from.cursor_back_mut().remove_current_as_list() else {\n break;\n };\n\n to.cursor_back_mut().splice_after(list);\n }\n\n let change = {\n let to = if undo { &self.redo_stack } else { &self.undo_stack };\n to.back().unwrap()\n };\n\n // Remember the buffer generation of the change so we can stop popping undos/redos.\n // Also, move to the point where the modification took place.\n let cursor = {\n let change = change.borrow();\n entry_buffer_generation = Some(change.generation_before);\n self.cursor_move_to_logical_internal(self.cursor, change.cursor)\n };\n\n let safe_cursor = if self.word_wrap_column > 0 {\n // If word-wrap is enabled, we need to move the cursor to the beginning of the line.\n // This is because the undo/redo operation may have changed the visual position of the cursor.\n self.goto_line_start(cursor, cursor.logical_pos.y)\n } else {\n cursor\n };\n\n {\n let mut change = change.borrow_mut();\n let change = &mut *change;\n\n // Undo: Whatever was deleted is now added and vice versa.\n mem::swap(&mut change.deleted, &mut change.added);\n\n // Delete the inserted portion.\n self.buffer.allocate_gap(cursor.offset, 0, change.deleted.len());\n\n // Reinsert the deleted portion.\n {\n let added = &change.added[..];\n let mut beg = 0;\n let mut offset = cursor.offset;\n\n while beg < added.len() {\n let (end, line) = simd::lines_fwd(added, beg, 0, 1);\n let has_newline = line != 0;\n let link = &added[beg..end];\n let line = unicode::strip_newline(link);\n let mut written;\n\n {\n let gap = self.buffer.allocate_gap(offset, line.len() + 2, 0);\n written = slice_copy_safe(gap, line);\n\n if has_newline {\n if self.newlines_are_crlf && written < gap.len() {\n gap[written] = b'\\r';\n written += 1;\n }\n if written < gap.len() {\n gap[written] = b'\\n';\n written += 1;\n }\n }\n\n self.buffer.commit_gap(written);\n }\n\n beg = end;\n offset += written;\n }\n }\n\n // Restore the previous line statistics.\n mem::swap(&mut self.stats, &mut change.stats_before);\n\n // Restore the previous selection.\n mem::swap(&mut self.selection, &mut change.selection_before);\n\n // Pretend as if the buffer was never modified.\n self.buffer.set_generation(change.generation_before);\n change.generation_before = buffer_generation;\n\n // Restore the previous cursor.\n let cursor_before =\n self.cursor_move_to_logical_internal(safe_cursor, change.cursor_before);\n change.cursor_before = self.cursor.logical_pos;\n // Can't use `set_cursor_internal` here, because we haven't updated the line stats yet.\n self.cursor = cursor_before;\n\n if self.undo_stack.is_empty() {\n self.last_history_type = HistoryType::Other;\n }\n }\n }\n\n if entry_buffer_generation.is_some() {\n self.recalc_after_content_changed();\n }\n }\n\n /// For interfacing with ICU.\n pub(crate) fn read_backward(&self, off: usize) -> &[u8] {\n self.buffer.read_backward(off)\n }\n\n /// For interfacing with ICU.\n pub fn read_forward(&self, off: usize) -> &[u8] {\n self.buffer.read_forward(off)\n }\n}\n\npub enum Bom {\n None,\n UTF8,\n UTF16LE,\n UTF16BE,\n UTF32LE,\n UTF32BE,\n GB18030,\n}\n\nconst BOM_MAX_LEN: usize = 4;\n\nfn detect_bom(bytes: &[u8]) -> Option<&'static str> {\n if bytes.len() >= 4 {\n if bytes.starts_with(b\"\\xFF\\xFE\\x00\\x00\") {\n return Some(\"UTF-32LE\");\n }\n if bytes.starts_with(b\"\\x00\\x00\\xFE\\xFF\") {\n return Some(\"UTF-32BE\");\n }\n if bytes.starts_with(b\"\\x84\\x31\\x95\\x33\") {\n return Some(\"GB18030\");\n }\n }\n if bytes.len() >= 3 && bytes.starts_with(b\"\\xEF\\xBB\\xBF\") {\n return Some(\"UTF-8\");\n }\n if bytes.len() >= 2 {\n if bytes.starts_with(b\"\\xFF\\xFE\") {\n return Some(\"UTF-16LE\");\n }\n if bytes.starts_with(b\"\\xFE\\xFF\") {\n return Some(\"UTF-16BE\");\n }\n }\n None\n}\n"], ["/edit/src/framebuffer.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! A shoddy framebuffer for terminal applications.\n\nuse std::cell::Cell;\nuse std::fmt::Write;\nuse std::ops::{BitOr, BitXor};\nuse std::ptr;\nuse std::slice::ChunksExact;\n\nuse crate::arena::{Arena, ArenaString};\nuse crate::helpers::{CoordType, Point, Rect, Size};\nuse crate::oklab::{oklab_blend, srgb_to_oklab};\nuse crate::simd::{MemsetSafe, memset};\nuse crate::unicode::MeasurementConfig;\n\n// Same constants as used in the PCG family of RNGs.\n#[cfg(target_pointer_width = \"32\")]\nconst HASH_MULTIPLIER: usize = 747796405; // https://doi.org/10.1090/S0025-5718-99-00996-5, Table 5\n#[cfg(target_pointer_width = \"64\")]\nconst HASH_MULTIPLIER: usize = 6364136223846793005; // Knuth's MMIX multiplier\n\n/// The size of our cache table. 1<<8 = 256.\nconst CACHE_TABLE_LOG2_SIZE: usize = 8;\nconst CACHE_TABLE_SIZE: usize = 1 << CACHE_TABLE_LOG2_SIZE;\n/// To index into the cache table, we use `color * HASH_MULTIPLIER` as the hash.\n/// Since the multiplication \"shifts\" the bits up, we don't just mask the lowest\n/// 8 bits out, but rather shift 56 bits down to get the best bits from the top.\nconst CACHE_TABLE_SHIFT: usize = usize::BITS as usize - CACHE_TABLE_LOG2_SIZE;\n\n/// Standard 16 VT & default foreground/background colors.\n#[derive(Clone, Copy)]\npub enum IndexedColor {\n Black,\n Red,\n Green,\n Yellow,\n Blue,\n Magenta,\n Cyan,\n White,\n BrightBlack,\n BrightRed,\n BrightGreen,\n BrightYellow,\n BrightBlue,\n BrightMagenta,\n BrightCyan,\n BrightWhite,\n\n Background,\n Foreground,\n}\n\n/// Number of indices used by [`IndexedColor`].\npub const INDEXED_COLORS_COUNT: usize = 18;\n\n/// Fallback theme. Matches Windows Terminal's Ottosson theme.\npub const DEFAULT_THEME: [u32; INDEXED_COLORS_COUNT] = [\n 0xff000000, // Black\n 0xff212cbe, // Red\n 0xff3aae3f, // Green\n 0xff4a9abe, // Yellow\n 0xffbe4d20, // Blue\n 0xffbe54bb, // Magenta\n 0xffb2a700, // Cyan\n 0xffbebebe, // White\n 0xff808080, // BrightBlack\n 0xff303eff, // BrightRed\n 0xff51ea58, // BrightGreen\n 0xff44c9ff, // BrightYellow\n 0xffff6a2f, // BrightBlue\n 0xffff74fc, // BrightMagenta\n 0xfff0e100, // BrightCyan\n 0xffffffff, // BrightWhite\n // --------\n 0xff000000, // Background\n 0xffbebebe, // Foreground\n];\n\n/// A shoddy framebuffer for terminal applications.\n///\n/// The idea is that you create a [`Framebuffer`], draw a bunch of text and\n/// colors into it, and it takes care of figuring out what changed since the\n/// last rendering and sending the differences as VT to the terminal.\n///\n/// This is an improvement over how many other terminal applications work,\n/// as they fail to accurately track what changed. If you watch the output\n/// of `vim` for instance, you'll notice that it redraws unrelated parts of\n/// the screen all the time.\npub struct Framebuffer {\n /// Store the color palette.\n indexed_colors: [u32; INDEXED_COLORS_COUNT],\n /// Front and back buffers. Indexed by `frame_counter & 1`.\n buffers: [Buffer; 2],\n /// The current frame counter. Increments on every `flip` call.\n frame_counter: usize,\n /// The colors used for `contrast()`. It stores the default colors\n /// of the palette as [dark, light], unless the palette is recognized\n /// as a light them, in which case it swaps them.\n auto_colors: [u32; 2],\n /// A cache table for previously contrasted colors.\n /// See: \n contrast_colors: [Cell<(u32, u32)>; CACHE_TABLE_SIZE],\n background_fill: u32,\n foreground_fill: u32,\n}\n\nimpl Framebuffer {\n /// Creates a new framebuffer.\n pub fn new() -> Self {\n Self {\n indexed_colors: DEFAULT_THEME,\n buffers: Default::default(),\n frame_counter: 0,\n auto_colors: [\n DEFAULT_THEME[IndexedColor::Black as usize],\n DEFAULT_THEME[IndexedColor::BrightWhite as usize],\n ],\n contrast_colors: [const { Cell::new((0, 0)) }; CACHE_TABLE_SIZE],\n background_fill: DEFAULT_THEME[IndexedColor::Background as usize],\n foreground_fill: DEFAULT_THEME[IndexedColor::Foreground as usize],\n }\n }\n\n /// Sets the base color palette.\n ///\n /// If you call this method, [`Framebuffer`] expects that you\n /// successfully detect the light/dark mode of the terminal.\n pub fn set_indexed_colors(&mut self, colors: [u32; INDEXED_COLORS_COUNT]) {\n self.indexed_colors = colors;\n self.background_fill = 0;\n self.foreground_fill = 0;\n\n self.auto_colors = [\n self.indexed_colors[IndexedColor::Black as usize],\n self.indexed_colors[IndexedColor::BrightWhite as usize],\n ];\n if !Self::is_dark(self.auto_colors[0]) {\n self.auto_colors.swap(0, 1);\n }\n }\n\n /// Begins a new frame with the given `size`.\n pub fn flip(&mut self, size: Size) {\n if size != self.buffers[0].bg_bitmap.size {\n for buffer in &mut self.buffers {\n buffer.text = LineBuffer::new(size);\n buffer.bg_bitmap = Bitmap::new(size);\n buffer.fg_bitmap = Bitmap::new(size);\n buffer.attributes = AttributeBuffer::new(size);\n }\n\n let front = &mut self.buffers[self.frame_counter & 1];\n // Trigger a full redraw. (Yes, it's a hack.)\n front.fg_bitmap.fill(1);\n // Trigger a cursor update as well, just to be sure.\n front.cursor = Cursor::new_invalid();\n }\n\n self.frame_counter = self.frame_counter.wrapping_add(1);\n\n let back = &mut self.buffers[self.frame_counter & 1];\n\n back.text.fill_whitespace();\n back.bg_bitmap.fill(self.background_fill);\n back.fg_bitmap.fill(self.foreground_fill);\n back.attributes.reset();\n back.cursor = Cursor::new_disabled();\n }\n\n /// Replaces text contents in a single line of the framebuffer.\n /// All coordinates are in viewport coordinates.\n /// Assumes that control characters have been replaced or escaped.\n pub fn replace_text(\n &mut self,\n y: CoordType,\n origin_x: CoordType,\n clip_right: CoordType,\n text: &str,\n ) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.text.replace_text(y, origin_x, clip_right, text)\n }\n\n /// Draws a scrollbar in the given `track` rectangle.\n ///\n /// Not entirely sure why I put it here instead of elsewhere.\n ///\n /// # Parameters\n ///\n /// * `clip_rect`: Clips the rendering to this rectangle.\n /// This is relevant when you have scrollareas inside scrollareas.\n /// * `track`: The rectangle in which to draw the scrollbar.\n /// In absolute viewport coordinates.\n /// * `content_offset`: The current offset of the scrollarea.\n /// * `content_height`: The height of the scrollarea content.\n pub fn draw_scrollbar(\n &mut self,\n clip_rect: Rect,\n track: Rect,\n content_offset: CoordType,\n content_height: CoordType,\n ) -> CoordType {\n let track_clipped = track.intersect(clip_rect);\n if track_clipped.is_empty() {\n return 0;\n }\n\n let viewport_height = track.height();\n // The content height is at least the viewport height.\n let content_height = content_height.max(viewport_height);\n\n // No need to draw a scrollbar if the content fits in the viewport.\n let content_offset_max = content_height - viewport_height;\n if content_offset_max == 0 {\n return 0;\n }\n\n // The content offset must be at least one viewport height from the bottom.\n // You don't want to scroll past the end after all...\n let content_offset = content_offset.clamp(0, content_offset_max);\n\n // In order to increase the visual resolution of the scrollbar,\n // we'll use 1/8th blocks to represent the thumb.\n // First, scale the offsets to get that 1/8th resolution.\n let viewport_height = viewport_height as i64 * 8;\n let content_offset_max = content_offset_max as i64 * 8;\n let content_offset = content_offset as i64 * 8;\n let content_height = content_height as i64 * 8;\n\n // The proportional thumb height (0-1) is the fraction of viewport and\n // content height. The taller the content, the smaller the thumb:\n // = viewport_height / content_height\n // We then scale that to the viewport height to get the height in 1/8th units.\n // = viewport_height * viewport_height / content_height\n // We add content_height/2 to round the integer division, which results in a numerator of:\n // = viewport_height * viewport_height + content_height / 2\n let numerator = viewport_height * viewport_height + content_height / 2;\n let thumb_height = numerator / content_height;\n // Ensure the thumb has a minimum size of 1 row.\n let thumb_height = thumb_height.max(8);\n\n // The proportional thumb top position (0-1) is:\n // = content_offset / content_offset_max\n // The maximum thumb top position is the viewport height minus the thumb height:\n // = viewport_height - thumb_height\n // To get the thumb top position in 1/8th units, we multiply both:\n // = (viewport_height - thumb_height) * content_offset / content_offset_max\n // We add content_offset_max/2 to round the integer division, which results in a numerator of:\n // = (viewport_height - thumb_height) * content_offset + content_offset_max / 2\n let numerator = (viewport_height - thumb_height) * content_offset + content_offset_max / 2;\n let thumb_top = numerator / content_offset_max;\n // The thumb bottom position is the thumb top position plus the thumb height.\n let thumb_bottom = thumb_top + thumb_height;\n\n // Shift to absolute coordinates.\n let thumb_top = thumb_top + track.top as i64 * 8;\n let thumb_bottom = thumb_bottom + track.top as i64 * 8;\n\n // Clamp to the visible area.\n let thumb_top = thumb_top.max(track_clipped.top as i64 * 8);\n let thumb_bottom = thumb_bottom.min(track_clipped.bottom as i64 * 8);\n\n // Calculate the height of the top/bottom cell of the thumb.\n let top_fract = (thumb_top % 8) as CoordType;\n let bottom_fract = (thumb_bottom % 8) as CoordType;\n\n // Shift to absolute coordinates.\n let thumb_top = ((thumb_top + 7) / 8) as CoordType;\n let thumb_bottom = (thumb_bottom / 8) as CoordType;\n\n self.blend_bg(track_clipped, self.indexed(IndexedColor::BrightBlack));\n self.blend_fg(track_clipped, self.indexed(IndexedColor::BrightWhite));\n\n // Draw the full blocks.\n for y in thumb_top..thumb_bottom {\n self.replace_text(y, track_clipped.left, track_clipped.right, \"█\");\n }\n\n // Draw the top/bottom cell of the thumb.\n // U+2581 to U+2588, 1/8th block to 8/8th block elements glyphs: ▁▂▃▄▅▆▇█\n // In UTF8: E2 96 81 to E2 96 88\n let mut fract_buf = [0xE2, 0x96, 0x88];\n if top_fract != 0 {\n fract_buf[2] = (0x88 - top_fract) as u8;\n self.replace_text(thumb_top - 1, track_clipped.left, track_clipped.right, unsafe {\n std::str::from_utf8_unchecked(&fract_buf)\n });\n }\n if bottom_fract != 0 {\n fract_buf[2] = (0x88 - bottom_fract) as u8;\n self.replace_text(thumb_bottom, track_clipped.left, track_clipped.right, unsafe {\n std::str::from_utf8_unchecked(&fract_buf)\n });\n let rect = Rect {\n left: track_clipped.left,\n top: thumb_bottom,\n right: track_clipped.right,\n bottom: thumb_bottom + 1,\n };\n self.blend_bg(rect, self.indexed(IndexedColor::BrightWhite));\n self.blend_fg(rect, self.indexed(IndexedColor::BrightBlack));\n }\n\n ((thumb_height + 4) / 8) as CoordType\n }\n\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.indexed_colors[index as usize]\n }\n\n /// Returns a color from the palette.\n ///\n /// To facilitate constant folding by the compiler,\n /// alpha is given as a fraction (`numerator` / `denominator`).\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n let c = self.indexed_colors[index as usize];\n let a = 255 * numerator / denominator;\n let r = (((c >> 16) & 0xFF) * numerator) / denominator;\n let g = (((c >> 8) & 0xFF) * numerator) / denominator;\n let b = ((c & 0xFF) * numerator) / denominator;\n a << 24 | r << 16 | g << 8 | b\n }\n\n /// Returns a color opposite to the brightness of the given `color`.\n pub fn contrasted(&self, color: u32) -> u32 {\n let idx = (color as usize).wrapping_mul(HASH_MULTIPLIER) >> CACHE_TABLE_SHIFT;\n let slot = self.contrast_colors[idx].get();\n if slot.0 == color { slot.1 } else { self.contrasted_slow(color) }\n }\n\n #[cold]\n fn contrasted_slow(&self, color: u32) -> u32 {\n let idx = (color as usize).wrapping_mul(HASH_MULTIPLIER) >> CACHE_TABLE_SHIFT;\n let contrast = self.auto_colors[Self::is_dark(color) as usize];\n self.contrast_colors[idx].set((color, contrast));\n contrast\n }\n\n fn is_dark(color: u32) -> bool {\n srgb_to_oklab(color).l < 0.5\n }\n\n /// Blends the given sRGB color onto the background bitmap.\n ///\n /// TODO: The current approach blends foreground/background independently,\n /// but ideally `blend_bg` with semi-transparent dark should also darken text below it.\n pub fn blend_bg(&mut self, target: Rect, bg: u32) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.bg_bitmap.blend(target, bg);\n }\n\n /// Blends the given sRGB color onto the foreground bitmap.\n ///\n /// TODO: The current approach blends foreground/background independently,\n /// but ideally `blend_fg` should blend with the background color below it.\n pub fn blend_fg(&mut self, target: Rect, fg: u32) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.fg_bitmap.blend(target, fg);\n }\n\n /// Reverses the foreground and background colors in the given rectangle.\n pub fn reverse(&mut self, target: Rect) {\n let back = &mut self.buffers[self.frame_counter & 1];\n\n let target = target.intersect(back.bg_bitmap.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = back.bg_bitmap.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let bg = &mut back.bg_bitmap.data[beg..end];\n let fg = &mut back.fg_bitmap.data[beg..end];\n bg.swap_with_slice(fg);\n }\n }\n\n /// Replaces VT attributes in the given rectangle.\n pub fn replace_attr(&mut self, target: Rect, mask: Attributes, attr: Attributes) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.attributes.replace(target, mask, attr);\n }\n\n /// Sets the current visible cursor position and type.\n ///\n /// Call this when focus is inside an editable area and you want to show the cursor.\n pub fn set_cursor(&mut self, pos: Point, overtype: bool) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.cursor.pos = pos;\n back.cursor.overtype = overtype;\n }\n\n /// Renders the framebuffer contents accumulated since the\n /// last call to `flip()` and returns them serialized as VT.\n pub fn render<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n let idx = self.frame_counter & 1;\n // Borrows the front/back buffers without letting Rust know that we have a reference to self.\n // SAFETY: Well this is certainly correct, but whether Rust and its strict rules likes it is another question.\n let (back, front) = unsafe {\n let ptr = self.buffers.as_mut_ptr();\n let back = &mut *ptr.add(idx);\n let front = &*ptr.add(1 - idx);\n (back, front)\n };\n\n let mut front_lines = front.text.lines.iter(); // hahaha\n let mut front_bgs = front.bg_bitmap.iter();\n let mut front_fgs = front.fg_bitmap.iter();\n let mut front_attrs = front.attributes.iter();\n\n let mut back_lines = back.text.lines.iter();\n let mut back_bgs = back.bg_bitmap.iter();\n let mut back_fgs = back.fg_bitmap.iter();\n let mut back_attrs = back.attributes.iter();\n\n let mut result = ArenaString::new_in(arena);\n let mut last_bg = u64::MAX;\n let mut last_fg = u64::MAX;\n let mut last_attr = Attributes::None;\n\n for y in 0..front.text.size.height {\n // SAFETY: The only thing that changes the size of these containers,\n // is the reset() method and it always resets front/back to the same size.\n let front_line = unsafe { front_lines.next().unwrap_unchecked() };\n let front_bg = unsafe { front_bgs.next().unwrap_unchecked() };\n let front_fg = unsafe { front_fgs.next().unwrap_unchecked() };\n let front_attr = unsafe { front_attrs.next().unwrap_unchecked() };\n\n let back_line = unsafe { back_lines.next().unwrap_unchecked() };\n let back_bg = unsafe { back_bgs.next().unwrap_unchecked() };\n let back_fg = unsafe { back_fgs.next().unwrap_unchecked() };\n let back_attr = unsafe { back_attrs.next().unwrap_unchecked() };\n\n // TODO: Ideally, we should properly diff the contents and so if\n // only parts of a line change, we should only update those parts.\n if front_line == back_line\n && front_bg == back_bg\n && front_fg == back_fg\n && front_attr == back_attr\n {\n continue;\n }\n\n let line_bytes = back_line.as_bytes();\n let mut cfg = MeasurementConfig::new(&line_bytes);\n let mut chunk_end = 0;\n\n if result.is_empty() {\n result.push_str(\"\\x1b[m\");\n }\n _ = write!(result, \"\\x1b[{};1H\", y + 1);\n\n while {\n let bg = back_bg[chunk_end];\n let fg = back_fg[chunk_end];\n let attr = back_attr[chunk_end];\n\n // Chunk into runs of the same color.\n while {\n chunk_end += 1;\n chunk_end < back_bg.len()\n && back_bg[chunk_end] == bg\n && back_fg[chunk_end] == fg\n && back_attr[chunk_end] == attr\n } {}\n\n if last_bg != bg as u64 {\n last_bg = bg as u64;\n self.format_color(&mut result, false, bg);\n }\n\n if last_fg != fg as u64 {\n last_fg = fg as u64;\n self.format_color(&mut result, true, fg);\n }\n\n if last_attr != attr {\n let diff = last_attr ^ attr;\n if diff.is(Attributes::Italic) {\n if attr.is(Attributes::Italic) {\n result.push_str(\"\\x1b[3m\");\n } else {\n result.push_str(\"\\x1b[23m\");\n }\n }\n if diff.is(Attributes::Underlined) {\n if attr.is(Attributes::Underlined) {\n result.push_str(\"\\x1b[4m\");\n } else {\n result.push_str(\"\\x1b[24m\");\n }\n }\n last_attr = attr;\n }\n\n let beg = cfg.cursor().offset;\n let end = cfg.goto_visual(Point { x: chunk_end as CoordType, y: 0 }).offset;\n result.push_str(&back_line[beg..end]);\n\n chunk_end < back_bg.len()\n } {}\n }\n\n // If the cursor has changed since the last frame we naturally need to update it,\n // but this also applies if the code above wrote to the screen,\n // as it uses CUP sequences to reposition the cursor for writing.\n if !result.is_empty() || back.cursor != front.cursor {\n if back.cursor.pos.x >= 0 && back.cursor.pos.y >= 0 {\n // CUP to the cursor position.\n // DECSCUSR to set the cursor style.\n // DECTCEM to show the cursor.\n _ = write!(\n result,\n \"\\x1b[{};{}H\\x1b[{} q\\x1b[?25h\",\n back.cursor.pos.y + 1,\n back.cursor.pos.x + 1,\n if back.cursor.overtype { 1 } else { 5 }\n );\n } else {\n // DECTCEM to hide the cursor.\n result.push_str(\"\\x1b[?25l\");\n }\n }\n\n result\n }\n\n fn format_color(&self, dst: &mut ArenaString, fg: bool, mut color: u32) {\n let typ = if fg { '3' } else { '4' };\n\n // Some terminals support transparent backgrounds which are used\n // if the default background color is active (CSI 49 m).\n //\n // If [`Framebuffer::set_indexed_colors`] was never called, we assume\n // that the terminal doesn't support transparency and initialize the\n // background bitmap with the `DEFAULT_THEME` default background color.\n // Otherwise, we assume that the terminal supports transparency\n // and initialize it with 0x00000000 (transparent).\n //\n // We also apply this to the foreground color, because it compresses\n // the output slightly and ensures that we keep \"default foreground\"\n // and \"color that happens to be default foreground\" separate.\n // (This also applies to the background color by the way.)\n if color == 0 {\n _ = write!(dst, \"\\x1b[{typ}9m\");\n return;\n }\n\n if (color & 0xff000000) != 0xff000000 {\n let idx = if fg { IndexedColor::Foreground } else { IndexedColor::Background };\n let dst = self.indexed(idx);\n color = oklab_blend(dst, color);\n }\n\n let r = color & 0xff;\n let g = (color >> 8) & 0xff;\n let b = (color >> 16) & 0xff;\n _ = write!(dst, \"\\x1b[{typ}8;2;{r};{g};{b}m\");\n }\n}\n\n#[derive(Default)]\nstruct Buffer {\n text: LineBuffer,\n bg_bitmap: Bitmap,\n fg_bitmap: Bitmap,\n attributes: AttributeBuffer,\n cursor: Cursor,\n}\n\n/// A buffer for the text contents of the framebuffer.\n#[derive(Default)]\nstruct LineBuffer {\n lines: Vec,\n size: Size,\n}\n\nimpl LineBuffer {\n fn new(size: Size) -> Self {\n Self { lines: vec![String::new(); size.height as usize], size }\n }\n\n fn fill_whitespace(&mut self) {\n let width = self.size.width as usize;\n for l in &mut self.lines {\n l.clear();\n l.reserve(width + width / 2);\n\n let buf = unsafe { l.as_mut_vec() };\n // Compiles down to `memset()`.\n buf.extend(std::iter::repeat_n(b' ', width));\n }\n }\n\n /// Replaces text contents in a single line of the framebuffer.\n /// All coordinates are in viewport coordinates.\n /// Assumes that control characters have been replaced or escaped.\n fn replace_text(\n &mut self,\n y: CoordType,\n origin_x: CoordType,\n clip_right: CoordType,\n text: &str,\n ) {\n let Some(line) = self.lines.get_mut(y as usize) else {\n return;\n };\n\n let bytes = text.as_bytes();\n let clip_right = clip_right.clamp(0, self.size.width);\n let layout_width = clip_right - origin_x;\n\n // Can't insert text that can't fit or is empty.\n if layout_width <= 0 || bytes.is_empty() {\n return;\n }\n\n let mut cfg = MeasurementConfig::new(&bytes);\n\n // Check if the text intersects with the left edge of the framebuffer\n // and figure out the parts that are inside.\n let mut left = origin_x;\n if left < 0 {\n let mut cursor = cfg.goto_visual(Point { x: -left, y: 0 });\n\n if left + cursor.visual_pos.x < 0 && cursor.offset < text.len() {\n // `-left` must've intersected a wide glyph and since goto_visual stops _before_ reaching the target,\n // we stopped before the wide glyph and thus must step forward to the next glyph.\n cursor = cfg.goto_logical(Point { x: cursor.logical_pos.x + 1, y: 0 });\n }\n\n left += cursor.visual_pos.x;\n }\n\n // If the text still starts outside the framebuffer, we must've ran out of text above.\n // Otherwise, if it starts outside the right edge to begin with, we can't insert it anyway.\n if left < 0 || left >= clip_right {\n return;\n }\n\n // Measure the width of the new text (= `res_new.visual_target.x`).\n let beg_off = cfg.cursor().offset;\n let end = cfg.goto_visual(Point { x: layout_width, y: 0 });\n\n // Figure out at which byte offset the new text gets inserted.\n let right = left + end.visual_pos.x;\n let line_bytes = line.as_bytes();\n let mut cfg_old = MeasurementConfig::new(&line_bytes);\n let res_old_beg = cfg_old.goto_visual(Point { x: left, y: 0 });\n let mut res_old_end = cfg_old.goto_visual(Point { x: right, y: 0 });\n\n // Since the goto functions will always stop short of the target position,\n // we need to manually step beyond it if we intersect with a wide glyph.\n if res_old_end.visual_pos.x < right {\n res_old_end = cfg_old.goto_logical(Point { x: res_old_end.logical_pos.x + 1, y: 0 });\n }\n\n // If we intersect a wide glyph, we need to pad the new text with spaces.\n let src = &text[beg_off..end.offset];\n let overlap_beg = (left - res_old_beg.visual_pos.x).max(0) as usize;\n let overlap_end = (res_old_end.visual_pos.x - right).max(0) as usize;\n let total_add = src.len() + overlap_beg + overlap_end;\n let total_del = res_old_end.offset - res_old_beg.offset;\n\n // This is basically a hand-written version of `Vec::splice()`,\n // but for strings under the assumption that all inputs are valid.\n // It also takes care of `overlap_beg` and `overlap_end` by inserting spaces.\n unsafe {\n // SAFETY: Our ucd code only returns valid UTF-8 offsets.\n // If it didn't that'd be a priority -9000 bug for any text editor.\n // And apart from that, all inputs are &str (= UTF8).\n let dst = line.as_mut_vec();\n\n let dst_len = dst.len();\n let src_len = src.len();\n\n // Make room for the new elements. NOTE that this must be done before\n // we call as_mut_ptr, or else we risk accessing a stale pointer.\n // We only need to reserve as much as the string actually grows by.\n dst.reserve(total_add.saturating_sub(total_del));\n\n // Move the pointer to the start of the insert.\n let mut ptr = dst.as_mut_ptr().add(res_old_beg.offset);\n\n // Move the tail end of the string by `total_add - total_del`-many bytes.\n // This both effectively deletes the old text and makes room for the new text.\n if total_add != total_del {\n // Move the tail of the vector to make room for the new elements.\n ptr::copy(\n ptr.add(total_del),\n ptr.add(total_add),\n dst_len - total_del - res_old_beg.offset,\n );\n }\n\n // Pad left.\n for _ in 0..overlap_beg {\n ptr.write(b' ');\n ptr = ptr.add(1);\n }\n\n // Copy the new elements into the vector.\n ptr::copy_nonoverlapping(src.as_ptr(), ptr, src_len);\n ptr = ptr.add(src_len);\n\n // Pad right.\n for _ in 0..overlap_end {\n ptr.write(b' ');\n ptr = ptr.add(1);\n }\n\n // Update the length of the vector.\n dst.set_len(dst_len - total_del + total_add);\n }\n }\n}\n\n/// An sRGB bitmap.\n#[derive(Default)]\nstruct Bitmap {\n data: Vec,\n size: Size,\n}\n\nimpl Bitmap {\n fn new(size: Size) -> Self {\n Self { data: vec![0; (size.width * size.height) as usize], size }\n }\n\n fn fill(&mut self, color: u32) {\n memset(&mut self.data, color);\n }\n\n /// Blends the given sRGB color onto the bitmap.\n ///\n /// This uses the `oklab` color space for blending so the\n /// resulting colors may look different from what you'd expect.\n fn blend(&mut self, target: Rect, color: u32) {\n if (color & 0xff000000) == 0x00000000 {\n return;\n }\n\n let target = target.intersect(self.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = self.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let data = &mut self.data[beg..end];\n\n if (color & 0xff000000) == 0xff000000 {\n memset(data, color);\n } else {\n let end = data.len();\n let mut off = 0;\n\n while {\n let c = data[off];\n\n // Chunk into runs of the same color, so that we only call alpha_blend once per run.\n let chunk_beg = off;\n while {\n off += 1;\n off < end && data[off] == c\n } {}\n let chunk_end = off;\n\n let c = oklab_blend(c, color);\n memset(&mut data[chunk_beg..chunk_end], c);\n\n off < end\n } {}\n }\n }\n }\n\n /// Iterates over each row in the bitmap.\n fn iter(&self) -> ChunksExact<'_, u32> {\n self.data.chunks_exact(self.size.width as usize)\n }\n}\n\n/// A bitfield for VT text attributes.\n///\n/// It being a bitfield allows for simple diffing.\n#[repr(transparent)]\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub struct Attributes(u8);\n\n#[allow(non_upper_case_globals)]\nimpl Attributes {\n pub const None: Self = Self(0);\n pub const Italic: Self = Self(0b1);\n pub const Underlined: Self = Self(0b10);\n pub const All: Self = Self(0b11);\n\n pub const fn is(self, attr: Self) -> bool {\n (self.0 & attr.0) == attr.0\n }\n}\n\nunsafe impl MemsetSafe for Attributes {}\n\nimpl BitOr for Attributes {\n type Output = Self;\n\n fn bitor(self, rhs: Self) -> Self::Output {\n Self(self.0 | rhs.0)\n }\n}\n\nimpl BitXor for Attributes {\n type Output = Self;\n\n fn bitxor(self, rhs: Self) -> Self::Output {\n Self(self.0 ^ rhs.0)\n }\n}\n\n/// Stores VT attributes for the framebuffer.\n#[derive(Default)]\nstruct AttributeBuffer {\n data: Vec,\n size: Size,\n}\n\nimpl AttributeBuffer {\n fn new(size: Size) -> Self {\n Self { data: vec![Default::default(); (size.width * size.height) as usize], size }\n }\n\n fn reset(&mut self) {\n memset(&mut self.data, Default::default());\n }\n\n fn replace(&mut self, target: Rect, mask: Attributes, attr: Attributes) {\n let target = target.intersect(self.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = self.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let dst = &mut self.data[beg..end];\n\n if mask == Attributes::All {\n memset(dst, attr);\n } else {\n for a in dst {\n *a = Attributes(a.0 & !mask.0 | attr.0);\n }\n }\n }\n }\n\n /// Iterates over each row in the bitmap.\n fn iter(&self) -> ChunksExact<'_, Attributes> {\n self.data.chunks_exact(self.size.width as usize)\n }\n}\n\n/// Stores cursor position and type for the framebuffer.\n#[derive(Default, PartialEq, Eq)]\nstruct Cursor {\n pos: Point,\n overtype: bool,\n}\n\nimpl Cursor {\n const fn new_invalid() -> Self {\n Self { pos: Point::MIN, overtype: false }\n }\n\n const fn new_disabled() -> Self {\n Self { pos: Point { x: -1, y: -1 }, overtype: false }\n }\n}\n"], ["/edit/src/bin/edit/main.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![feature(allocator_api, linked_list_cursors, string_from_utf8_lossy_owned)]\n\nmod documents;\nmod draw_editor;\nmod draw_filepicker;\nmod draw_menubar;\nmod draw_statusbar;\nmod localization;\nmod state;\n\nuse std::borrow::Cow;\n#[cfg(feature = \"debug-latency\")]\nuse std::fmt::Write;\nuse std::path::{Path, PathBuf};\nuse std::time::Duration;\nuse std::{env, process};\n\nuse draw_editor::*;\nuse draw_filepicker::*;\nuse draw_menubar::*;\nuse draw_statusbar::*;\nuse edit::arena::{self, Arena, ArenaString, scratch_arena};\nuse edit::framebuffer::{self, IndexedColor};\nuse edit::helpers::{CoordType, KIBI, MEBI, MetricFormatter, Rect, Size};\nuse edit::input::{self, kbmod, vk};\nuse edit::oklab::oklab_blend;\nuse edit::tui::*;\nuse edit::vt::{self, Token};\nuse edit::{apperr, arena_format, base64, path, sys, unicode};\nuse localization::*;\nuse state::*;\n\n#[cfg(target_pointer_width = \"32\")]\nconst SCRATCH_ARENA_CAPACITY: usize = 128 * MEBI;\n#[cfg(target_pointer_width = \"64\")]\nconst SCRATCH_ARENA_CAPACITY: usize = 512 * MEBI;\n\nfn main() -> process::ExitCode {\n if cfg!(debug_assertions) {\n let hook = std::panic::take_hook();\n std::panic::set_hook(Box::new(move |info| {\n drop(RestoreModes);\n drop(sys::Deinit);\n hook(info);\n }));\n }\n\n match run() {\n Ok(()) => process::ExitCode::SUCCESS,\n Err(err) => {\n sys::write_stdout(&format!(\"{}\\n\", FormatApperr::from(err)));\n process::ExitCode::FAILURE\n }\n }\n}\n\nfn run() -> apperr::Result<()> {\n // Init `sys` first, as everything else may depend on its functionality (IO, function pointers, etc.).\n let _sys_deinit = sys::init();\n // Next init `arena`, so that `scratch_arena` works. `loc` depends on it.\n arena::init(SCRATCH_ARENA_CAPACITY)?;\n // Init the `loc` module, so that error messages are localized.\n localization::init();\n\n let mut state = State::new()?;\n if handle_args(&mut state)? {\n return Ok(());\n }\n\n // This will reopen stdin if it's redirected (which may fail) and switch\n // the terminal to raw mode which prevents the user from pressing Ctrl+C.\n // `handle_args` may want to print a help message (must not fail),\n // and reads files (may hang; should be cancelable with Ctrl+C).\n // As such, we call this after `handle_args`.\n sys::switch_modes()?;\n\n let mut vt_parser = vt::Parser::new();\n let mut input_parser = input::Parser::new();\n let mut tui = Tui::new()?;\n\n let _restore = setup_terminal(&mut tui, &mut state, &mut vt_parser);\n\n state.menubar_color_bg = oklab_blend(\n tui.indexed(IndexedColor::Background),\n tui.indexed_alpha(IndexedColor::BrightBlue, 1, 2),\n );\n state.menubar_color_fg = tui.contrasted(state.menubar_color_bg);\n let floater_bg = oklab_blend(\n tui.indexed_alpha(IndexedColor::Background, 2, 3),\n tui.indexed_alpha(IndexedColor::Foreground, 1, 3),\n );\n let floater_fg = tui.contrasted(floater_bg);\n tui.setup_modifier_translations(ModifierTranslations {\n ctrl: loc(LocId::Ctrl),\n alt: loc(LocId::Alt),\n shift: loc(LocId::Shift),\n });\n tui.set_floater_default_bg(floater_bg);\n tui.set_floater_default_fg(floater_fg);\n tui.set_modal_default_bg(floater_bg);\n tui.set_modal_default_fg(floater_fg);\n\n sys::inject_window_size_into_stdin();\n\n #[cfg(feature = \"debug-latency\")]\n let mut last_latency_width = 0;\n\n loop {\n #[cfg(feature = \"debug-latency\")]\n let time_beg;\n #[cfg(feature = \"debug-latency\")]\n let mut passes;\n\n // Process a batch of input.\n {\n let scratch = scratch_arena(None);\n let read_timeout = vt_parser.read_timeout().min(tui.read_timeout());\n let Some(input) = sys::read_stdin(&scratch, read_timeout) else {\n break;\n };\n\n #[cfg(feature = \"debug-latency\")]\n {\n time_beg = std::time::Instant::now();\n passes = 0usize;\n }\n\n let vt_iter = vt_parser.parse(&input);\n let mut input_iter = input_parser.parse(vt_iter);\n\n while {\n let input = input_iter.next();\n let more = input.is_some();\n let mut ctx = tui.create_context(input);\n\n draw(&mut ctx, &mut state);\n\n #[cfg(feature = \"debug-latency\")]\n {\n passes += 1;\n }\n\n more\n } {}\n }\n\n // Continue rendering until the layout has settled.\n // This can take >1 frame, if the input focus is tossed between different controls.\n while tui.needs_settling() {\n let mut ctx = tui.create_context(None);\n\n draw(&mut ctx, &mut state);\n\n #[cfg(feature = \"debug-latency\")]\n {\n passes += 1;\n }\n }\n\n if state.exit {\n break;\n }\n\n // Render the UI and write it to the terminal.\n {\n let scratch = scratch_arena(None);\n let mut output = tui.render(&scratch);\n\n write_terminal_title(&mut output, &mut state);\n\n if state.osc_clipboard_sync {\n write_osc_clipboard(&mut tui, &mut state, &mut output);\n }\n\n #[cfg(feature = \"debug-latency\")]\n {\n // Print the number of passes and latency in the top right corner.\n let time_end = std::time::Instant::now();\n let status = time_end - time_beg;\n\n let scratch_alt = scratch_arena(Some(&scratch));\n let status = arena_format!(\n &scratch_alt,\n \"{}P {}B {:.3}μs\",\n passes,\n output.len(),\n status.as_nanos() as f64 / 1000.0\n );\n\n // \"μs\" is 3 bytes and 2 columns.\n let cols = status.len() as edit::helpers::CoordType - 3 + 2;\n\n // Since the status may shrink and grow, we may have to overwrite the previous one with whitespace.\n let padding = (last_latency_width - cols).max(0);\n\n // If the `output` is already very large,\n // Rust may double the size during the write below.\n // Let's avoid that by reserving the needed size in advance.\n output.reserve_exact(128);\n\n // To avoid moving the cursor, push and pop it onto the VT cursor stack.\n _ = write!(\n output,\n \"\\x1b7\\x1b[0;41;97m\\x1b[1;{0}H{1:2$}{3}\\x1b8\",\n tui.size().width - cols - padding + 1,\n \"\",\n padding as usize,\n status\n );\n\n last_latency_width = cols;\n }\n\n sys::write_stdout(&output);\n }\n }\n\n Ok(())\n}\n\n// Returns true if the application should exit early.\nfn handle_args(state: &mut State) -> apperr::Result {\n let scratch = scratch_arena(None);\n let mut paths: Vec = Vec::new_in(&*scratch);\n let mut cwd = env::current_dir()?;\n\n // The best CLI argument parser in the world.\n for arg in env::args_os().skip(1) {\n if arg == \"-h\" || arg == \"--help\" || (cfg!(windows) && arg == \"/?\") {\n print_help();\n return Ok(true);\n } else if arg == \"-v\" || arg == \"--version\" {\n print_version();\n return Ok(true);\n } else if arg == \"-\" {\n paths.clear();\n break;\n }\n let p = cwd.join(Path::new(&arg));\n let p = path::normalize(&p);\n if !p.is_dir() {\n paths.push(p);\n }\n }\n\n for p in &paths {\n state.documents.add_file_path(p)?;\n }\n if let Some(parent) = paths.first().and_then(|p| p.parent()) {\n cwd = parent.to_path_buf();\n }\n\n if let Some(mut file) = sys::open_stdin_if_redirected() {\n let doc = state.documents.add_untitled()?;\n let mut tb = doc.buffer.borrow_mut();\n tb.read_file(&mut file, None)?;\n tb.mark_as_dirty();\n } else if paths.is_empty() {\n // No files were passed, and stdin is not redirected.\n state.documents.add_untitled()?;\n }\n\n state.file_picker_pending_dir = DisplayablePathBuf::from_path(cwd);\n Ok(false)\n}\n\nfn print_help() {\n sys::write_stdout(concat!(\n \"Usage: edit [OPTIONS] [FILE[:LINE[:COLUMN]]]\\n\",\n \"Options:\\n\",\n \" -h, --help Print this help message\\n\",\n \" -v, --version Print the version number\\n\",\n \"\\n\",\n \"Arguments:\\n\",\n \" FILE[:LINE[:COLUMN]] The file to open, optionally with line and column (e.g., foo.txt:123:45)\\n\",\n ));\n}\n\nfn print_version() {\n sys::write_stdout(concat!(\"edit version \", env!(\"CARGO_PKG_VERSION\"), \"\\n\"));\n}\n\nfn draw(ctx: &mut Context, state: &mut State) {\n draw_menubar(ctx, state);\n draw_editor(ctx, state);\n draw_statusbar(ctx, state);\n\n if state.wants_close {\n draw_handle_wants_close(ctx, state);\n }\n if state.wants_exit {\n draw_handle_wants_exit(ctx, state);\n }\n if state.wants_goto {\n draw_goto_menu(ctx, state);\n }\n if state.wants_file_picker != StateFilePicker::None {\n draw_file_picker(ctx, state);\n }\n if state.wants_save {\n draw_handle_save(ctx, state);\n }\n if state.wants_encoding_change != StateEncodingChange::None {\n draw_dialog_encoding_change(ctx, state);\n }\n if state.wants_go_to_file {\n draw_go_to_file(ctx, state);\n }\n if state.wants_about {\n draw_dialog_about(ctx, state);\n }\n if ctx.clipboard_ref().wants_host_sync() {\n draw_handle_clipboard_change(ctx, state);\n }\n if state.error_log_count != 0 {\n draw_error_log(ctx, state);\n }\n\n if let Some(key) = ctx.keyboard_input() {\n // Shortcuts that are not handled as part of the textarea, etc.\n\n if key == kbmod::CTRL | vk::N {\n draw_add_untitled_document(ctx, state);\n } else if key == kbmod::CTRL | vk::O {\n state.wants_file_picker = StateFilePicker::Open;\n } else if key == kbmod::CTRL | vk::S {\n state.wants_save = true;\n } else if key == kbmod::CTRL_SHIFT | vk::S {\n state.wants_file_picker = StateFilePicker::SaveAs;\n } else if key == kbmod::CTRL | vk::W {\n state.wants_close = true;\n } else if key == kbmod::CTRL | vk::P {\n state.wants_go_to_file = true;\n } else if key == kbmod::CTRL | vk::Q {\n state.wants_exit = true;\n } else if key == kbmod::CTRL | vk::G {\n state.wants_goto = true;\n } else if key == kbmod::CTRL | vk::F && state.wants_search.kind != StateSearchKind::Disabled\n {\n state.wants_search.kind = StateSearchKind::Search;\n state.wants_search.focus = true;\n } else if key == kbmod::CTRL | vk::R && state.wants_search.kind != StateSearchKind::Disabled\n {\n state.wants_search.kind = StateSearchKind::Replace;\n state.wants_search.focus = true;\n } else if key == vk::F3 {\n search_execute(ctx, state, SearchAction::Search);\n } else {\n return;\n }\n\n // All of the above shortcuts happen to require a rerender.\n ctx.needs_rerender();\n ctx.set_input_consumed();\n }\n}\n\nfn draw_handle_wants_exit(_ctx: &mut Context, state: &mut State) {\n while let Some(doc) = state.documents.active() {\n if doc.buffer.borrow().is_dirty() {\n state.wants_close = true;\n return;\n }\n state.documents.remove_active();\n }\n\n if state.documents.len() == 0 {\n state.exit = true;\n }\n}\n\nfn write_terminal_title(output: &mut ArenaString, state: &mut State) {\n let (filename, dirty) = state\n .documents\n .active()\n .map_or((\"\", false), |d| (&d.filename, d.buffer.borrow().is_dirty()));\n\n if filename == state.osc_title_file_status.filename\n && dirty == state.osc_title_file_status.dirty\n {\n return;\n }\n\n output.push_str(\"\\x1b]0;\");\n if !filename.is_empty() {\n if dirty {\n output.push_str(\"● \");\n }\n output.push_str(&sanitize_control_chars(filename));\n output.push_str(\" - \");\n }\n output.push_str(\"edit\\x1b\\\\\");\n\n state.osc_title_file_status.filename = filename.to_string();\n state.osc_title_file_status.dirty = dirty;\n}\n\nconst LARGE_CLIPBOARD_THRESHOLD: usize = 128 * KIBI;\n\nfn draw_handle_clipboard_change(ctx: &mut Context, state: &mut State) {\n let data_len = ctx.clipboard_ref().read().len();\n\n if state.osc_clipboard_always_send || data_len < LARGE_CLIPBOARD_THRESHOLD {\n ctx.clipboard_mut().mark_as_synchronized();\n state.osc_clipboard_sync = true;\n return;\n }\n\n let over_limit = data_len >= SCRATCH_ARENA_CAPACITY / 4;\n let mut done = None;\n\n ctx.modal_begin(\"warning\", loc(LocId::WarningDialogTitle));\n {\n ctx.block_begin(\"description\");\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n if over_limit {\n ctx.label(\"line1\", loc(LocId::LargeClipboardWarningLine1));\n ctx.attr_position(Position::Center);\n ctx.label(\"line2\", loc(LocId::SuperLargeClipboardWarning));\n ctx.attr_position(Position::Center);\n } else {\n let label2 = {\n let template = loc(LocId::LargeClipboardWarningLine2);\n let size = arena_format!(ctx.arena(), \"{}\", MetricFormatter(data_len));\n\n let mut label =\n ArenaString::with_capacity_in(template.len() + size.len(), ctx.arena());\n label.push_str(template);\n label.replace_once_in_place(\"{size}\", &size);\n label\n };\n\n ctx.label(\"line1\", loc(LocId::LargeClipboardWarningLine1));\n ctx.attr_position(Position::Center);\n ctx.label(\"line2\", &label2);\n ctx.attr_position(Position::Center);\n ctx.label(\"line3\", loc(LocId::LargeClipboardWarningLine3));\n ctx.attr_position(Position::Center);\n }\n ctx.block_end();\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n if over_limit {\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n done = Some(true);\n }\n ctx.inherit_focus();\n } else {\n if ctx.button(\"always\", loc(LocId::Always), ButtonStyle::default()) {\n state.osc_clipboard_always_send = true;\n done = Some(true);\n }\n\n if ctx.button(\"yes\", loc(LocId::Yes), ButtonStyle::default()) {\n done = Some(true);\n }\n if data_len < 10 * LARGE_CLIPBOARD_THRESHOLD {\n ctx.inherit_focus();\n }\n\n if ctx.button(\"no\", loc(LocId::No), ButtonStyle::default()) {\n done = Some(false);\n }\n if data_len >= 10 * LARGE_CLIPBOARD_THRESHOLD {\n ctx.inherit_focus();\n }\n }\n }\n ctx.table_end();\n }\n if ctx.modal_end() {\n done = Some(false);\n }\n\n if let Some(sync) = done {\n state.osc_clipboard_sync = sync;\n ctx.clipboard_mut().mark_as_synchronized();\n ctx.needs_rerender();\n }\n}\n\n#[cold]\nfn write_osc_clipboard(tui: &mut Tui, state: &mut State, output: &mut ArenaString) {\n let clipboard = tui.clipboard_mut();\n let data = clipboard.read();\n\n if !data.is_empty() {\n // Rust doubles the size of a string when it needs to grow it.\n // If `data` is *really* large, this may then double\n // the size of the `output` from e.g. 100MB to 200MB. Not good.\n // We can avoid that by reserving the needed size in advance.\n output.reserve_exact(base64::encode_len(data.len()) + 16);\n output.push_str(\"\\x1b]52;c;\");\n base64::encode(output, data);\n output.push_str(\"\\x1b\\\\\");\n }\n\n state.osc_clipboard_sync = false;\n}\n\nstruct RestoreModes;\n\nimpl Drop for RestoreModes {\n fn drop(&mut self) {\n // Same as in the beginning but in the reverse order.\n // It also includes DECSCUSR 0 to reset the cursor style and DECTCEM to show the cursor.\n // We specifically don't reset mode 1036, because most applications expect it to be set nowadays.\n sys::write_stdout(\"\\x1b[0 q\\x1b[?25h\\x1b]0;\\x07\\x1b[?1002;1006;2004l\\x1b[?1049l\");\n }\n}\n\nfn setup_terminal(tui: &mut Tui, state: &mut State, vt_parser: &mut vt::Parser) -> RestoreModes {\n sys::write_stdout(concat!(\n // 1049: Alternative Screen Buffer\n // I put the ASB switch in the beginning, just in case the terminal performs\n // some additional state tracking beyond the modes we enable/disable.\n // 1002: Cell Motion Mouse Tracking\n // 1006: SGR Mouse Mode\n // 2004: Bracketed Paste Mode\n // 1036: Xterm: \"meta sends escape\" (Alt keypresses should be encoded with ESC + char)\n \"\\x1b[?1049h\\x1b[?1002;1006;2004h\\x1b[?1036h\",\n // OSC 4 color table requests for indices 0 through 15 (base colors).\n \"\\x1b]4;0;?;1;?;2;?;3;?;4;?;5;?;6;?;7;?\\x07\",\n \"\\x1b]4;8;?;9;?;10;?;11;?;12;?;13;?;14;?;15;?\\x07\",\n // OSC 10 and 11 queries for the current foreground and background colors.\n \"\\x1b]10;?\\x07\\x1b]11;?\\x07\",\n // Test whether ambiguous width characters are two columns wide.\n // We use \"…\", because it's the most common ambiguous width character we use,\n // and the old Windows conhost doesn't actually use wcwidth, it measures the\n // actual display width of the character and assigns it columns accordingly.\n // We detect it by writing the character and asking for the cursor position.\n \"\\r…\\x1b[6n\",\n // CSI c reports the terminal capabilities.\n // It also helps us to detect the end of the responses, because not all\n // terminals support the OSC queries, but all of them support CSI c.\n \"\\x1b[c\",\n ));\n\n let mut done = false;\n let mut osc_buffer = String::new();\n let mut indexed_colors = framebuffer::DEFAULT_THEME;\n let mut color_responses = 0;\n let mut ambiguous_width = 1;\n\n while !done {\n let scratch = scratch_arena(None);\n\n // We explicitly set a high read timeout, because we're not\n // waiting for user keyboard input. If we encounter a lone ESC,\n // it's unlikely to be from a ESC keypress, but rather from a VT sequence.\n let Some(input) = sys::read_stdin(&scratch, Duration::from_secs(3)) else {\n break;\n };\n\n let mut vt_stream = vt_parser.parse(&input);\n while let Some(token) = vt_stream.next() {\n match token {\n Token::Csi(csi) => match csi.final_byte {\n 'c' => done = true,\n // CPR (Cursor Position Report) response.\n 'R' => ambiguous_width = csi.params[1] as CoordType - 1,\n _ => {}\n },\n Token::Osc { mut data, partial } => {\n if partial {\n osc_buffer.push_str(data);\n continue;\n }\n if !osc_buffer.is_empty() {\n osc_buffer.push_str(data);\n data = &osc_buffer;\n }\n\n let mut splits = data.split_terminator(';');\n\n let color = match splits.next().unwrap_or(\"\") {\n // The response is `4;;rgb://`.\n \"4\" => match splits.next().unwrap_or(\"\").parse::() {\n Ok(val) if val < 16 => &mut indexed_colors[val],\n _ => continue,\n },\n // The response is `10;rgb://`.\n \"10\" => &mut indexed_colors[IndexedColor::Foreground as usize],\n // The response is `11;rgb://`.\n \"11\" => &mut indexed_colors[IndexedColor::Background as usize],\n _ => continue,\n };\n\n let color_param = splits.next().unwrap_or(\"\");\n if !color_param.starts_with(\"rgb:\") {\n continue;\n }\n\n let mut iter = color_param[4..].split_terminator('/');\n let rgb_parts = [(); 3].map(|_| iter.next().unwrap_or(\"0\"));\n let mut rgb = 0;\n\n for part in rgb_parts {\n if part.len() == 2 || part.len() == 4 {\n let Ok(mut val) = usize::from_str_radix(part, 16) else {\n continue;\n };\n if part.len() == 4 {\n // Round from 16 bits to 8 bits.\n val = (val * 0xff + 0x7fff) / 0xffff;\n }\n rgb = (rgb >> 8) | ((val as u32) << 16);\n }\n }\n\n *color = rgb | 0xff000000;\n color_responses += 1;\n osc_buffer.clear();\n }\n _ => {}\n }\n }\n }\n\n if ambiguous_width == 2 {\n unicode::setup_ambiguous_width(2);\n state.documents.reflow_all();\n }\n\n if color_responses == indexed_colors.len() {\n tui.setup_indexed_colors(indexed_colors);\n }\n\n RestoreModes\n}\n\n/// Strips all C0 control characters from the string and replaces them with \"_\".\n///\n/// Jury is still out on whether this should also strip C1 control characters.\n/// That requires parsing UTF8 codepoints, which is annoying.\nfn sanitize_control_chars(text: &str) -> Cow<'_, str> {\n if let Some(off) = text.bytes().position(|b| (..0x20).contains(&b)) {\n let mut sanitized = text.to_string();\n // SAFETY: We only search for ASCII and replace it with ASCII.\n let vec = unsafe { sanitized.as_bytes_mut() };\n\n for i in &mut vec[off..] {\n *i = if (..0x20).contains(i) { b'_' } else { *i }\n }\n\n Cow::Owned(sanitized)\n } else {\n Cow::Borrowed(text)\n }\n}\n"], ["/edit/src/unicode/measurement.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::hint::cold_path;\n\nuse super::Utf8Chars;\nuse super::tables::*;\nuse crate::document::ReadableDocument;\nuse crate::helpers::{CoordType, Point};\n\n// On one hand it's disgusting that I wrote this as a global variable, but on the\n// other hand, this isn't a public library API, and it makes the code a lot cleaner,\n// because we don't need to inject this once-per-process value everywhere.\nstatic mut AMBIGUOUS_WIDTH: usize = 1;\n\n/// Sets the width of \"ambiguous\" width characters as per \"UAX #11: East Asian Width\".\n///\n/// Defaults to 1.\npub fn setup_ambiguous_width(ambiguous_width: CoordType) {\n unsafe { AMBIGUOUS_WIDTH = ambiguous_width as usize };\n}\n\n#[inline]\nfn ambiguous_width() -> usize {\n // SAFETY: This is a global variable that is set once per process.\n // It is never changed after that, so this is safe to call.\n unsafe { AMBIGUOUS_WIDTH }\n}\n\n/// Stores a position inside a [`ReadableDocument`].\n///\n/// The cursor tracks both the absolute byte-offset,\n/// as well as the position in terminal-related coordinates.\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Cursor {\n /// Offset in bytes within the buffer.\n pub offset: usize,\n /// Position in the buffer in lines (.y) and grapheme clusters (.x).\n ///\n /// Line wrapping has NO influence on this.\n pub logical_pos: Point,\n /// Position in the buffer in laid out rows (.y) and columns (.x).\n ///\n /// Line wrapping has an influence on this.\n pub visual_pos: Point,\n /// Horizontal position in visual columns.\n ///\n /// Line wrapping has NO influence on this and if word wrap is disabled,\n /// it's identical to `visual_pos.x`. This is useful for calculating tab widths.\n pub column: CoordType,\n /// When `measure_forward` hits the `word_wrap_column`, the question is:\n /// Was there a wrap opportunity on this line? Because if there wasn't,\n /// a hard-wrap is required; otherwise, the word that is being laid-out is\n /// moved to the next line. This boolean carries this state between calls.\n pub wrap_opp: bool,\n}\n\n/// Your entrypoint to navigating inside a [`ReadableDocument`].\n#[derive(Clone)]\npub struct MeasurementConfig<'doc> {\n cursor: Cursor,\n tab_size: CoordType,\n word_wrap_column: CoordType,\n buffer: &'doc dyn ReadableDocument,\n}\n\nimpl<'doc> MeasurementConfig<'doc> {\n /// Creates a new [`MeasurementConfig`] for the given document.\n pub fn new(buffer: &'doc dyn ReadableDocument) -> Self {\n Self { cursor: Default::default(), tab_size: 8, word_wrap_column: 0, buffer }\n }\n\n /// Sets the initial cursor to the given position.\n ///\n /// WARNING: While the code doesn't panic if the cursor is invalid,\n /// the results will obviously be complete garbage.\n pub fn with_cursor(mut self, cursor: Cursor) -> Self {\n self.cursor = cursor;\n self\n }\n\n /// Sets the tab size.\n ///\n /// Defaults to 8, because that's what a tab in terminals evaluates to.\n pub fn with_tab_size(mut self, tab_size: CoordType) -> Self {\n self.tab_size = tab_size.max(1);\n self\n }\n\n /// You want word wrap? Set it here!\n ///\n /// Defaults to 0, which means no word wrap.\n pub fn with_word_wrap_column(mut self, word_wrap_column: CoordType) -> Self {\n self.word_wrap_column = word_wrap_column;\n self\n }\n\n /// Navigates **forward** to the given absolute offset.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_offset(&mut self, offset: usize) -> Cursor {\n self.measure_forward(offset, Point::MAX, Point::MAX)\n }\n\n /// Navigates **forward** to the given logical position.\n ///\n /// Logical positions are in lines and grapheme clusters.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_logical(&mut self, logical_target: Point) -> Cursor {\n self.measure_forward(usize::MAX, logical_target, Point::MAX)\n }\n\n /// Navigates **forward** to the given visual position.\n ///\n /// Visual positions are in laid out rows and columns.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_visual(&mut self, visual_target: Point) -> Cursor {\n self.measure_forward(usize::MAX, Point::MAX, visual_target)\n }\n\n /// Returns the current cursor position.\n pub fn cursor(&self) -> Cursor {\n self.cursor\n }\n\n // NOTE that going to a visual target can result in ambiguous results,\n // where going to an identical logical target will yield a different result.\n //\n // Imagine if you have a `word_wrap_column` of 6 and there's \"Hello World\" on the line:\n // `goto_logical` will return a `visual_pos` of {0,1}, while `goto_visual` returns {6,0}.\n // This is because from a logical POV, if the wrap location equals the wrap column,\n // the wrap exists on both lines and it'll default to wrapping. `goto_visual` however will always\n // try to return a Y position that matches the requested position, so that Home/End works properly.\n fn measure_forward(\n &mut self,\n offset_target: usize,\n logical_target: Point,\n visual_target: Point,\n ) -> Cursor {\n if self.cursor.offset >= offset_target\n || self.cursor.logical_pos >= logical_target\n || self.cursor.visual_pos >= visual_target\n {\n return self.cursor;\n }\n\n let mut offset = self.cursor.offset;\n let mut logical_pos_x = self.cursor.logical_pos.x;\n let mut logical_pos_y = self.cursor.logical_pos.y;\n let mut visual_pos_x = self.cursor.visual_pos.x;\n let mut visual_pos_y = self.cursor.visual_pos.y;\n let mut column = self.cursor.column;\n\n let mut logical_target_x = Self::calc_target_x(logical_target, logical_pos_y);\n let mut visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n\n // wrap_opp = Wrap Opportunity\n // These store the position and column of the last wrap opportunity. If `word_wrap_column` is\n // zero (word wrap disabled), all grapheme clusters are a wrap opportunity, because none are.\n let mut wrap_opp = self.cursor.wrap_opp;\n let mut wrap_opp_offset = offset;\n let mut wrap_opp_logical_pos_x = logical_pos_x;\n let mut wrap_opp_visual_pos_x = visual_pos_x;\n let mut wrap_opp_column = column;\n\n let mut chunk_iter = Utf8Chars::new(b\"\", 0);\n let mut chunk_range = offset..offset;\n let mut props_next_cluster = ucd_start_of_text_properties();\n\n loop {\n // Have we reached the target already? Stop.\n if offset >= offset_target\n || logical_pos_x >= logical_target_x\n || visual_pos_x >= visual_target_x\n {\n break;\n }\n\n let props_current_cluster = props_next_cluster;\n let mut props_last_char;\n let mut offset_next_cluster;\n let mut state = 0;\n let mut width = 0;\n\n // Since we want to measure the width of the current cluster,\n // by necessity we need to seek to the next cluster.\n // We'll then reuse the offset and properties of the next cluster in\n // the next iteration of the this (outer) loop (`props_next_cluster`).\n loop {\n if !chunk_iter.has_next() {\n cold_path();\n chunk_iter = Utf8Chars::new(self.buffer.read_forward(chunk_range.end), 0);\n chunk_range = chunk_range.end..chunk_range.end + chunk_iter.len();\n }\n\n // Since this loop seeks ahead to the next cluster, and since `chunk_iter`\n // records the offset of the next character after the returned one, we need\n // to save the offset of the previous `chunk_iter` before calling `next()`.\n // Similar applies to the width.\n props_last_char = props_next_cluster;\n offset_next_cluster = chunk_range.start + chunk_iter.offset();\n width += ucd_grapheme_cluster_character_width(props_next_cluster, ambiguous_width())\n as CoordType;\n\n // The `Document::read_forward` interface promises us that it will not split\n // grapheme clusters across chunks. Therefore, we can safely break here.\n let ch = match chunk_iter.next() {\n Some(ch) => ch,\n None => break,\n };\n\n // Get the properties of the next cluster.\n props_next_cluster = ucd_grapheme_cluster_lookup(ch);\n state = ucd_grapheme_cluster_joins(state, props_last_char, props_next_cluster);\n\n // Stop if the next character does not join.\n if ucd_grapheme_cluster_joins_done(state) {\n break;\n }\n }\n\n if offset_next_cluster == offset {\n // No advance and the iterator is empty? End of text reached.\n if chunk_iter.is_empty() {\n break;\n }\n // Ignore the first iteration when processing the start-of-text.\n continue;\n }\n\n // The max. width of a terminal cell is 2.\n width = width.min(2);\n\n // Tabs require special handling because they can have a variable width.\n if props_last_char == ucd_tab_properties() {\n // SAFETY: `self.tab_size` is clamped to >= 1 in `with_tab_size`.\n // This assert ensures that Rust doesn't insert panicking null checks.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1) };\n width = self.tab_size - (column % self.tab_size);\n }\n\n // Hard wrap: Both the logical and visual position advance by one line.\n if props_last_char == ucd_linefeed_properties() {\n cold_path();\n\n wrap_opp = false;\n\n // Don't cross the newline if the target is on this line but we haven't reached it.\n // E.g. if the callers asks for column 100 on a 10 column line,\n // we'll return with the cursor set to column 10.\n if logical_pos_y >= logical_target.y || visual_pos_y >= visual_target.y {\n break;\n }\n\n offset = offset_next_cluster;\n logical_pos_x = 0;\n logical_pos_y += 1;\n visual_pos_x = 0;\n visual_pos_y += 1;\n column = 0;\n\n logical_target_x = Self::calc_target_x(logical_target, logical_pos_y);\n visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n continue;\n }\n\n // Avoid advancing past the visual target, because `width` can be greater than 1.\n if visual_pos_x + width > visual_target_x {\n break;\n }\n\n // Since this code above may need to revert to a previous `wrap_opp_*`,\n // it must be done before advancing / checking for `ucd_line_break_joins`.\n if self.word_wrap_column > 0 && visual_pos_x + width > self.word_wrap_column {\n if !wrap_opp {\n // Otherwise, the lack of a wrap opportunity means that a single word\n // is wider than the word wrap column. We need to force-break the word.\n // This is similar to the above, but \"bar\" gets written at column 0.\n wrap_opp_offset = offset;\n wrap_opp_logical_pos_x = logical_pos_x;\n wrap_opp_visual_pos_x = visual_pos_x;\n wrap_opp_column = column;\n visual_pos_x = 0;\n } else {\n // If we had a wrap opportunity on this line, we can move all\n // characters since then to the next line without stopping this loop:\n // +---------+ +---------+ +---------+\n // | foo| -> | | -> | |\n // | | |foo | |foobar |\n // +---------+ +---------+ +---------+\n // We don't actually move \"foo\", but rather just change where \"bar\" goes.\n // Since this function doesn't copy text, the end result is the same.\n visual_pos_x -= wrap_opp_visual_pos_x;\n }\n\n wrap_opp = false;\n visual_pos_y += 1;\n visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n\n if visual_pos_x == visual_target_x {\n break;\n }\n\n // Imagine the word is \"hello\" and on the \"o\" we notice it wraps.\n // If the target however was the \"e\", then we must revert back to \"h\" and search for it.\n if visual_pos_x > visual_target_x {\n cold_path();\n\n offset = wrap_opp_offset;\n logical_pos_x = wrap_opp_logical_pos_x;\n visual_pos_x = 0;\n column = wrap_opp_column;\n\n chunk_iter.seek(chunk_iter.len());\n chunk_range = offset..offset;\n props_next_cluster = ucd_start_of_text_properties();\n continue;\n }\n }\n\n offset = offset_next_cluster;\n logical_pos_x += 1;\n visual_pos_x += width;\n column += width;\n\n if self.word_wrap_column > 0\n && !ucd_line_break_joins(props_current_cluster, props_next_cluster)\n {\n wrap_opp = true;\n wrap_opp_offset = offset;\n wrap_opp_logical_pos_x = logical_pos_x;\n wrap_opp_visual_pos_x = visual_pos_x;\n wrap_opp_column = column;\n }\n }\n\n // If we're here, we hit our target. Now the only question is:\n // Is the word we're currently on so wide that it will be wrapped further down the document?\n if self.word_wrap_column > 0 {\n if !wrap_opp {\n // If the current laid-out line had no wrap opportunities, it means we had an input\n // such as \"fooooooooooooooooooooo\" at a `word_wrap_column` of e.g. 10. The word\n // didn't fit and the lack of a `wrap_opp` indicates we must force a hard wrap.\n // Thankfully, if we reach this point, that was already done by the code above.\n } else if wrap_opp_logical_pos_x != logical_pos_x && visual_pos_y <= visual_target.y {\n // Imagine the string \"foo bar\" with a word wrap column of 6. If I ask for the cursor at\n // `logical_pos={5,0}`, then the code above exited while reaching the target.\n // At this point, this function doesn't know yet that after the \"b\" there's \"ar\"\n // which causes a word wrap, and causes the final visual position to be {1,1}.\n // This code thus seeks ahead and checks if the current word will wrap or not.\n // Of course we only need to do this if the cursor isn't on a wrap opportunity already.\n\n // The loop below should not modify the target we already found.\n let mut visual_pos_x_lookahead = visual_pos_x;\n\n loop {\n let props_current_cluster = props_next_cluster;\n let mut props_last_char;\n let mut offset_next_cluster;\n let mut state = 0;\n let mut width = 0;\n\n // Since we want to measure the width of the current cluster,\n // by necessity we need to seek to the next cluster.\n // We'll then reuse the offset and properties of the next cluster in\n // the next iteration of the this (outer) loop (`props_next_cluster`).\n loop {\n if !chunk_iter.has_next() {\n cold_path();\n chunk_iter =\n Utf8Chars::new(self.buffer.read_forward(chunk_range.end), 0);\n chunk_range = chunk_range.end..chunk_range.end + chunk_iter.len();\n }\n\n // Since this loop seeks ahead to the next cluster, and since `chunk_iter`\n // records the offset of the next character after the returned one, we need\n // to save the offset of the previous `chunk_iter` before calling `next()`.\n // Similar applies to the width.\n props_last_char = props_next_cluster;\n offset_next_cluster = chunk_range.start + chunk_iter.offset();\n width += ucd_grapheme_cluster_character_width(\n props_next_cluster,\n ambiguous_width(),\n ) as CoordType;\n\n // The `Document::read_forward` interface promises us that it will not split\n // grapheme clusters across chunks. Therefore, we can safely break here.\n let ch = match chunk_iter.next() {\n Some(ch) => ch,\n None => break,\n };\n\n // Get the properties of the next cluster.\n props_next_cluster = ucd_grapheme_cluster_lookup(ch);\n state =\n ucd_grapheme_cluster_joins(state, props_last_char, props_next_cluster);\n\n // Stop if the next character does not join.\n if ucd_grapheme_cluster_joins_done(state) {\n break;\n }\n }\n\n if offset_next_cluster == offset {\n // No advance and the iterator is empty? End of text reached.\n if chunk_iter.is_empty() {\n break;\n }\n // Ignore the first iteration when processing the start-of-text.\n continue;\n }\n\n // The max. width of a terminal cell is 2.\n width = width.min(2);\n\n // Tabs require special handling because they can have a variable width.\n if props_last_char == ucd_tab_properties() {\n // SAFETY: `self.tab_size` is clamped to >= 1 in `with_tab_size`.\n // This assert ensures that Rust doesn't insert panicking null checks.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1) };\n width = self.tab_size - (column % self.tab_size);\n }\n\n // Hard wrap: Both the logical and visual position advance by one line.\n if props_last_char == ucd_linefeed_properties() {\n break;\n }\n\n visual_pos_x_lookahead += width;\n\n if visual_pos_x_lookahead > self.word_wrap_column {\n visual_pos_x -= wrap_opp_visual_pos_x;\n visual_pos_y += 1;\n break;\n } else if !ucd_line_break_joins(props_current_cluster, props_next_cluster) {\n break;\n }\n }\n }\n\n if visual_pos_y > visual_target.y {\n // Imagine the string \"foo bar\" with a word wrap column of 6. If I ask for the cursor at\n // `visual_pos={100,0}`, the code above exited early after wrapping without reaching the target.\n // Since I asked for the last character on the first line, we must wrap back up the last wrap\n offset = wrap_opp_offset;\n logical_pos_x = wrap_opp_logical_pos_x;\n visual_pos_x = wrap_opp_visual_pos_x;\n visual_pos_y = visual_target.y;\n column = wrap_opp_column;\n wrap_opp = true;\n }\n }\n\n self.cursor.offset = offset;\n self.cursor.logical_pos = Point { x: logical_pos_x, y: logical_pos_y };\n self.cursor.visual_pos = Point { x: visual_pos_x, y: visual_pos_y };\n self.cursor.column = column;\n self.cursor.wrap_opp = wrap_opp;\n self.cursor\n }\n\n #[inline]\n fn calc_target_x(target: Point, pos_y: CoordType) -> CoordType {\n match pos_y.cmp(&target.y) {\n std::cmp::Ordering::Less => CoordType::MAX,\n std::cmp::Ordering::Equal => target.x,\n std::cmp::Ordering::Greater => 0,\n }\n }\n}\n\n/// Returns an offset past a newline.\n///\n/// If `offset` is right in front of a newline,\n/// this will return the offset past said newline.\npub fn skip_newline(text: &[u8], mut offset: usize) -> usize {\n if offset >= text.len() {\n return offset;\n }\n if text[offset] == b'\\r' {\n offset += 1;\n }\n if offset >= text.len() {\n return offset;\n }\n if text[offset] == b'\\n' {\n offset += 1;\n }\n offset\n}\n\n/// Strips a trailing newline from the given text.\npub fn strip_newline(mut text: &[u8]) -> &[u8] {\n // Rust generates surprisingly tight assembly for this.\n if text.last() == Some(&b'\\n') {\n text = &text[..text.len() - 1];\n }\n if text.last() == Some(&b'\\r') {\n text = &text[..text.len() - 1];\n }\n text\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n struct ChunkedDoc<'a>(&'a [&'a [u8]]);\n\n impl ReadableDocument for ChunkedDoc<'_> {\n fn read_forward(&self, mut off: usize) -> &[u8] {\n for chunk in self.0 {\n if off < chunk.len() {\n return &chunk[off..];\n }\n off -= chunk.len();\n }\n &[]\n }\n\n fn read_backward(&self, mut off: usize) -> &[u8] {\n for chunk in self.0.iter().rev() {\n if off < chunk.len() {\n return &chunk[..chunk.len() - off];\n }\n off -= chunk.len();\n }\n &[]\n }\n }\n\n #[test]\n fn test_measure_forward_newline_start() {\n let cursor =\n MeasurementConfig::new(&\"foo\\nbar\".as_bytes()).goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 1 },\n column: 0,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_clipped_wide_char() {\n let cursor = MeasurementConfig::new(&\"a😶‍🌫️b\".as_bytes()).goto_visual(Point { x: 2, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 1,\n logical_pos: Point { x: 1, y: 0 },\n visual_pos: Point { x: 1, y: 0 },\n column: 1,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_word_wrap() {\n // |foo␣ |\n // |bar␣ |\n // |baz |\n let text = \"foo bar \\nbaz\".as_bytes();\n\n // Does hitting a logical target wrap the visual position along with the word?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6);\n let cursor = cfg.goto_logical(Point { x: 5, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 5,\n logical_pos: Point { x: 5, y: 0 },\n visual_pos: Point { x: 1, y: 1 },\n column: 5,\n wrap_opp: true,\n }\n );\n\n // Does hitting the visual target within a word reset the hit back to the end of the visual line?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6);\n let cursor = cfg.goto_visual(Point { x: CoordType::MAX, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n // Does hitting the same target but with a non-zero starting position result in the same outcome?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6).with_cursor(Cursor {\n offset: 1,\n logical_pos: Point { x: 1, y: 0 },\n visual_pos: Point { x: 1, y: 0 },\n column: 1,\n wrap_opp: false,\n });\n let cursor = cfg.goto_visual(Point { x: 5, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 5, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 4, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 0, y: 2 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 9,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 2 },\n column: 0,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 5, y: 2 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 12,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 2 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_tabs() {\n let text = \"a\\tb\\tc\".as_bytes();\n let cursor =\n MeasurementConfig::new(&text).with_tab_size(4).goto_visual(Point { x: 4, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 2,\n logical_pos: Point { x: 2, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_chunk_boundaries() {\n let chunks = [\n \"Hello\".as_bytes(),\n \"\\u{1F469}\\u{1F3FB}\".as_bytes(), // 8 bytes, 2 columns\n \"World\".as_bytes(),\n ];\n let doc = ChunkedDoc(&chunks);\n let cursor = MeasurementConfig::new(&doc).goto_visual(Point { x: 5 + 2 + 3, y: 0 });\n assert_eq!(cursor.offset, 5 + 8 + 3);\n assert_eq!(cursor.logical_pos, Point { x: 5 + 1 + 3, y: 0 });\n }\n\n #[test]\n fn test_exact_wrap() {\n // |foo_ |\n // |bar. |\n // |abc |\n let chunks = [\"foo \".as_bytes(), \"bar\".as_bytes(), \".\\n\".as_bytes(), \"abc\".as_bytes()];\n let doc = ChunkedDoc(&chunks);\n let mut cfg = MeasurementConfig::new(&doc).with_word_wrap_column(7);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: 7, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n let beg1 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 4, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n\n let beg2 = cfg.goto_visual(Point { x: 0, y: 2 });\n assert_eq!(\n beg2,\n Cursor {\n offset: 9,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 2 },\n column: 0,\n wrap_opp: false,\n }\n );\n\n let end2 = cfg.goto_visual(Point { x: max, y: 2 });\n assert_eq!(\n end2,\n Cursor {\n offset: 12,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 2 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_force_wrap() {\n // |//_ |\n // |aaaaaaaa|\n // |aaaa |\n let bytes = \"// aaaaaaaaaaaa\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n let max = CoordType::MAX;\n\n // At the end of \"// \" there should be a wrap.\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 3, y: 0 },\n column: 3,\n wrap_opp: true,\n }\n );\n\n // Test if the ambiguous visual position at the wrap location doesn't change the offset.\n let beg0 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 3,\n wrap_opp: false,\n }\n );\n\n // Test if navigating inside the wrapped line doesn't cause further wrapping.\n //\n // This step of the test is important, as it ensures that the following force-wrap works,\n // even if 1 of the 8 \"a\"s was already processed.\n let beg0_off1 = cfg.goto_logical(Point { x: 4, y: 0 });\n assert_eq!(\n beg0_off1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 1, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n // Test if the force-wrap applies at the end of the first 8 \"a\"s.\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 11,\n logical_pos: Point { x: 11, y: 0 },\n visual_pos: Point { x: 8, y: 1 },\n column: 11,\n wrap_opp: true,\n }\n );\n\n // Test if the remaining 4 \"a\"s are properly laid-out.\n let end2 = cfg.goto_visual(Point { x: max, y: 2 });\n assert_eq!(\n end2,\n Cursor {\n offset: 15,\n logical_pos: Point { x: 15, y: 0 },\n visual_pos: Point { x: 4, y: 2 },\n column: 15,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_force_wrap_wide() {\n // These Yijing Hexagram Symbols form no word wrap opportunities.\n let text = \"䷀䷁䷂䷃䷄䷅䷆䷇䷈䷉\";\n let expected = [\"䷀䷁\", \"䷂䷃\", \"䷄䷅\", \"䷆䷇\", \"䷈䷉\"];\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(5);\n\n for (y, &expected) in expected.iter().enumerate() {\n let y = y as CoordType;\n // In order for `goto_visual()` to hit column 0 after a word wrap,\n // it MUST be able to go back by 1 grapheme, which is what this tests.\n let beg = cfg.goto_visual(Point { x: 0, y });\n let end = cfg.goto_visual(Point { x: 5, y });\n let actual = &text[beg.offset..end.offset];\n assert_eq!(actual, expected);\n }\n }\n\n // Similar to the `test_force_wrap` test, but here we vertically descend\n // down the document without ever touching the first or last column.\n // I found that this finds curious bugs at times.\n #[test]\n fn test_force_wrap_column() {\n // |//_ |\n // |aaaaaaaa|\n // |aaaa |\n let bytes = \"// aaaaaaaaaaaa\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n\n // At the end of \"// \" there should be a wrap.\n let end0 = cfg.goto_visual(Point { x: CoordType::MAX, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 3, y: 0 },\n column: 3,\n wrap_opp: true,\n }\n );\n\n let mid1 = cfg.goto_visual(Point { x: end0.visual_pos.x, y: 1 });\n assert_eq!(\n mid1,\n Cursor {\n offset: 6,\n logical_pos: Point { x: 6, y: 0 },\n visual_pos: Point { x: 3, y: 1 },\n column: 6,\n wrap_opp: false,\n }\n );\n\n let mid2 = cfg.goto_visual(Point { x: end0.visual_pos.x, y: 2 });\n assert_eq!(\n mid2,\n Cursor {\n offset: 14,\n logical_pos: Point { x: 14, y: 0 },\n visual_pos: Point { x: 3, y: 2 },\n column: 14,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_any_wrap() {\n // |//_-----|\n // |------- |\n let bytes = \"// ------------\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 8, y: 0 },\n column: 8,\n wrap_opp: true,\n }\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 15,\n logical_pos: Point { x: 15, y: 0 },\n visual_pos: Point { x: 7, y: 1 },\n column: 15,\n wrap_opp: true,\n }\n );\n }\n\n #[test]\n fn test_any_wrap_wide() {\n // These Japanese characters form word wrap opportunity between each character.\n let text = \"零一二三四五六七八九\";\n let expected = [\"零一\", \"二三\", \"四五\", \"六七\", \"八九\"];\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(5);\n\n for (y, &expected) in expected.iter().enumerate() {\n let y = y as CoordType;\n // In order for `goto_visual()` to hit column 0 after a word wrap,\n // it MUST be able to go back by 1 grapheme, which is what this tests.\n let beg = cfg.goto_visual(Point { x: 0, y });\n let end = cfg.goto_visual(Point { x: 5, y });\n let actual = &text[beg.offset..end.offset];\n assert_eq!(actual, expected);\n }\n }\n\n #[test]\n fn test_wrap_tab() {\n // |foo_ | <- 1 space\n // |____b | <- 1 tab, 1 space\n let text = \"foo \\t b\";\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8).with_tab_size(4);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n },\n );\n\n let beg1 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n },\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 7,\n logical_pos: Point { x: 7, y: 0 },\n visual_pos: Point { x: 6, y: 1 },\n column: 10,\n wrap_opp: true,\n },\n );\n }\n\n #[test]\n fn test_crlf() {\n let text = \"a\\r\\nbcd\\r\\ne\".as_bytes();\n let cursor = MeasurementConfig::new(&text).goto_visual(Point { x: CoordType::MAX, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 6,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 1 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_wrapped_cursor_can_seek_backward() {\n let bytes = \"hello world\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(10);\n\n // When the word wrap at column 10 hits, the cursor will be at the end of the word \"world\" (between l and d).\n // This tests if the algorithm is capable of going back to the start of the word and find the actual target.\n let cursor = cfg.goto_visual(Point { x: 2, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 2, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_strip_newline() {\n assert_eq!(strip_newline(b\"hello\\n\"), b\"hello\");\n assert_eq!(strip_newline(b\"hello\\r\\n\"), b\"hello\");\n assert_eq!(strip_newline(b\"hello\"), b\"hello\");\n }\n}\n"], ["/edit/src/sys/unix.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Unix-specific platform code.\n//!\n//! Read the `windows` module for reference.\n//! TODO: This reminds me that the sys API should probably be a trait.\n\nuse std::ffi::{CStr, c_char, c_int, c_void};\nuse std::fs::File;\nuse std::mem::{self, ManuallyDrop, MaybeUninit};\nuse std::os::fd::{AsRawFd as _, FromRawFd as _};\nuse std::path::Path;\nuse std::ptr::{self, NonNull, null_mut};\nuse std::{thread, time};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::helpers::*;\nuse crate::{apperr, arena_format};\n\n#[cfg(target_os = \"netbsd\")]\nconst fn desired_mprotect(flags: c_int) -> c_int {\n // NetBSD allows an mmap(2) caller to specify what protection flags they\n // will use later via mprotect. It does not allow a caller to move from\n // PROT_NONE to PROT_READ | PROT_WRITE.\n //\n // see PROT_MPROTECT in man 2 mmap\n flags << 3\n}\n\n#[cfg(not(target_os = \"netbsd\"))]\nconst fn desired_mprotect(_: c_int) -> c_int {\n libc::PROT_NONE\n}\n\nstruct State {\n stdin: libc::c_int,\n stdin_flags: libc::c_int,\n stdout: libc::c_int,\n stdout_initial_termios: Option,\n inject_resize: bool,\n // Buffer for incomplete UTF-8 sequences (max 4 bytes needed)\n utf8_buf: [u8; 4],\n utf8_len: usize,\n}\n\nstatic mut STATE: State = State {\n stdin: libc::STDIN_FILENO,\n stdin_flags: 0,\n stdout: libc::STDOUT_FILENO,\n stdout_initial_termios: None,\n inject_resize: false,\n utf8_buf: [0; 4],\n utf8_len: 0,\n};\n\nextern \"C\" fn sigwinch_handler(_: libc::c_int) {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\npub fn init() -> Deinit {\n Deinit\n}\n\npub fn switch_modes() -> apperr::Result<()> {\n unsafe {\n // Reopen stdin if it's redirected (= piped input).\n if libc::isatty(STATE.stdin) == 0 {\n STATE.stdin = check_int_return(libc::open(c\"/dev/tty\".as_ptr(), libc::O_RDONLY))?;\n }\n\n // Store the stdin flags so we can more easily toggle `O_NONBLOCK` later on.\n STATE.stdin_flags = check_int_return(libc::fcntl(STATE.stdin, libc::F_GETFL))?;\n\n // Set STATE.inject_resize to true whenever we get a SIGWINCH.\n let mut sigwinch_action: libc::sigaction = mem::zeroed();\n sigwinch_action.sa_sigaction = sigwinch_handler as libc::sighandler_t;\n check_int_return(libc::sigaction(libc::SIGWINCH, &sigwinch_action, null_mut()))?;\n\n // Get the original terminal modes so we can disable raw mode on exit.\n let mut termios = MaybeUninit::::uninit();\n check_int_return(libc::tcgetattr(STATE.stdout, termios.as_mut_ptr()))?;\n let mut termios = termios.assume_init();\n STATE.stdout_initial_termios = Some(termios);\n\n termios.c_iflag &= !(\n // When neither IGNBRK...\n libc::IGNBRK\n // ...nor BRKINT are set, a BREAK reads as a null byte ('\\0'), ...\n | libc::BRKINT\n // ...except when PARMRK is set, in which case it reads as the sequence \\377 \\0 \\0.\n | libc::PARMRK\n // Disable input parity checking.\n | libc::INPCK\n // Disable stripping of eighth bit.\n | libc::ISTRIP\n // Disable mapping of NL to CR on input.\n | libc::INLCR\n // Disable ignoring CR on input.\n | libc::IGNCR\n // Disable mapping of CR to NL on input.\n | libc::ICRNL\n // Disable software flow control.\n | libc::IXON\n );\n // Disable output processing.\n termios.c_oflag &= !libc::OPOST;\n termios.c_cflag &= !(\n // Reset character size mask.\n libc::CSIZE\n // Disable parity generation.\n | libc::PARENB\n );\n // Set character size back to 8 bits.\n termios.c_cflag |= libc::CS8;\n termios.c_lflag &= !(\n // Disable signal generation (SIGINT, SIGTSTP, SIGQUIT).\n libc::ISIG\n // Disable canonical mode (line buffering).\n | libc::ICANON\n // Disable echoing of input characters.\n | libc::ECHO\n // Disable echoing of NL.\n | libc::ECHONL\n // Disable extended input processing (e.g. Ctrl-V).\n | libc::IEXTEN\n );\n\n // Set the terminal to raw mode.\n termios.c_lflag &= !(libc::ICANON | libc::ECHO);\n check_int_return(libc::tcsetattr(STATE.stdout, libc::TCSANOW, &termios))?;\n\n Ok(())\n }\n}\n\npub struct Deinit;\n\nimpl Drop for Deinit {\n fn drop(&mut self) {\n unsafe {\n #[allow(static_mut_refs)]\n if let Some(termios) = STATE.stdout_initial_termios.take() {\n // Restore the original terminal modes.\n libc::tcsetattr(STATE.stdout, libc::TCSANOW, &termios);\n }\n }\n }\n}\n\npub fn inject_window_size_into_stdin() {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\nfn get_window_size() -> (u16, u16) {\n let mut winsz: libc::winsize = unsafe { mem::zeroed() };\n\n for attempt in 1.. {\n let ret = unsafe { libc::ioctl(STATE.stdout, libc::TIOCGWINSZ, &raw mut winsz) };\n if ret == -1 || (winsz.ws_col != 0 && winsz.ws_row != 0) {\n break;\n }\n\n if attempt == 10 {\n winsz.ws_col = 80;\n winsz.ws_row = 24;\n break;\n }\n\n // Some terminals are bad emulators and don't report TIOCGWINSZ immediately.\n thread::sleep(time::Duration::from_millis(10 * attempt));\n }\n\n (winsz.ws_col, winsz.ws_row)\n}\n\n/// Reads from stdin.\n///\n/// Returns `None` if there was an error reading from stdin.\n/// Returns `Some(\"\")` if the given timeout was reached.\n/// Otherwise, it returns the read, non-empty string.\npub fn read_stdin(arena: &Arena, mut timeout: time::Duration) -> Option> {\n unsafe {\n if STATE.inject_resize {\n timeout = time::Duration::ZERO;\n }\n\n let read_poll = timeout != time::Duration::MAX;\n let mut buf = Vec::new_in(arena);\n\n // We don't know if the input is valid UTF8, so we first use a Vec and then\n // later turn it into UTF8 using `from_utf8_lossy_owned`.\n // It is important that we allocate the buffer with an explicit capacity,\n // because we later use `spare_capacity_mut` to access it.\n buf.reserve(4 * KIBI);\n\n // We got some leftover broken UTF8 from a previous read? Prepend it.\n if STATE.utf8_len != 0 {\n buf.extend_from_slice(&STATE.utf8_buf[..STATE.utf8_len]);\n STATE.utf8_len = 0;\n }\n\n loop {\n if timeout != time::Duration::MAX {\n let beg = time::Instant::now();\n\n let mut pollfd = libc::pollfd { fd: STATE.stdin, events: libc::POLLIN, revents: 0 };\n let ret;\n #[cfg(target_os = \"linux\")]\n {\n let ts = libc::timespec {\n tv_sec: timeout.as_secs() as libc::time_t,\n tv_nsec: timeout.subsec_nanos() as libc::c_long,\n };\n ret = libc::ppoll(&mut pollfd, 1, &ts, ptr::null());\n }\n #[cfg(not(target_os = \"linux\"))]\n {\n ret = libc::poll(&mut pollfd, 1, timeout.as_millis() as libc::c_int);\n }\n if ret < 0 {\n return None; // Error? Let's assume it's an EOF.\n }\n if ret == 0 {\n break; // Timeout? We can stop reading.\n }\n\n timeout = timeout.saturating_sub(beg.elapsed());\n };\n\n // If we're asked for a non-blocking read we need\n // to manipulate `O_NONBLOCK` and vice versa.\n set_tty_nonblocking(read_poll);\n\n // Read from stdin.\n let spare = buf.spare_capacity_mut();\n let ret = libc::read(STATE.stdin, spare.as_mut_ptr() as *mut _, spare.len());\n if ret > 0 {\n buf.set_len(buf.len() + ret as usize);\n break;\n }\n if ret == 0 {\n return None; // EOF\n }\n if ret < 0 {\n match errno() {\n libc::EINTR if STATE.inject_resize => break,\n libc::EAGAIN if timeout == time::Duration::ZERO => break,\n libc::EINTR | libc::EAGAIN => {}\n _ => return None,\n }\n }\n }\n\n if !buf.is_empty() {\n // We only need to check the last 3 bytes for UTF-8 continuation bytes,\n // because we should be able to assume that any 4 byte sequence is complete.\n let lim = buf.len().saturating_sub(3);\n let mut off = buf.len() - 1;\n\n // Find the start of the last potentially incomplete UTF-8 sequence.\n while off > lim && buf[off] & 0b1100_0000 == 0b1000_0000 {\n off -= 1;\n }\n\n let seq_len = match buf[off] {\n b if b & 0b1000_0000 == 0 => 1,\n b if b & 0b1110_0000 == 0b1100_0000 => 2,\n b if b & 0b1111_0000 == 0b1110_0000 => 3,\n b if b & 0b1111_1000 == 0b1111_0000 => 4,\n // If the lead byte we found isn't actually one, we don't cache it.\n // `from_utf8_lossy_owned` will replace it with U+FFFD.\n _ => 0,\n };\n\n // Cache incomplete sequence if any.\n if off + seq_len > buf.len() {\n STATE.utf8_len = buf.len() - off;\n STATE.utf8_buf[..STATE.utf8_len].copy_from_slice(&buf[off..]);\n buf.truncate(off);\n }\n }\n\n let mut result = ArenaString::from_utf8_lossy_owned(buf);\n\n // We received a SIGWINCH? Add a fake window size sequence for our input parser.\n // I prepend it so that on startup, the TUI system gets first initialized with a size.\n if STATE.inject_resize {\n STATE.inject_resize = false;\n let (w, h) = get_window_size();\n if w > 0 && h > 0 {\n let scratch = scratch_arena(Some(arena));\n let seq = arena_format!(&scratch, \"\\x1b[8;{h};{w}t\");\n result.replace_range(0..0, &seq);\n }\n }\n\n result.shrink_to_fit();\n Some(result)\n }\n}\n\npub fn write_stdout(text: &str) {\n if text.is_empty() {\n return;\n }\n\n // If we don't set the TTY to blocking mode,\n // the write will potentially fail with EAGAIN.\n set_tty_nonblocking(false);\n\n let buf = text.as_bytes();\n let mut written = 0;\n\n while written < buf.len() {\n let w = &buf[written..];\n let w = &buf[..w.len().min(GIBI)];\n let n = unsafe { libc::write(STATE.stdout, w.as_ptr() as *const _, w.len()) };\n\n if n >= 0 {\n written += n as usize;\n continue;\n }\n\n let err = errno();\n if err != libc::EINTR {\n return;\n }\n }\n}\n\n/// Sets/Resets `O_NONBLOCK` on the TTY handle.\n///\n/// Note that setting this flag applies to both stdin and stdout, because the\n/// TTY is a bidirectional device and both handles refer to the same thing.\nfn set_tty_nonblocking(nonblock: bool) {\n unsafe {\n let is_nonblock = (STATE.stdin_flags & libc::O_NONBLOCK) != 0;\n if is_nonblock != nonblock {\n STATE.stdin_flags ^= libc::O_NONBLOCK;\n let _ = libc::fcntl(STATE.stdin, libc::F_SETFL, STATE.stdin_flags);\n }\n }\n}\n\npub fn open_stdin_if_redirected() -> Option {\n unsafe {\n // Did we reopen stdin during `init()`?\n if STATE.stdin != libc::STDIN_FILENO {\n Some(File::from_raw_fd(libc::STDIN_FILENO))\n } else {\n None\n }\n }\n}\n\n#[derive(Clone, PartialEq, Eq)]\npub struct FileId {\n st_dev: libc::dev_t,\n st_ino: libc::ino_t,\n}\n\n/// Returns a unique identifier for the given file by handle or path.\npub fn file_id(file: Option<&File>, path: &Path) -> apperr::Result {\n let file = match file {\n Some(f) => f,\n None => &File::open(path)?,\n };\n\n unsafe {\n let mut stat = MaybeUninit::::uninit();\n check_int_return(libc::fstat(file.as_raw_fd(), stat.as_mut_ptr()))?;\n let stat = stat.assume_init();\n Ok(FileId { st_dev: stat.st_dev, st_ino: stat.st_ino })\n }\n}\n\n/// Reserves a virtual memory region of the given size.\n/// To commit the memory, use `virtual_commit`.\n/// To release the memory, use `virtual_release`.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Don't forget to release the memory when you're done with it or you'll leak it.\npub unsafe fn virtual_reserve(size: usize) -> apperr::Result> {\n unsafe {\n let ptr = libc::mmap(\n null_mut(),\n size,\n desired_mprotect(libc::PROT_READ | libc::PROT_WRITE),\n libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,\n -1,\n 0,\n );\n if ptr.is_null() || ptr::eq(ptr, libc::MAP_FAILED) {\n Err(errno_to_apperr(libc::ENOMEM))\n } else {\n Ok(NonNull::new_unchecked(ptr as *mut u8))\n }\n }\n}\n\n/// Releases a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from `virtual_reserve`.\npub unsafe fn virtual_release(base: NonNull, size: usize) {\n unsafe {\n libc::munmap(base.cast().as_ptr(), size);\n }\n}\n\n/// Commits a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from `virtual_reserve`\n/// and to pass a size less than or equal to the size passed to `virtual_reserve`.\npub unsafe fn virtual_commit(base: NonNull, size: usize) -> apperr::Result<()> {\n unsafe {\n let status = libc::mprotect(base.cast().as_ptr(), size, libc::PROT_READ | libc::PROT_WRITE);\n if status != 0 { Err(errno_to_apperr(libc::ENOMEM)) } else { Ok(()) }\n }\n}\n\nunsafe fn load_library(name: *const c_char) -> apperr::Result> {\n unsafe {\n NonNull::new(libc::dlopen(name, libc::RTLD_LAZY))\n .ok_or_else(|| errno_to_apperr(libc::ENOENT))\n }\n}\n\n/// Loads a function from a dynamic library.\n///\n/// # Safety\n///\n/// This function is highly unsafe as it requires you to know the exact type\n/// of the function you're loading. No type checks whatsoever are performed.\n//\n// It'd be nice to constrain T to std::marker::FnPtr, but that's unstable.\npub unsafe fn get_proc_address(\n handle: NonNull,\n name: *const c_char,\n) -> apperr::Result {\n unsafe {\n let sym = libc::dlsym(handle.as_ptr(), name);\n if sym.is_null() {\n Err(errno_to_apperr(libc::ENOENT))\n } else {\n Ok(mem::transmute_copy(&sym))\n }\n }\n}\n\npub struct LibIcu {\n pub libicuuc: NonNull,\n pub libicui18n: NonNull,\n}\n\npub fn load_icu() -> apperr::Result {\n const fn const_str_eq(a: &str, b: &str) -> bool {\n let a = a.as_bytes();\n let b = b.as_bytes();\n let mut i = 0;\n\n loop {\n if i >= a.len() || i >= b.len() {\n return a.len() == b.len();\n }\n if a[i] != b[i] {\n return false;\n }\n i += 1;\n }\n }\n\n const LIBICUUC: &str = concat!(env!(\"EDIT_CFG_ICUUC_SONAME\"), \"\\0\");\n const LIBICUI18N: &str = concat!(env!(\"EDIT_CFG_ICUI18N_SONAME\"), \"\\0\");\n\n if const { const_str_eq(LIBICUUC, LIBICUI18N) } {\n let icu = unsafe { load_library(LIBICUUC.as_ptr() as *const _)? };\n Ok(LibIcu { libicuuc: icu, libicui18n: icu })\n } else {\n let libicuuc = unsafe { load_library(LIBICUUC.as_ptr() as *const _)? };\n let libicui18n = unsafe { load_library(LIBICUI18N.as_ptr() as *const _)? };\n Ok(LibIcu { libicuuc, libicui18n })\n }\n}\n/// ICU, by default, adds the major version as a suffix to each exported symbol.\n/// They also recommend to disable this for system-level installations (`runConfigureICU Linux --disable-renaming`),\n/// but I found that many (most?) Linux distributions don't do this for some reason.\n/// This function returns the suffix, if any.\n#[cfg(edit_icu_renaming_auto_detect)]\npub fn icu_detect_renaming_suffix(arena: &Arena, handle: NonNull) -> ArenaString<'_> {\n unsafe {\n type T = *const c_void;\n\n let mut res = ArenaString::new_in(arena);\n\n // Check if the ICU library is using unversioned symbols.\n // Return an empty suffix in that case.\n if get_proc_address::(handle, c\"u_errorName\".as_ptr()).is_ok() {\n return res;\n }\n\n // In the versions (63-76) and distributions (Arch/Debian) I tested,\n // this symbol seems to be always present. This allows us to call `dladdr`.\n // It's the `UCaseMap::~UCaseMap()` destructor which for some reason isn't\n // in a namespace. Thank you ICU maintainers for this oversight.\n let proc = match get_proc_address::(handle, c\"_ZN8UCaseMapD1Ev\".as_ptr()) {\n Ok(proc) => proc,\n Err(_) => return res,\n };\n\n // `dladdr` is specific to GNU's libc unfortunately.\n let mut info: libc::Dl_info = mem::zeroed();\n let ret = libc::dladdr(proc, &mut info);\n if ret == 0 {\n return res;\n }\n\n // The library path is in `info.dli_fname`.\n let path = match CStr::from_ptr(info.dli_fname).to_str() {\n Ok(name) => name,\n Err(_) => return res,\n };\n\n let path = match std::fs::read_link(path) {\n Ok(path) => path,\n Err(_) => path.into(),\n };\n\n // I'm going to assume it's something like \"libicuuc.so.76.1\".\n let path = path.into_os_string();\n let path = path.to_string_lossy();\n let suffix_start = match path.rfind(\".so.\") {\n Some(pos) => pos + 4,\n None => return res,\n };\n let version = &path[suffix_start..];\n let version_end = version.find('.').unwrap_or(version.len());\n let version = &version[..version_end];\n\n res.push('_');\n res.push_str(version);\n res\n }\n}\n\n#[cfg(edit_icu_renaming_auto_detect)]\n#[allow(clippy::not_unsafe_ptr_arg_deref)]\npub fn icu_add_renaming_suffix<'a, 'b, 'r>(\n arena: &'a Arena,\n name: *const c_char,\n suffix: &str,\n) -> *const c_char\nwhere\n 'a: 'r,\n 'b: 'r,\n{\n if suffix.is_empty() {\n name\n } else {\n // SAFETY: In this particular case we know that the string\n // is valid UTF-8, because it comes from icu.rs.\n let name = unsafe { CStr::from_ptr(name) };\n let name = unsafe { name.to_str().unwrap_unchecked() };\n\n let mut res = ManuallyDrop::new(ArenaString::new_in(arena));\n res.reserve(name.len() + suffix.len() + 1);\n res.push_str(name);\n res.push_str(suffix);\n res.push('\\0');\n res.as_ptr() as *const c_char\n }\n}\n\npub fn preferred_languages(arena: &Arena) -> Vec, &Arena> {\n let mut locales = Vec::new_in(arena);\n\n for key in [\"LANGUAGE\", \"LC_ALL\", \"LANG\"] {\n if let Ok(val) = std::env::var(key)\n && !val.is_empty()\n {\n locales.extend(val.split(':').filter(|s| !s.is_empty()).map(|s| {\n // Replace all underscores with dashes,\n // because the localization code expects pt-br, not pt_BR.\n let mut res = Vec::new_in(arena);\n res.extend(s.as_bytes().iter().map(|&b| if b == b'_' { b'-' } else { b }));\n unsafe { ArenaString::from_utf8_unchecked(res) }\n }));\n break;\n }\n }\n\n locales\n}\n\n#[inline]\nfn errno() -> i32 {\n // Under `-O -Copt-level=s` the 1.87 compiler fails to fully inline and\n // remove the raw_os_error() call. This leaves us with the drop() call.\n // ManuallyDrop fixes that and results in a direct `std::sys::os::errno` call.\n ManuallyDrop::new(std::io::Error::last_os_error()).raw_os_error().unwrap_or(0)\n}\n\n#[inline]\npub(crate) fn io_error_to_apperr(err: std::io::Error) -> apperr::Error {\n errno_to_apperr(err.raw_os_error().unwrap_or(0))\n}\n\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n write!(f, \"Error {code}\")?;\n\n unsafe {\n let ptr = libc::strerror(code as i32);\n if !ptr.is_null() {\n let msg = CStr::from_ptr(ptr).to_string_lossy();\n write!(f, \": {msg}\")?;\n }\n }\n\n Ok(())\n}\n\npub fn apperr_is_not_found(err: apperr::Error) -> bool {\n err == errno_to_apperr(libc::ENOENT)\n}\n\nconst fn errno_to_apperr(no: c_int) -> apperr::Error {\n apperr::Error::new_sys(if no < 0 { 0 } else { no as u32 })\n}\n\nfn check_int_return(ret: libc::c_int) -> apperr::Result {\n if ret < 0 { Err(errno_to_apperr(errno())) } else { Ok(ret) }\n}\n"], ["/edit/src/sys/windows.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ffi::{OsString, c_char, c_void};\nuse std::fmt::Write as _;\nuse std::fs::{self, File};\nuse std::mem::MaybeUninit;\nuse std::os::windows::io::{AsRawHandle as _, FromRawHandle};\nuse std::path::{Path, PathBuf};\nuse std::ptr::{self, NonNull, null, null_mut};\nuse std::{mem, time};\n\nuse windows_sys::Win32::Storage::FileSystem;\nuse windows_sys::Win32::System::Diagnostics::Debug;\nuse windows_sys::Win32::System::{Console, IO, LibraryLoader, Memory, Threading};\nuse windows_sys::Win32::{Foundation, Globalization};\nuse windows_sys::w;\n\nuse crate::apperr;\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::helpers::*;\n\nmacro_rules! w_env {\n ($s:literal) => {{\n const INPUT: &[u8] = env!($s).as_bytes();\n const OUTPUT_LEN: usize = windows_sys::core::utf16_len(INPUT) + 1;\n const OUTPUT: &[u16; OUTPUT_LEN] = {\n let mut buffer = [0; OUTPUT_LEN];\n let mut input_pos = 0;\n let mut output_pos = 0;\n while let Some((mut code_point, new_pos)) =\n windows_sys::core::decode_utf8_char(INPUT, input_pos)\n {\n input_pos = new_pos;\n if code_point <= 0xffff {\n buffer[output_pos] = code_point as u16;\n output_pos += 1;\n } else {\n code_point -= 0x10000;\n buffer[output_pos] = 0xd800 + (code_point >> 10) as u16;\n output_pos += 1;\n buffer[output_pos] = 0xdc00 + (code_point & 0x3ff) as u16;\n output_pos += 1;\n }\n }\n &{ buffer }\n };\n OUTPUT.as_ptr()\n }};\n}\n\ntype ReadConsoleInputExW = unsafe extern \"system\" fn(\n h_console_input: Foundation::HANDLE,\n lp_buffer: *mut Console::INPUT_RECORD,\n n_length: u32,\n lp_number_of_events_read: *mut u32,\n w_flags: u16,\n) -> Foundation::BOOL;\n\nunsafe extern \"system\" fn read_console_input_ex_placeholder(\n _: Foundation::HANDLE,\n _: *mut Console::INPUT_RECORD,\n _: u32,\n _: *mut u32,\n _: u16,\n) -> Foundation::BOOL {\n panic!();\n}\n\nconst CONSOLE_READ_NOWAIT: u16 = 0x0002;\n\nconst INVALID_CONSOLE_MODE: u32 = u32::MAX;\n\nstruct State {\n read_console_input_ex: ReadConsoleInputExW,\n stdin: Foundation::HANDLE,\n stdout: Foundation::HANDLE,\n stdin_cp_old: u32,\n stdout_cp_old: u32,\n stdin_mode_old: u32,\n stdout_mode_old: u32,\n leading_surrogate: u16,\n inject_resize: bool,\n wants_exit: bool,\n}\n\nstatic mut STATE: State = State {\n read_console_input_ex: read_console_input_ex_placeholder,\n stdin: null_mut(),\n stdout: null_mut(),\n stdin_cp_old: 0,\n stdout_cp_old: 0,\n stdin_mode_old: INVALID_CONSOLE_MODE,\n stdout_mode_old: INVALID_CONSOLE_MODE,\n leading_surrogate: 0,\n inject_resize: false,\n wants_exit: false,\n};\n\nextern \"system\" fn console_ctrl_handler(_ctrl_type: u32) -> Foundation::BOOL {\n unsafe {\n STATE.wants_exit = true;\n IO::CancelIoEx(STATE.stdin, null());\n }\n 1\n}\n\n/// Initializes the platform-specific state.\npub fn init() -> Deinit {\n unsafe {\n // Get the stdin and stdout handles first, so that if this function fails,\n // we at least got something to use for `write_stdout`.\n STATE.stdin = Console::GetStdHandle(Console::STD_INPUT_HANDLE);\n STATE.stdout = Console::GetStdHandle(Console::STD_OUTPUT_HANDLE);\n\n Deinit\n }\n}\n\n/// Switches the terminal into raw mode, etc.\npub fn switch_modes() -> apperr::Result<()> {\n unsafe {\n // `kernel32.dll` doesn't exist on OneCore variants of Windows.\n // NOTE: `kernelbase.dll` is NOT a stable API to rely on. In our case it's the best option though.\n //\n // This is written as two nested `match` statements so that we can return the error from the first\n // `load_read_func` call if it fails. The kernel32.dll lookup may contain some valid information,\n // while the kernelbase.dll lookup may not, since it's not a stable API.\n unsafe fn load_read_func(module: *const u16) -> apperr::Result {\n unsafe {\n get_module(module)\n .and_then(|m| get_proc_address(m, c\"ReadConsoleInputExW\".as_ptr()))\n }\n }\n STATE.read_console_input_ex = match load_read_func(w!(\"kernel32.dll\")) {\n Ok(func) => func,\n Err(err) => match load_read_func(w!(\"kernelbase.dll\")) {\n Ok(func) => func,\n Err(_) => return Err(err),\n },\n };\n\n // Reopen stdin if it's redirected (= piped input).\n if ptr::eq(STATE.stdin, Foundation::INVALID_HANDLE_VALUE)\n || !matches!(FileSystem::GetFileType(STATE.stdin), FileSystem::FILE_TYPE_CHAR)\n {\n STATE.stdin = FileSystem::CreateFileW(\n w!(\"CONIN$\"),\n Foundation::GENERIC_READ | Foundation::GENERIC_WRITE,\n FileSystem::FILE_SHARE_READ | FileSystem::FILE_SHARE_WRITE,\n null_mut(),\n FileSystem::OPEN_EXISTING,\n 0,\n null_mut(),\n );\n }\n if ptr::eq(STATE.stdin, Foundation::INVALID_HANDLE_VALUE)\n || ptr::eq(STATE.stdout, Foundation::INVALID_HANDLE_VALUE)\n {\n return Err(get_last_error());\n }\n\n check_bool_return(Console::SetConsoleCtrlHandler(Some(console_ctrl_handler), 1))?;\n\n STATE.stdin_cp_old = Console::GetConsoleCP();\n STATE.stdout_cp_old = Console::GetConsoleOutputCP();\n check_bool_return(Console::GetConsoleMode(STATE.stdin, &raw mut STATE.stdin_mode_old))?;\n check_bool_return(Console::GetConsoleMode(STATE.stdout, &raw mut STATE.stdout_mode_old))?;\n\n check_bool_return(Console::SetConsoleCP(Globalization::CP_UTF8))?;\n check_bool_return(Console::SetConsoleOutputCP(Globalization::CP_UTF8))?;\n check_bool_return(Console::SetConsoleMode(\n STATE.stdin,\n Console::ENABLE_WINDOW_INPUT\n | Console::ENABLE_EXTENDED_FLAGS\n | Console::ENABLE_VIRTUAL_TERMINAL_INPUT,\n ))?;\n check_bool_return(Console::SetConsoleMode(\n STATE.stdout,\n Console::ENABLE_PROCESSED_OUTPUT\n | Console::ENABLE_WRAP_AT_EOL_OUTPUT\n | Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING\n | Console::DISABLE_NEWLINE_AUTO_RETURN,\n ))?;\n\n Ok(())\n }\n}\n\npub struct Deinit;\n\nimpl Drop for Deinit {\n fn drop(&mut self) {\n unsafe {\n if STATE.stdin_cp_old != 0 {\n Console::SetConsoleCP(STATE.stdin_cp_old);\n STATE.stdin_cp_old = 0;\n }\n if STATE.stdout_cp_old != 0 {\n Console::SetConsoleOutputCP(STATE.stdout_cp_old);\n STATE.stdout_cp_old = 0;\n }\n if STATE.stdin_mode_old != INVALID_CONSOLE_MODE {\n Console::SetConsoleMode(STATE.stdin, STATE.stdin_mode_old);\n STATE.stdin_mode_old = INVALID_CONSOLE_MODE;\n }\n if STATE.stdout_mode_old != INVALID_CONSOLE_MODE {\n Console::SetConsoleMode(STATE.stdout, STATE.stdout_mode_old);\n STATE.stdout_mode_old = INVALID_CONSOLE_MODE;\n }\n }\n }\n}\n\n/// During startup we need to get the window size from the terminal.\n/// Because I didn't want to type a bunch of code, this function tells\n/// [`read_stdin`] to inject a fake sequence, which gets picked up by\n/// the input parser and provided to the TUI code.\npub fn inject_window_size_into_stdin() {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\nfn get_console_size() -> Option {\n unsafe {\n let mut info: Console::CONSOLE_SCREEN_BUFFER_INFOEX = mem::zeroed();\n info.cbSize = mem::size_of::() as u32;\n if Console::GetConsoleScreenBufferInfoEx(STATE.stdout, &mut info) == 0 {\n return None;\n }\n\n let w = (info.srWindow.Right - info.srWindow.Left + 1).max(1) as CoordType;\n let h = (info.srWindow.Bottom - info.srWindow.Top + 1).max(1) as CoordType;\n Some(Size { width: w, height: h })\n }\n}\n\n/// Reads from stdin.\n///\n/// # Returns\n///\n/// * `None` if there was an error reading from stdin.\n/// * `Some(\"\")` if the given timeout was reached.\n/// * Otherwise, it returns the read, non-empty string.\npub fn read_stdin(arena: &Arena, mut timeout: time::Duration) -> Option> {\n let scratch = scratch_arena(Some(arena));\n\n // On startup we're asked to inject a window size so that the UI system can layout the elements.\n // --> Inject a fake sequence for our input parser.\n let mut resize_event = None;\n if unsafe { STATE.inject_resize } {\n unsafe { STATE.inject_resize = false };\n timeout = time::Duration::ZERO;\n resize_event = get_console_size();\n }\n\n let read_poll = timeout != time::Duration::MAX; // there is a timeout -> don't block in read()\n let input_buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut input_buf_cap = input_buf.len();\n let utf16_buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut utf16_buf_len = 0;\n\n // If there was a leftover leading surrogate from the last read, we prepend it to the buffer.\n if unsafe { STATE.leading_surrogate } != 0 {\n utf16_buf[0] = MaybeUninit::new(unsafe { STATE.leading_surrogate });\n utf16_buf_len = 1;\n input_buf_cap -= 1;\n unsafe { STATE.leading_surrogate = 0 };\n }\n\n // Read until there's either a timeout or we have something to process.\n loop {\n if timeout != time::Duration::MAX {\n let beg = time::Instant::now();\n\n match unsafe { Threading::WaitForSingleObject(STATE.stdin, timeout.as_millis() as u32) }\n {\n // Ready to read? Continue with reading below.\n Foundation::WAIT_OBJECT_0 => {}\n // Timeout? Skip reading entirely.\n Foundation::WAIT_TIMEOUT => break,\n // Error? Tell the caller stdin is broken.\n _ => return None,\n }\n\n timeout = timeout.saturating_sub(beg.elapsed());\n }\n\n // Read from stdin.\n let input = unsafe {\n // If we had a `inject_resize`, we don't want to block indefinitely for other pending input on startup,\n // but are still interested in any other pending input that may be waiting for us.\n let flags = if read_poll { CONSOLE_READ_NOWAIT } else { 0 };\n let mut read = 0;\n let ok = (STATE.read_console_input_ex)(\n STATE.stdin,\n input_buf[0].as_mut_ptr(),\n input_buf_cap as u32,\n &mut read,\n flags,\n );\n if ok == 0 || STATE.wants_exit {\n return None;\n }\n input_buf[..read as usize].assume_init_ref()\n };\n\n // Convert Win32 input records into UTF16.\n for inp in input {\n match inp.EventType as u32 {\n Console::KEY_EVENT => {\n let event = unsafe { &inp.Event.KeyEvent };\n let ch = unsafe { event.uChar.UnicodeChar };\n if event.bKeyDown != 0 && ch != 0 {\n utf16_buf[utf16_buf_len] = MaybeUninit::new(ch);\n utf16_buf_len += 1;\n }\n }\n Console::WINDOW_BUFFER_SIZE_EVENT => {\n let event = unsafe { &inp.Event.WindowBufferSizeEvent };\n let w = event.dwSize.X as CoordType;\n let h = event.dwSize.Y as CoordType;\n // Windows is prone to sending broken/useless `WINDOW_BUFFER_SIZE_EVENT`s.\n // E.g. starting conhost will emit 3 in a row. Skip rendering in that case.\n if w > 0 && h > 0 {\n resize_event = Some(Size { width: w, height: h });\n }\n }\n _ => {}\n }\n }\n\n if resize_event.is_some() || utf16_buf_len != 0 {\n break;\n }\n }\n\n const RESIZE_EVENT_FMT_MAX_LEN: usize = 16; // \"\\x1b[8;65535;65535t\"\n let resize_event_len = if resize_event.is_some() { RESIZE_EVENT_FMT_MAX_LEN } else { 0 };\n // +1 to account for a potential `STATE.leading_surrogate`.\n let utf8_max_len = (utf16_buf_len + 1) * 3;\n let mut text = ArenaString::new_in(arena);\n text.reserve(utf8_max_len + resize_event_len);\n\n // Now prepend our previously extracted resize event.\n if let Some(resize_event) = resize_event {\n // If I read xterm's documentation correctly, CSI 18 t reports the window size in characters.\n // CSI 8 ; height ; width t is the response. Of course, we didn't send the request,\n // but we can use this fake response to trigger the editor to resize itself.\n _ = write!(text, \"\\x1b[8;{};{}t\", resize_event.height, resize_event.width);\n }\n\n // If the input ends with a lone lead surrogate, we need to remember it for the next read.\n if utf16_buf_len > 0 {\n unsafe {\n let last_char = utf16_buf[utf16_buf_len - 1].assume_init();\n if (0xD800..0xDC00).contains(&last_char) {\n STATE.leading_surrogate = last_char;\n utf16_buf_len -= 1;\n }\n }\n }\n\n // Convert the remaining input to UTF8, the sane encoding.\n if utf16_buf_len > 0 {\n unsafe {\n let vec = text.as_mut_vec();\n let spare = vec.spare_capacity_mut();\n\n let len = Globalization::WideCharToMultiByte(\n Globalization::CP_UTF8,\n 0,\n utf16_buf[0].as_ptr(),\n utf16_buf_len as i32,\n spare.as_mut_ptr() as *mut _,\n spare.len() as i32,\n null(),\n null_mut(),\n );\n\n if len > 0 {\n vec.set_len(vec.len() + len as usize);\n }\n }\n }\n\n text.shrink_to_fit();\n Some(text)\n}\n\n/// Writes a string to stdout.\n///\n/// Use this instead of `print!` or `println!` to avoid\n/// the overhead of Rust's stdio handling. Don't need that.\npub fn write_stdout(text: &str) {\n unsafe {\n let mut offset = 0;\n\n while offset < text.len() {\n let ptr = text.as_ptr().add(offset);\n let write = (text.len() - offset).min(GIBI) as u32;\n let mut written = 0;\n let ok = FileSystem::WriteFile(STATE.stdout, ptr, write, &mut written, null_mut());\n offset += written as usize;\n if ok == 0 || written == 0 {\n break;\n }\n }\n }\n}\n\n/// Check if the stdin handle is redirected to a file, etc.\n///\n/// # Returns\n///\n/// * `Some(file)` if stdin is redirected.\n/// * Otherwise, `None`.\npub fn open_stdin_if_redirected() -> Option {\n unsafe {\n let handle = Console::GetStdHandle(Console::STD_INPUT_HANDLE);\n // Did we reopen stdin during `init()`?\n if !std::ptr::eq(STATE.stdin, handle) { Some(File::from_raw_handle(handle)) } else { None }\n }\n}\n\npub fn drives() -> impl Iterator {\n unsafe {\n let mut mask = FileSystem::GetLogicalDrives();\n std::iter::from_fn(move || {\n let bit = mask.trailing_zeros();\n if bit >= 26 {\n None\n } else {\n mask &= !(1 << bit);\n Some((b'A' + bit as u8) as char)\n }\n })\n }\n}\n\n/// A unique identifier for a file.\npub enum FileId {\n Id(FileSystem::FILE_ID_INFO),\n Path(PathBuf),\n}\n\nimpl PartialEq for FileId {\n fn eq(&self, other: &Self) -> bool {\n match (self, other) {\n (Self::Id(left), Self::Id(right)) => {\n // Lowers to an efficient word-wise comparison.\n const SIZE: usize = std::mem::size_of::();\n let a: &[u8; SIZE] = unsafe { mem::transmute(left) };\n let b: &[u8; SIZE] = unsafe { mem::transmute(right) };\n a == b\n }\n (Self::Path(left), Self::Path(right)) => left == right,\n _ => false,\n }\n }\n}\n\nimpl Eq for FileId {}\n\n/// Returns a unique identifier for the given file by handle or path.\npub fn file_id(file: Option<&File>, path: &Path) -> apperr::Result {\n let file = match file {\n Some(f) => f,\n None => &File::open(path)?,\n };\n\n file_id_from_handle(file).or_else(|_| Ok(FileId::Path(std::fs::canonicalize(path)?)))\n}\n\nfn file_id_from_handle(file: &File) -> apperr::Result {\n unsafe {\n let mut info = MaybeUninit::::uninit();\n check_bool_return(FileSystem::GetFileInformationByHandleEx(\n file.as_raw_handle(),\n FileSystem::FileIdInfo,\n info.as_mut_ptr() as *mut _,\n mem::size_of::() as u32,\n ))?;\n Ok(FileId::Id(info.assume_init()))\n }\n}\n\n/// Canonicalizes the given path.\n///\n/// This differs from [`fs::canonicalize`] in that it strips the `\\\\?\\` UNC\n/// prefix on Windows. This is because it's confusing/ugly when displaying it.\npub fn canonicalize(path: &Path) -> std::io::Result {\n let mut path = fs::canonicalize(path)?;\n let path = path.as_mut_os_string();\n let mut path = mem::take(path).into_encoded_bytes();\n\n if path.len() > 6 && &path[0..4] == br\"\\\\?\\\" && path[4].is_ascii_uppercase() && path[5] == b':'\n {\n path.drain(0..4);\n }\n\n let path = unsafe { OsString::from_encoded_bytes_unchecked(path) };\n let path = PathBuf::from(path);\n Ok(path)\n}\n\n/// Reserves a virtual memory region of the given size.\n/// To commit the memory, use [`virtual_commit`].\n/// To release the memory, use [`virtual_release`].\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Don't forget to release the memory when you're done with it or you'll leak it.\npub unsafe fn virtual_reserve(size: usize) -> apperr::Result> {\n unsafe {\n #[allow(unused_assignments, unused_mut)]\n let mut base = null_mut();\n\n // In debug builds, we use fixed addresses to aid in debugging.\n // Makes it possible to immediately tell which address space a pointer belongs to.\n #[cfg(all(debug_assertions, not(target_pointer_width = \"32\")))]\n {\n static mut S_BASE_GEN: usize = 0x0000100000000000; // 16 TiB\n S_BASE_GEN += 0x0000001000000000; // 64 GiB\n base = S_BASE_GEN as *mut _;\n }\n\n check_ptr_return(Memory::VirtualAlloc(\n base,\n size,\n Memory::MEM_RESERVE,\n Memory::PAGE_READWRITE,\n ) as *mut u8)\n }\n}\n\n/// Releases a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from [`virtual_reserve`].\npub unsafe fn virtual_release(base: NonNull, _size: usize) {\n unsafe {\n // NOTE: `VirtualFree` fails if the pointer isn't\n // a valid base address or if the size isn't zero.\n Memory::VirtualFree(base.as_ptr() as *mut _, 0, Memory::MEM_RELEASE);\n }\n}\n\n/// Commits a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from [`virtual_reserve`]\n/// and to pass a size less than or equal to the size passed to [`virtual_reserve`].\npub unsafe fn virtual_commit(base: NonNull, size: usize) -> apperr::Result<()> {\n unsafe {\n check_ptr_return(Memory::VirtualAlloc(\n base.as_ptr() as *mut _,\n size,\n Memory::MEM_COMMIT,\n Memory::PAGE_READWRITE,\n ))\n .map(|_| ())\n }\n}\n\nunsafe fn get_module(name: *const u16) -> apperr::Result> {\n unsafe { check_ptr_return(LibraryLoader::GetModuleHandleW(name)) }\n}\n\nunsafe fn load_library(name: *const u16) -> apperr::Result> {\n unsafe {\n check_ptr_return(LibraryLoader::LoadLibraryExW(\n name,\n null_mut(),\n LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32,\n ))\n }\n}\n\n/// Loads a function from a dynamic library.\n///\n/// # Safety\n///\n/// This function is highly unsafe as it requires you to know the exact type\n/// of the function you're loading. No type checks whatsoever are performed.\n//\n// It'd be nice to constrain T to std::marker::FnPtr, but that's unstable.\npub unsafe fn get_proc_address(\n handle: NonNull,\n name: *const c_char,\n) -> apperr::Result {\n unsafe {\n let ptr = LibraryLoader::GetProcAddress(handle.as_ptr(), name as *const u8);\n if let Some(ptr) = ptr { Ok(mem::transmute_copy(&ptr)) } else { Err(get_last_error()) }\n }\n}\n\npub struct LibIcu {\n pub libicuuc: NonNull,\n pub libicui18n: NonNull,\n}\n\npub fn load_icu() -> apperr::Result {\n const fn const_ptr_u16_eq(a: *const u16, b: *const u16) -> bool {\n unsafe {\n let mut a = a;\n let mut b = b;\n loop {\n if *a != *b {\n return false;\n }\n if *a == 0 {\n return true;\n }\n a = a.add(1);\n b = b.add(1);\n }\n }\n }\n\n const LIBICUUC: *const u16 = w_env!(\"EDIT_CFG_ICUUC_SONAME\");\n const LIBICUI18N: *const u16 = w_env!(\"EDIT_CFG_ICUI18N_SONAME\");\n\n if const { const_ptr_u16_eq(LIBICUUC, LIBICUI18N) } {\n let icu = unsafe { load_library(LIBICUUC)? };\n Ok(LibIcu { libicuuc: icu, libicui18n: icu })\n } else {\n let libicuuc = unsafe { load_library(LIBICUUC)? };\n let libicui18n = unsafe { load_library(LIBICUI18N)? };\n Ok(LibIcu { libicuuc, libicui18n })\n }\n}\n\n/// Returns a list of preferred languages for the current user.\npub fn preferred_languages(arena: &Arena) -> Vec, &Arena> {\n // If the GetUserPreferredUILanguages() don't fit into 512 characters,\n // honestly, just give up. How many languages do you realistically need?\n const LEN: usize = 512;\n\n let scratch = scratch_arena(Some(arena));\n let mut res = Vec::new_in(arena);\n\n // Get the list of preferred languages via `GetUserPreferredUILanguages`.\n let langs = unsafe {\n let buf = scratch.alloc_uninit_slice(LEN);\n let mut len = buf.len() as u32;\n let mut num = 0;\n\n let ok = Globalization::GetUserPreferredUILanguages(\n Globalization::MUI_LANGUAGE_NAME,\n &mut num,\n buf[0].as_mut_ptr(),\n &mut len,\n );\n\n if ok == 0 || num == 0 {\n len = 0;\n }\n\n // Drop the terminating double-null character.\n len = len.saturating_sub(1);\n\n buf[..len as usize].assume_init_ref()\n };\n\n // Convert UTF16 to UTF8.\n let langs = wide_to_utf8(&scratch, langs);\n\n // Split the null-delimited string into individual chunks\n // and copy them into the given arena.\n res.extend(\n langs\n .split_terminator('\\0')\n .filter(|s| !s.is_empty())\n .map(|s| ArenaString::from_str(arena, s)),\n );\n res\n}\n\nfn wide_to_utf8<'a>(arena: &'a Arena, wide: &[u16]) -> ArenaString<'a> {\n let mut res = ArenaString::new_in(arena);\n res.reserve(wide.len() * 3);\n\n let len = unsafe {\n Globalization::WideCharToMultiByte(\n Globalization::CP_UTF8,\n 0,\n wide.as_ptr(),\n wide.len() as i32,\n res.as_mut_ptr() as *mut _,\n res.capacity() as i32,\n null(),\n null_mut(),\n )\n };\n if len > 0 {\n unsafe { res.as_mut_vec().set_len(len as usize) };\n }\n\n res.shrink_to_fit();\n res\n}\n\n#[cold]\nfn get_last_error() -> apperr::Error {\n unsafe { gle_to_apperr(Foundation::GetLastError()) }\n}\n\n#[inline]\nconst fn gle_to_apperr(gle: u32) -> apperr::Error {\n apperr::Error::new_sys(if gle == 0 { 0x8000FFFF } else { 0x80070000 | gle })\n}\n\n#[inline]\npub(crate) fn io_error_to_apperr(err: std::io::Error) -> apperr::Error {\n gle_to_apperr(err.raw_os_error().unwrap_or(0) as u32)\n}\n\n/// Formats a platform error code into a human-readable string.\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n unsafe {\n let mut ptr: *mut u8 = null_mut();\n let len = Debug::FormatMessageA(\n Debug::FORMAT_MESSAGE_ALLOCATE_BUFFER\n | Debug::FORMAT_MESSAGE_FROM_SYSTEM\n | Debug::FORMAT_MESSAGE_IGNORE_INSERTS,\n null(),\n code,\n 0,\n &mut ptr as *mut *mut _ as *mut _,\n 0,\n null_mut(),\n );\n\n write!(f, \"Error {code:#08x}\")?;\n\n if len > 0 {\n let msg = str_from_raw_parts(ptr, len as usize);\n let msg = msg.trim_ascii();\n let msg = msg.replace(['\\r', '\\n'], \" \");\n write!(f, \": {msg}\")?;\n Foundation::LocalFree(ptr as *mut _);\n }\n\n Ok(())\n }\n}\n\n/// Checks if the given error is a \"file not found\" error.\npub fn apperr_is_not_found(err: apperr::Error) -> bool {\n err == gle_to_apperr(Foundation::ERROR_FILE_NOT_FOUND)\n}\n\nfn check_bool_return(ret: Foundation::BOOL) -> apperr::Result<()> {\n if ret == 0 { Err(get_last_error()) } else { Ok(()) }\n}\n\nfn check_ptr_return(ret: *mut T) -> apperr::Result> {\n NonNull::new(ret).ok_or_else(get_last_error)\n}\n"], ["/edit/src/vt.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Our VT parser.\n\nuse std::time;\n\nuse crate::simd::memchr2;\nuse crate::unicode::Utf8Chars;\n\n/// The parser produces these tokens.\npub enum Token<'parser, 'input> {\n /// A bunch of text. Doesn't contain any control characters.\n Text(&'input str),\n /// A single control character, like backspace or return.\n Ctrl(char),\n /// We encountered `ESC x` and this contains `x`.\n Esc(char),\n /// We encountered `ESC O x` and this contains `x`.\n SS3(char),\n /// A CSI sequence started with `ESC [`.\n ///\n /// They are the most common escape sequences. See [`Csi`].\n Csi(&'parser Csi),\n /// An OSC sequence started with `ESC ]`.\n ///\n /// The sequence may be split up into multiple tokens if the input\n /// is given in chunks. This is indicated by the `partial` field.\n Osc { data: &'input str, partial: bool },\n /// An DCS sequence started with `ESC P`.\n ///\n /// The sequence may be split up into multiple tokens if the input\n /// is given in chunks. This is indicated by the `partial` field.\n Dcs { data: &'input str, partial: bool },\n}\n\n/// Stores the state of the parser.\n#[derive(Clone, Copy)]\nenum State {\n Ground,\n Esc,\n Ss3,\n Csi,\n Osc,\n Dcs,\n OscEsc,\n DcsEsc,\n}\n\n/// A single CSI sequence, parsed for your convenience.\npub struct Csi {\n /// The parameters of the CSI sequence.\n pub params: [u16; 32],\n /// The number of parameters stored in [`Csi::params`].\n pub param_count: usize,\n /// The private byte, if any. `0` if none.\n ///\n /// The private byte is the first character right after the\n /// `ESC [` sequence. It is usually a `?` or `<`.\n pub private_byte: char,\n /// The final byte of the CSI sequence.\n ///\n /// This is the last character of the sequence, e.g. `m` or `H`.\n pub final_byte: char,\n}\n\npub struct Parser {\n state: State,\n // Csi is not part of State, because it allows us\n // to more quickly erase and reuse the struct.\n csi: Csi,\n}\n\nimpl Parser {\n pub fn new() -> Self {\n Self {\n state: State::Ground,\n csi: Csi { params: [0; 32], param_count: 0, private_byte: '\\0', final_byte: '\\0' },\n }\n }\n\n /// Suggests a timeout for the next call to `read()`.\n ///\n /// We need this because of the ambiguity of whether a trailing\n /// escape character in an input is starting another escape sequence or\n /// is just the result of the user literally pressing the Escape key.\n pub fn read_timeout(&mut self) -> std::time::Duration {\n match self.state {\n // 100ms is a upper ceiling for a responsive feel.\n // Realistically though, this could be much lower.\n //\n // However, there seems to be issues with OpenSSH on Windows.\n // See: https://github.com/PowerShell/Win32-OpenSSH/issues/2275\n State::Esc => time::Duration::from_millis(100),\n _ => time::Duration::MAX,\n }\n }\n\n /// Parses the given input into VT sequences.\n ///\n /// You should call this function even if your `read()`\n /// had a timeout (pass an empty string in that case).\n pub fn parse<'parser, 'input>(\n &'parser mut self,\n input: &'input str,\n ) -> Stream<'parser, 'input> {\n Stream { parser: self, input, off: 0 }\n }\n}\n\n/// An iterator that parses VT sequences into [`Token`]s.\n///\n/// Can't implement [`Iterator`], because this is a \"lending iterator\".\npub struct Stream<'parser, 'input> {\n parser: &'parser mut Parser,\n input: &'input str,\n off: usize,\n}\n\nimpl<'input> Stream<'_, 'input> {\n /// Returns the input that is being parsed.\n pub fn input(&self) -> &'input str {\n self.input\n }\n\n /// Returns the current parser offset.\n pub fn offset(&self) -> usize {\n self.off\n }\n\n /// Reads and consumes raw bytes from the input.\n pub fn read(&mut self, dst: &mut [u8]) -> usize {\n let bytes = self.input.as_bytes();\n let off = self.off.min(bytes.len());\n let len = dst.len().min(bytes.len() - off);\n dst[..len].copy_from_slice(&bytes[off..off + len]);\n self.off += len;\n len\n }\n\n fn decode_next(&mut self) -> char {\n let mut iter = Utf8Chars::new(self.input.as_bytes(), self.off);\n let c = iter.next().unwrap_or('\\0');\n self.off = iter.offset();\n c\n }\n\n /// Parses the next VT sequence from the previously given input.\n #[allow(\n clippy::should_implement_trait,\n reason = \"can't implement Iterator because this is a lending iterator\"\n )]\n pub fn next(&mut self) -> Option> {\n let input = self.input;\n let bytes = input.as_bytes();\n\n // If the previous input ended with an escape character, `read_timeout()`\n // returned `Some(..)` timeout, and if the caller did everything correctly\n // and there was indeed a timeout, we should be called with an empty\n // input. In that case we'll return the escape as its own token.\n if input.is_empty() && matches!(self.parser.state, State::Esc) {\n self.parser.state = State::Ground;\n return Some(Token::Esc('\\0'));\n }\n\n while self.off < bytes.len() {\n // TODO: The state machine can be roughly broken up into two parts:\n // * Wants to parse 1 `char` at a time: Ground, Esc, Ss3\n // These could all be unified to a single call to `decode_next()`.\n // * Wants to bulk-process bytes: Csi, Osc, Dcs\n // We should do that so the UTF8 handling is a bit more \"unified\".\n match self.parser.state {\n State::Ground => match bytes[self.off] {\n 0x1b => {\n self.parser.state = State::Esc;\n self.off += 1;\n }\n c @ (0x00..0x20 | 0x7f) => {\n self.off += 1;\n return Some(Token::Ctrl(c as char));\n }\n _ => {\n let beg = self.off;\n while {\n self.off += 1;\n self.off < bytes.len()\n && bytes[self.off] >= 0x20\n && bytes[self.off] != 0x7f\n } {}\n return Some(Token::Text(&input[beg..self.off]));\n }\n },\n State::Esc => match self.decode_next() {\n '[' => {\n self.parser.state = State::Csi;\n self.parser.csi.private_byte = '\\0';\n self.parser.csi.final_byte = '\\0';\n while self.parser.csi.param_count > 0 {\n self.parser.csi.param_count -= 1;\n self.parser.csi.params[self.parser.csi.param_count] = 0;\n }\n }\n ']' => {\n self.parser.state = State::Osc;\n }\n 'O' => {\n self.parser.state = State::Ss3;\n }\n 'P' => {\n self.parser.state = State::Dcs;\n }\n c => {\n self.parser.state = State::Ground;\n return Some(Token::Esc(c));\n }\n },\n State::Ss3 => {\n self.parser.state = State::Ground;\n return Some(Token::SS3(self.decode_next()));\n }\n State::Csi => {\n loop {\n // If we still have slots left, parse the parameter.\n if self.parser.csi.param_count < self.parser.csi.params.len() {\n let dst = &mut self.parser.csi.params[self.parser.csi.param_count];\n while self.off < bytes.len() && bytes[self.off].is_ascii_digit() {\n let add = bytes[self.off] as u32 - b'0' as u32;\n let value = *dst as u32 * 10 + add;\n *dst = value.min(u16::MAX as u32) as u16;\n self.off += 1;\n }\n } else {\n // ...otherwise, skip the parameters until we find the final byte.\n while self.off < bytes.len() && bytes[self.off].is_ascii_digit() {\n self.off += 1;\n }\n }\n\n // Encountered the end of the input before finding the final byte.\n if self.off >= bytes.len() {\n return None;\n }\n\n let c = bytes[self.off];\n self.off += 1;\n\n match c {\n 0x40..=0x7e => {\n self.parser.state = State::Ground;\n self.parser.csi.final_byte = c as char;\n if self.parser.csi.param_count != 0\n || self.parser.csi.params[0] != 0\n {\n self.parser.csi.param_count += 1;\n }\n return Some(Token::Csi(&self.parser.csi));\n }\n b';' => self.parser.csi.param_count += 1,\n b'<'..=b'?' => self.parser.csi.private_byte = c as char,\n _ => {}\n }\n }\n }\n State::Osc | State::Dcs => {\n let beg = self.off;\n let mut data;\n let mut partial;\n\n loop {\n // Find any indication for the end of the OSC/DCS sequence.\n self.off = memchr2(b'\\x07', b'\\x1b', bytes, self.off);\n\n data = &input[beg..self.off];\n partial = self.off >= bytes.len();\n\n // Encountered the end of the input before finding the terminator.\n if partial {\n break;\n }\n\n let c = bytes[self.off];\n self.off += 1;\n\n if c == 0x1b {\n // It's only a string terminator if it's followed by \\.\n // We're at the end so we're saving the state and will continue next time.\n if self.off >= bytes.len() {\n self.parser.state = match self.parser.state {\n State::Osc => State::OscEsc,\n _ => State::DcsEsc,\n };\n partial = true;\n break;\n }\n\n // False alarm: Not a string terminator.\n if bytes[self.off] != b'\\\\' {\n continue;\n }\n\n self.off += 1;\n }\n\n break;\n }\n\n let state = self.parser.state;\n if !partial {\n self.parser.state = State::Ground;\n }\n return match state {\n State::Osc => Some(Token::Osc { data, partial }),\n _ => Some(Token::Dcs { data, partial }),\n };\n }\n State::OscEsc | State::DcsEsc => {\n // We were processing an OSC/DCS sequence and the last byte was an escape character.\n // It's only a string terminator if it's followed by \\ (= \"\\x1b\\\\\").\n if bytes[self.off] == b'\\\\' {\n // It was indeed a string terminator and we can now tell the caller about it.\n let state = self.parser.state;\n\n // Consume the terminator (one byte in the previous input and this byte).\n self.parser.state = State::Ground;\n self.off += 1;\n\n return match state {\n State::OscEsc => Some(Token::Osc { data: \"\", partial: false }),\n _ => Some(Token::Dcs { data: \"\", partial: false }),\n };\n } else {\n // False alarm: Not a string terminator.\n // We'll return the escape character as a separate token.\n // Processing will continue from the current state (`bytes[self.off]`).\n self.parser.state = match self.parser.state {\n State::OscEsc => State::Osc,\n _ => State::Dcs,\n };\n return match self.parser.state {\n State::Osc => Some(Token::Osc { data: \"\\x1b\", partial: true }),\n _ => Some(Token::Dcs { data: \"\\x1b\", partial: true }),\n };\n }\n }\n }\n }\n\n None\n }\n}\n"], ["/edit/src/bin/edit/draw_statusbar.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena::scratch_arena;\nuse edit::framebuffer::{Attributes, IndexedColor};\nuse edit::fuzzy::score_fuzzy;\nuse edit::helpers::*;\nuse edit::input::vk;\nuse edit::tui::*;\nuse edit::{arena_format, icu};\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_statusbar(ctx: &mut Context, state: &mut State) {\n ctx.table_begin(\"statusbar\");\n ctx.attr_focus_well();\n ctx.attr_background_rgba(state.menubar_color_bg);\n ctx.attr_foreground_rgba(state.menubar_color_fg);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n ctx.attr_padding(Rect::two(0, 1));\n\n if let Some(doc) = state.documents.active() {\n let mut tb = doc.buffer.borrow_mut();\n\n ctx.table_next_row();\n\n if ctx.button(\"newline\", if tb.is_crlf() { \"CRLF\" } else { \"LF\" }, ButtonStyle::default()) {\n let is_crlf = tb.is_crlf();\n tb.normalize_newlines(!is_crlf);\n }\n if state.wants_statusbar_focus {\n state.wants_statusbar_focus = false;\n ctx.steal_focus();\n }\n\n state.wants_encoding_picker |=\n ctx.button(\"encoding\", tb.encoding(), ButtonStyle::default());\n if state.wants_encoding_picker {\n if doc.path.is_some() {\n ctx.block_begin(\"frame\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 1.0,\n offset_x: 0.0,\n offset_y: 0.0,\n });\n ctx.attr_padding(Rect::two(0, 1));\n ctx.attr_border();\n {\n if ctx.button(\"reopen\", loc(LocId::EncodingReopen), ButtonStyle::default()) {\n state.wants_encoding_change = StateEncodingChange::Reopen;\n }\n ctx.focus_on_first_present();\n if ctx.button(\"convert\", loc(LocId::EncodingConvert), ButtonStyle::default()) {\n state.wants_encoding_change = StateEncodingChange::Convert;\n }\n }\n ctx.block_end();\n } else {\n // Can't reopen a file that doesn't exist.\n state.wants_encoding_change = StateEncodingChange::Convert;\n }\n\n if !ctx.contains_focus() {\n state.wants_encoding_picker = false;\n ctx.needs_rerender();\n }\n }\n\n state.wants_indentation_picker |= ctx.button(\n \"indentation\",\n &arena_format!(\n ctx.arena(),\n \"{}:{}\",\n loc(if tb.indent_with_tabs() {\n LocId::IndentationTabs\n } else {\n LocId::IndentationSpaces\n }),\n tb.tab_size(),\n ),\n ButtonStyle::default(),\n );\n if state.wants_indentation_picker {\n ctx.table_begin(\"indentation-picker\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 1.0,\n offset_x: 0.0,\n offset_y: 0.0,\n });\n ctx.attr_border();\n ctx.attr_padding(Rect::two(0, 1));\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n {\n if ctx.contains_focus() && ctx.consume_shortcut(vk::RETURN) {\n ctx.toss_focus_up();\n }\n\n ctx.table_next_row();\n\n ctx.list_begin(\"type\");\n ctx.focus_on_first_present();\n ctx.attr_padding(Rect::two(0, 1));\n {\n if ctx.list_item(tb.indent_with_tabs(), loc(LocId::IndentationTabs))\n != ListSelection::Unchanged\n {\n tb.set_indent_with_tabs(true);\n ctx.needs_rerender();\n }\n if ctx.list_item(!tb.indent_with_tabs(), loc(LocId::IndentationSpaces))\n != ListSelection::Unchanged\n {\n tb.set_indent_with_tabs(false);\n ctx.needs_rerender();\n }\n }\n ctx.list_end();\n\n ctx.list_begin(\"width\");\n ctx.attr_padding(Rect::two(0, 2));\n {\n for width in 1u8..=8 {\n let ch = [b'0' + width];\n let label = unsafe { std::str::from_utf8_unchecked(&ch) };\n\n if ctx.list_item(tb.tab_size() == width as CoordType, label)\n != ListSelection::Unchanged\n {\n tb.set_tab_size(width as CoordType);\n ctx.needs_rerender();\n }\n }\n }\n ctx.list_end();\n }\n ctx.table_end();\n\n if !ctx.contains_focus() {\n state.wants_indentation_picker = false;\n ctx.needs_rerender();\n }\n }\n\n ctx.label(\n \"location\",\n &arena_format!(\n ctx.arena(),\n \"{}:{}\",\n tb.cursor_logical_pos().y + 1,\n tb.cursor_logical_pos().x + 1\n ),\n );\n\n #[cfg(feature = \"debug-latency\")]\n ctx.label(\n \"stats\",\n &arena_format!(ctx.arena(), \"{}/{}\", tb.logical_line_count(), tb.visual_line_count(),),\n );\n\n if tb.is_overtype() && ctx.button(\"overtype\", \"OVR\", ButtonStyle::default()) {\n tb.set_overtype(false);\n ctx.needs_rerender();\n }\n\n if tb.is_dirty() {\n ctx.label(\"dirty\", \"*\");\n }\n\n ctx.block_begin(\"filename-container\");\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n {\n let total = state.documents.len();\n let mut filename = doc.filename.as_str();\n let filename_buf;\n\n if total > 1 {\n filename_buf = arena_format!(ctx.arena(), \"{} + {}\", filename, total - 1);\n filename = &filename_buf;\n }\n\n state.wants_go_to_file |= ctx.button(\"filename\", filename, ButtonStyle::default());\n ctx.inherit_focus();\n ctx.attr_overflow(Overflow::TruncateMiddle);\n ctx.attr_position(Position::Right);\n }\n ctx.block_end();\n } else {\n state.wants_statusbar_focus = false;\n state.wants_encoding_picker = false;\n state.wants_indentation_picker = false;\n }\n\n ctx.table_end();\n}\n\npub fn draw_dialog_encoding_change(ctx: &mut Context, state: &mut State) {\n let encoding = state.documents.active_mut().map_or(\"\", |doc| doc.buffer.borrow().encoding());\n let reopen = state.wants_encoding_change == StateEncodingChange::Reopen;\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n let mut change = None;\n let mut done = encoding.is_empty();\n\n ctx.modal_begin(\n \"encode\",\n if reopen { loc(LocId::EncodingReopen) } else { loc(LocId::EncodingConvert) },\n );\n {\n ctx.table_begin(\"encoding-search\");\n ctx.table_set_columns(&[0, COORD_TYPE_SAFE_MAX]);\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n ctx.inherit_focus();\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n ctx.label(\"needle-label\", loc(LocId::SearchNeedleLabel));\n\n if ctx.editline(\"needle\", &mut state.encoding_picker_needle) {\n encoding_picker_update_list(state);\n }\n ctx.inherit_focus();\n }\n ctx.table_end();\n\n ctx.scrollarea_begin(\"scrollarea\", Size { width, height });\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n {\n ctx.list_begin(\"encodings\");\n ctx.inherit_focus();\n\n for enc in state\n .encoding_picker_results\n .as_deref()\n .unwrap_or_else(|| icu::get_available_encodings().preferred)\n {\n if ctx.list_item(enc.canonical == encoding, enc.label) == ListSelection::Activated {\n change = Some(enc.canonical);\n break;\n }\n ctx.attr_overflow(Overflow::TruncateTail);\n }\n ctx.list_end();\n }\n ctx.scrollarea_end();\n }\n done |= ctx.modal_end();\n done |= change.is_some();\n\n if let Some(encoding) = change\n && let Some(doc) = state.documents.active_mut()\n {\n if reopen && doc.path.is_some() {\n let mut res = Ok(());\n if doc.buffer.borrow().is_dirty() {\n res = doc.save(None);\n }\n if res.is_ok() {\n res = doc.reread(Some(encoding));\n }\n if let Err(err) = res {\n error_log_add(ctx, state, err);\n }\n } else {\n doc.buffer.borrow_mut().set_encoding(encoding);\n }\n }\n\n if done {\n state.wants_encoding_change = StateEncodingChange::None;\n state.encoding_picker_needle.clear();\n state.encoding_picker_results = None;\n ctx.needs_rerender();\n }\n}\n\nfn encoding_picker_update_list(state: &mut State) {\n state.encoding_picker_results = None;\n\n let needle = state.encoding_picker_needle.trim_ascii();\n if needle.is_empty() {\n return;\n }\n\n let encodings = icu::get_available_encodings();\n let scratch = scratch_arena(None);\n let mut matches = Vec::new_in(&*scratch);\n\n for enc in encodings.all {\n let local_scratch = scratch_arena(Some(&scratch));\n let (score, _) = score_fuzzy(&local_scratch, enc.label, needle, true);\n\n if score > 0 {\n matches.push((score, *enc));\n }\n }\n\n matches.sort_by(|a, b| b.0.cmp(&a.0));\n state.encoding_picker_results = Some(Vec::from_iter(matches.iter().map(|(_, enc)| *enc)));\n}\n\npub fn draw_go_to_file(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"go-to-file\", loc(LocId::ViewGoToFile));\n {\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n\n ctx.scrollarea_begin(\"scrollarea\", Size { width, height });\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n ctx.inherit_focus();\n {\n ctx.list_begin(\"documents\");\n ctx.inherit_focus();\n\n if state.documents.update_active(|doc| {\n let tb = doc.buffer.borrow();\n\n ctx.styled_list_item_begin();\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.styled_label_add_text(if tb.is_dirty() { \"* \" } else { \" \" });\n ctx.styled_label_add_text(&doc.filename);\n\n if let Some(path) = &doc.dir {\n ctx.styled_label_add_text(\" \");\n ctx.styled_label_set_attributes(Attributes::Italic);\n ctx.styled_label_add_text(path.as_str());\n }\n\n ctx.styled_list_item_end(false) == ListSelection::Activated\n }) {\n state.wants_go_to_file = false;\n ctx.needs_rerender();\n }\n\n ctx.list_end();\n }\n ctx.scrollarea_end();\n }\n if ctx.modal_end() {\n state.wants_go_to_file = false;\n }\n}\n"], ["/edit/src/bin/edit/draw_filepicker.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::cmp::Ordering;\nuse std::fs;\nuse std::path::{Path, PathBuf};\n\nuse edit::arena::scratch_arena;\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\nuse edit::{icu, path};\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_file_picker(ctx: &mut Context, state: &mut State) {\n // The save dialog is pre-filled with the current document filename.\n if state.wants_file_picker == StateFilePicker::SaveAs {\n state.wants_file_picker = StateFilePicker::SaveAsShown;\n\n if state.file_picker_pending_name.as_os_str().is_empty() {\n state.file_picker_pending_name =\n state.documents.active().map_or(\"Untitled.txt\", |doc| doc.filename.as_str()).into();\n }\n }\n\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n let mut doit = None;\n let mut done = false;\n\n ctx.modal_begin(\n \"file-picker\",\n if state.wants_file_picker == StateFilePicker::Open {\n loc(LocId::FileOpen)\n } else {\n loc(LocId::FileSaveAs)\n },\n );\n ctx.attr_intrinsic_size(Size { width, height });\n {\n let contains_focus = ctx.contains_focus();\n let mut activated = false;\n\n ctx.table_begin(\"path\");\n ctx.table_set_columns(&[0, COORD_TYPE_SAFE_MAX]);\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n ctx.attr_padding(Rect::two(1, 1));\n ctx.inherit_focus();\n {\n ctx.table_next_row();\n\n ctx.label(\"dir-label\", loc(LocId::SaveAsDialogPathLabel));\n ctx.label(\"dir\", state.file_picker_pending_dir.as_str());\n ctx.attr_overflow(Overflow::TruncateMiddle);\n\n ctx.table_next_row();\n ctx.inherit_focus();\n\n ctx.label(\"name-label\", loc(LocId::SaveAsDialogNameLabel));\n\n let name_changed = ctx.editline(\"name\", &mut state.file_picker_pending_name);\n ctx.inherit_focus();\n\n if ctx.contains_focus() {\n if name_changed && ctx.is_focused() {\n update_autocomplete_suggestions(state);\n }\n } else if !state.file_picker_autocomplete.is_empty() {\n state.file_picker_autocomplete.clear();\n }\n\n if !state.file_picker_autocomplete.is_empty() {\n let bg = ctx.indexed_alpha(IndexedColor::Background, 3, 4);\n let fg = ctx.contrasted(bg);\n let focus_list_beg = ctx.is_focused() && ctx.consume_shortcut(vk::DOWN);\n let focus_list_end = ctx.is_focused() && ctx.consume_shortcut(vk::UP);\n let mut autocomplete_done = ctx.consume_shortcut(vk::ESCAPE);\n\n ctx.list_begin(\"suggestions\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 0.0,\n offset_x: 0.0,\n offset_y: 1.0,\n });\n ctx.attr_border();\n ctx.attr_background_rgba(bg);\n ctx.attr_foreground_rgba(fg);\n {\n for (idx, suggestion) in state.file_picker_autocomplete.iter().enumerate() {\n let sel = ctx.list_item(false, suggestion.as_str());\n if sel != ListSelection::Unchanged {\n state.file_picker_pending_name = suggestion.as_path().into();\n }\n if sel == ListSelection::Activated {\n autocomplete_done = true;\n }\n\n let is_first = idx == 0;\n let is_last = idx == state.file_picker_autocomplete.len() - 1;\n if (is_first && focus_list_beg) || (is_last && focus_list_end) {\n ctx.list_item_steal_focus();\n } else if ctx.is_focused()\n && ((is_first && ctx.consume_shortcut(vk::UP))\n || (is_last && ctx.consume_shortcut(vk::DOWN)))\n {\n ctx.toss_focus_up();\n }\n }\n }\n ctx.list_end();\n\n // If the user typed something, we want to put focus back into the editline.\n // TODO: The input should be processed by the editline and not simply get swallowed.\n if ctx.keyboard_input().is_some() {\n ctx.set_input_consumed();\n autocomplete_done = true;\n }\n\n if autocomplete_done {\n state.file_picker_autocomplete.clear();\n }\n }\n\n if ctx.is_focused() && ctx.consume_shortcut(vk::RETURN) {\n activated = true;\n }\n }\n ctx.table_end();\n\n if state.file_picker_entries.is_none() {\n draw_dialog_saveas_refresh_files(state);\n }\n\n ctx.scrollarea_begin(\n \"directory\",\n Size {\n width: 0,\n // -1 for the label (top)\n // -1 for the label (bottom)\n // -1 for the editline (bottom)\n height: height - 3,\n },\n );\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n {\n ctx.next_block_id_mixin(state.file_picker_pending_dir_revision);\n ctx.list_begin(\"files\");\n ctx.inherit_focus();\n\n for entries in state.file_picker_entries.as_ref().unwrap() {\n for entry in entries {\n match ctx.list_item(false, entry.as_str()) {\n ListSelection::Unchanged => {}\n ListSelection::Selected => {\n state.file_picker_pending_name = entry.as_path().into()\n }\n ListSelection::Activated => activated = true,\n }\n ctx.attr_overflow(Overflow::TruncateMiddle);\n }\n }\n\n ctx.list_end();\n }\n ctx.scrollarea_end();\n\n if contains_focus\n && (ctx.consume_shortcut(vk::BACK) || ctx.consume_shortcut(kbmod::ALT | vk::UP))\n {\n state.file_picker_pending_name = \"..\".into();\n activated = true;\n }\n\n if activated {\n doit = draw_file_picker_update_path(state);\n\n // Check if the file already exists and show an overwrite warning in that case.\n if state.wants_file_picker != StateFilePicker::Open\n && let Some(path) = doit.as_deref()\n && path.exists()\n {\n state.file_picker_overwrite_warning = doit.take();\n }\n }\n }\n if ctx.modal_end() {\n done = true;\n }\n\n if state.file_picker_overwrite_warning.is_some() {\n let mut save;\n\n ctx.modal_begin(\"overwrite\", loc(LocId::FileOverwriteWarning));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n let contains_focus = ctx.contains_focus();\n\n ctx.label(\"description\", loc(LocId::FileOverwriteWarningDescription));\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n save = ctx.button(\"yes\", loc(LocId::Yes), ButtonStyle::default());\n ctx.inherit_focus();\n\n if ctx.button(\"no\", loc(LocId::No), ButtonStyle::default()) {\n state.file_picker_overwrite_warning = None;\n }\n }\n ctx.table_end();\n\n if contains_focus {\n save |= ctx.consume_shortcut(vk::Y);\n if ctx.consume_shortcut(vk::N) {\n state.file_picker_overwrite_warning = None;\n }\n }\n }\n if ctx.modal_end() {\n state.file_picker_overwrite_warning = None;\n }\n\n if save {\n doit = state.file_picker_overwrite_warning.take();\n }\n }\n\n if let Some(path) = doit {\n let res = if state.wants_file_picker == StateFilePicker::Open {\n state.documents.add_file_path(&path).map(|_| ())\n } else if let Some(doc) = state.documents.active_mut() {\n doc.save(Some(path))\n } else {\n Ok(())\n };\n match res {\n Ok(..) => {\n ctx.needs_rerender();\n done = true;\n }\n Err(err) => error_log_add(ctx, state, err),\n }\n }\n\n if done {\n state.wants_file_picker = StateFilePicker::None;\n state.file_picker_pending_name = Default::default();\n state.file_picker_entries = Default::default();\n state.file_picker_overwrite_warning = Default::default();\n state.file_picker_autocomplete = Default::default();\n }\n}\n\n// Returns Some(path) if the path refers to a file.\nfn draw_file_picker_update_path(state: &mut State) -> Option {\n let old_path = state.file_picker_pending_dir.as_path();\n let path = old_path.join(&state.file_picker_pending_name);\n let path = path::normalize(&path);\n\n let (dir, name) = if path.is_dir() {\n // If the current path is C:\\ and the user selects \"..\", we want to\n // navigate to the drive picker. Since `path::normalize` will turn C:\\.. into C:\\,\n // we can detect this by checking if the length of the path didn't change.\n let dir = if cfg!(windows)\n && state.file_picker_pending_name == Path::new(\"..\")\n // It's unnecessary to check the contents of the paths.\n && old_path.as_os_str().len() == path.as_os_str().len()\n {\n Path::new(\"\")\n } else {\n path.as_path()\n };\n (dir, PathBuf::new())\n } else {\n let dir = path.parent().unwrap_or(&path);\n let name = path.file_name().map_or(Default::default(), |s| s.into());\n (dir, name)\n };\n if dir != state.file_picker_pending_dir.as_path() {\n state.file_picker_pending_dir = DisplayablePathBuf::from_path(dir.to_path_buf());\n state.file_picker_pending_dir_revision =\n state.file_picker_pending_dir_revision.wrapping_add(1);\n state.file_picker_entries = None;\n }\n\n state.file_picker_pending_name = name;\n if state.file_picker_pending_name.as_os_str().is_empty() { None } else { Some(path) }\n}\n\nfn draw_dialog_saveas_refresh_files(state: &mut State) {\n let dir = state.file_picker_pending_dir.as_path();\n // [\"..\", directories, files]\n let mut dirs_files = [Vec::new(), Vec::new(), Vec::new()];\n\n #[cfg(windows)]\n if dir.as_os_str().is_empty() {\n // If the path is empty, we are at the drive picker.\n // Add all drives as entries.\n for drive in edit::sys::drives() {\n dirs_files[1].push(DisplayablePathBuf::from_string(format!(\"{drive}:\\\\\")));\n }\n\n state.file_picker_entries = Some(dirs_files);\n return;\n }\n\n if cfg!(windows) || dir.parent().is_some() {\n dirs_files[0].push(DisplayablePathBuf::from(\"..\"));\n }\n\n if let Ok(iter) = fs::read_dir(dir) {\n for entry in iter.flatten() {\n if let Ok(metadata) = entry.metadata() {\n let mut name = entry.file_name();\n let dir = metadata.is_dir()\n || (metadata.is_symlink()\n && fs::metadata(entry.path()).is_ok_and(|m| m.is_dir()));\n let idx = if dir { 1 } else { 2 };\n\n if dir {\n name.push(\"/\");\n }\n\n dirs_files[idx].push(DisplayablePathBuf::from(name));\n }\n }\n }\n\n for entries in &mut dirs_files[1..] {\n entries.sort_by(|a, b| {\n let a = a.as_bytes();\n let b = b.as_bytes();\n\n let a_is_dir = a.last() == Some(&b'/');\n let b_is_dir = b.last() == Some(&b'/');\n\n match b_is_dir.cmp(&a_is_dir) {\n Ordering::Equal => icu::compare_strings(a, b),\n other => other,\n }\n });\n }\n\n state.file_picker_entries = Some(dirs_files);\n}\n\n#[inline(never)]\nfn update_autocomplete_suggestions(state: &mut State) {\n state.file_picker_autocomplete.clear();\n\n if state.file_picker_pending_name.as_os_str().is_empty() {\n return;\n }\n\n let scratch = scratch_arena(None);\n let needle = state.file_picker_pending_name.as_os_str().as_encoded_bytes();\n let mut matches = Vec::new();\n\n // Using binary search below we'll quickly find the lower bound\n // of items that match the needle (= share a common prefix).\n //\n // The problem is finding the upper bound. Here I'm using a trick:\n // By appending U+10FFFF (the highest possible Unicode code point)\n // we create a needle that naturally yields an upper bound.\n let mut needle_upper_bound = Vec::with_capacity_in(needle.len() + 4, &*scratch);\n needle_upper_bound.extend_from_slice(needle);\n needle_upper_bound.extend_from_slice(b\"\\xf4\\x8f\\xbf\\xbf\");\n\n if let Some(dirs_files) = &state.file_picker_entries {\n 'outer: for entries in &dirs_files[1..] {\n let lower = entries\n .binary_search_by(|entry| icu::compare_strings(entry.as_bytes(), needle))\n .unwrap_or_else(|i| i);\n\n for entry in &entries[lower..] {\n let haystack = entry.as_bytes();\n match icu::compare_strings(haystack, &needle_upper_bound) {\n Ordering::Less => {\n matches.push(entry.clone());\n if matches.len() >= 5 {\n break 'outer; // Limit to 5 suggestions\n }\n }\n // We're looking for suggestions, not for matches.\n Ordering::Equal => {}\n // No more matches possible.\n Ordering::Greater => break,\n }\n }\n }\n }\n\n state.file_picker_autocomplete = matches;\n}\n"], ["/edit/src/buffer/navigation.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Range;\n\nuse crate::document::ReadableDocument;\n\n#[derive(Clone, Copy, PartialEq, Eq)]\nenum CharClass {\n Whitespace,\n Newline,\n Separator,\n Word,\n}\n\nconst fn construct_classifier(separators: &[u8]) -> [CharClass; 256] {\n let mut classifier = [CharClass::Word; 256];\n\n classifier[b' ' as usize] = CharClass::Whitespace;\n classifier[b'\\t' as usize] = CharClass::Whitespace;\n classifier[b'\\n' as usize] = CharClass::Newline;\n classifier[b'\\r' as usize] = CharClass::Newline;\n\n let mut i = 0;\n let len = separators.len();\n while i < len {\n let ch = separators[i];\n assert!(ch < 128, \"Only ASCII separators are supported.\");\n classifier[ch as usize] = CharClass::Separator;\n i += 1;\n }\n\n classifier\n}\n\nconst WORD_CLASSIFIER: [CharClass; 256] =\n construct_classifier(br#\"`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?\"#);\n\n/// Finds the next word boundary given a document cursor offset.\n/// Returns the offset of the next word boundary.\npub fn word_forward(doc: &dyn ReadableDocument, offset: usize) -> usize {\n word_navigation(WordForward { doc, offset, chunk: &[], chunk_off: 0 })\n}\n\n/// The backward version of `word_forward`.\npub fn word_backward(doc: &dyn ReadableDocument, offset: usize) -> usize {\n word_navigation(WordBackward { doc, offset, chunk: &[], chunk_off: 0 })\n}\n\n/// Word navigation implementation. Matches the behavior of VS Code.\nfn word_navigation(mut nav: T) -> usize {\n // First, fill `self.chunk` with at least 1 grapheme.\n nav.read();\n\n // Skip one newline, if any.\n nav.skip_newline();\n\n // Skip any whitespace.\n nav.skip_class(CharClass::Whitespace);\n\n // Skip one word or separator and take note of the class.\n let class = nav.peek(CharClass::Whitespace);\n if matches!(class, CharClass::Separator | CharClass::Word) {\n nav.next();\n\n let off = nav.offset();\n\n // Continue skipping the same class.\n nav.skip_class(class);\n\n // If the class was a separator and we only moved one character,\n // continue skipping characters of the word class.\n if off == nav.offset() && class == CharClass::Separator {\n nav.skip_class(CharClass::Word);\n }\n }\n\n nav.offset()\n}\n\ntrait WordNavigation {\n fn read(&mut self);\n fn skip_newline(&mut self);\n fn skip_class(&mut self, class: CharClass);\n fn peek(&self, default: CharClass) -> CharClass;\n fn next(&mut self);\n fn offset(&self) -> usize;\n}\n\nstruct WordForward<'a> {\n doc: &'a dyn ReadableDocument,\n offset: usize,\n chunk: &'a [u8],\n chunk_off: usize,\n}\n\nimpl WordNavigation for WordForward<'_> {\n fn read(&mut self) {\n self.chunk = self.doc.read_forward(self.offset);\n self.chunk_off = 0;\n }\n\n fn skip_newline(&mut self) {\n // We can rely on the fact that the document does not split graphemes across chunks.\n // = If there's a newline it's wholly contained in this chunk.\n // Unlike with `WordBackward`, we can't check for CR and LF separately as only a CR followed\n // by a LF is a newline. A lone CR in the document is just a regular control character.\n self.chunk_off += match self.chunk.get(self.chunk_off) {\n Some(&b'\\n') => 1,\n Some(&b'\\r') if self.chunk.get(self.chunk_off + 1) == Some(&b'\\n') => 2,\n _ => 0,\n }\n }\n\n fn skip_class(&mut self, class: CharClass) {\n while !self.chunk.is_empty() {\n while self.chunk_off < self.chunk.len() {\n if WORD_CLASSIFIER[self.chunk[self.chunk_off] as usize] != class {\n return;\n }\n self.chunk_off += 1;\n }\n\n self.offset += self.chunk.len();\n self.chunk = self.doc.read_forward(self.offset);\n self.chunk_off = 0;\n }\n }\n\n fn peek(&self, default: CharClass) -> CharClass {\n if self.chunk_off < self.chunk.len() {\n WORD_CLASSIFIER[self.chunk[self.chunk_off] as usize]\n } else {\n default\n }\n }\n\n fn next(&mut self) {\n self.chunk_off += 1;\n }\n\n fn offset(&self) -> usize {\n self.offset + self.chunk_off\n }\n}\n\nstruct WordBackward<'a> {\n doc: &'a dyn ReadableDocument,\n offset: usize,\n chunk: &'a [u8],\n chunk_off: usize,\n}\n\nimpl WordNavigation for WordBackward<'_> {\n fn read(&mut self) {\n self.chunk = self.doc.read_backward(self.offset);\n self.chunk_off = self.chunk.len();\n }\n\n fn skip_newline(&mut self) {\n // We can rely on the fact that the document does not split graphemes across chunks.\n // = If there's a newline it's wholly contained in this chunk.\n if self.chunk_off > 0 && self.chunk[self.chunk_off - 1] == b'\\n' {\n self.chunk_off -= 1;\n }\n if self.chunk_off > 0 && self.chunk[self.chunk_off - 1] == b'\\r' {\n self.chunk_off -= 1;\n }\n }\n\n fn skip_class(&mut self, class: CharClass) {\n while !self.chunk.is_empty() {\n while self.chunk_off > 0 {\n if WORD_CLASSIFIER[self.chunk[self.chunk_off - 1] as usize] != class {\n return;\n }\n self.chunk_off -= 1;\n }\n\n self.offset -= self.chunk.len();\n self.chunk = self.doc.read_backward(self.offset);\n self.chunk_off = self.chunk.len();\n }\n }\n\n fn peek(&self, default: CharClass) -> CharClass {\n if self.chunk_off > 0 {\n WORD_CLASSIFIER[self.chunk[self.chunk_off - 1] as usize]\n } else {\n default\n }\n }\n\n fn next(&mut self) {\n self.chunk_off -= 1;\n }\n\n fn offset(&self) -> usize {\n self.offset - self.chunk.len() + self.chunk_off\n }\n}\n\n/// Returns the offset range of the \"word\" at the given offset.\n/// Does not cross newlines. Works similar to VS Code.\npub fn word_select(doc: &dyn ReadableDocument, offset: usize) -> Range {\n let mut beg = offset;\n let mut end = offset;\n let mut class = CharClass::Newline;\n\n let mut chunk = doc.read_forward(end);\n if !chunk.is_empty() {\n // Not at the end of the document? Great!\n // We default to using the next char as the class, because in terminals\n // the cursor is usually always to the left of the cell you clicked on.\n class = WORD_CLASSIFIER[chunk[0] as usize];\n\n let mut chunk_off = 0;\n\n // Select the word, unless we hit a newline.\n if class != CharClass::Newline {\n loop {\n chunk_off += 1;\n end += 1;\n\n if chunk_off >= chunk.len() {\n chunk = doc.read_forward(end);\n chunk_off = 0;\n if chunk.is_empty() {\n break;\n }\n }\n\n if WORD_CLASSIFIER[chunk[chunk_off] as usize] != class {\n break;\n }\n }\n }\n }\n\n let mut chunk = doc.read_backward(beg);\n if !chunk.is_empty() {\n let mut chunk_off = chunk.len();\n\n // If we failed to determine the class, because we hit the end of the document\n // or a newline, we fall back to using the previous character, of course.\n if class == CharClass::Newline {\n class = WORD_CLASSIFIER[chunk[chunk_off - 1] as usize];\n }\n\n // Select the word, unless we hit a newline.\n if class != CharClass::Newline {\n loop {\n if WORD_CLASSIFIER[chunk[chunk_off - 1] as usize] != class {\n break;\n }\n\n chunk_off -= 1;\n beg -= 1;\n\n if chunk_off == 0 {\n chunk = doc.read_backward(beg);\n chunk_off = chunk.len();\n if chunk.is_empty() {\n break;\n }\n }\n }\n }\n }\n\n beg..end\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn test_word_navigation() {\n assert_eq!(word_forward(&\"Hello World\".as_bytes(), 0), 5);\n assert_eq!(word_forward(&\"Hello,World\".as_bytes(), 0), 5);\n assert_eq!(word_forward(&\" Hello\".as_bytes(), 0), 8);\n assert_eq!(word_forward(&\"\\n\\nHello\".as_bytes(), 0), 1);\n\n assert_eq!(word_backward(&\"Hello World\".as_bytes(), 11), 6);\n assert_eq!(word_backward(&\"Hello,World\".as_bytes(), 10), 6);\n assert_eq!(word_backward(&\"Hello \".as_bytes(), 7), 0);\n assert_eq!(word_backward(&\"Hello\\n\\n\".as_bytes(), 7), 6);\n }\n}\n"], ["/edit/src/simd/memchr2.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! `memchr`, but with two needles.\n\nuse std::ptr;\n\n/// `memchr`, but with two needles.\n///\n/// Returns the index of the first occurrence of either needle in the\n/// `haystack`. If no needle is found, `haystack.len()` is returned.\n/// `offset` specifies the index to start searching from.\npub fn memchr2(needle1: u8, needle2: u8, haystack: &[u8], offset: usize) -> usize {\n unsafe {\n let beg = haystack.as_ptr();\n let end = beg.add(haystack.len());\n let it = beg.add(offset.min(haystack.len()));\n let it = memchr2_raw(needle1, needle2, it, end);\n it.offset_from_unsigned(beg)\n }\n}\n\nunsafe fn memchr2_raw(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { MEMCHR2_DISPATCH(needle1, needle2, beg, end) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { memchr2_neon(needle1, needle2, beg, end) };\n\n #[allow(unreachable_code)]\n return unsafe { memchr2_fallback(needle1, needle2, beg, end) };\n}\n\nunsafe fn memchr2_fallback(\n needle1: u8,\n needle2: u8,\n mut beg: *const u8,\n end: *const u8,\n) -> *const u8 {\n unsafe {\n while !ptr::eq(beg, end) {\n let ch = *beg;\n if ch == needle1 || ch == needle2 {\n break;\n }\n beg = beg.add(1);\n }\n beg\n }\n}\n\n// In order to make `memchr2_raw` slim and fast, we use a function pointer that updates\n// itself to the correct implementation on the first call. This reduces binary size.\n// It would also reduce branches if we had >2 implementations (a jump still needs to be predicted).\n// NOTE that this ONLY works if Control Flow Guard is disabled on Windows.\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut MEMCHR2_DISPATCH: unsafe fn(\n needle1: u8,\n needle2: u8,\n beg: *const u8,\n end: *const u8,\n) -> *const u8 = memchr2_dispatch;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nunsafe fn memchr2_dispatch(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n let func = if is_x86_feature_detected!(\"avx2\") { memchr2_avx2 } else { memchr2_fallback };\n unsafe { MEMCHR2_DISPATCH = func };\n unsafe { func(needle1, needle2, beg, end) }\n}\n\n// FWIW, I found that adding support for AVX512 was not useful at the time,\n// as it only marginally improved file load performance by <5%.\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"avx2\")]\nunsafe fn memchr2_avx2(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n\n let n1 = _mm256_set1_epi8(needle1 as i8);\n let n2 = _mm256_set1_epi8(needle2 as i8);\n let mut remaining = end.offset_from_unsigned(beg);\n\n while remaining >= 32 {\n let v = _mm256_loadu_si256(beg as *const _);\n let a = _mm256_cmpeq_epi8(v, n1);\n let b = _mm256_cmpeq_epi8(v, n2);\n let c = _mm256_or_si256(a, b);\n let m = _mm256_movemask_epi8(c) as u32;\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(32);\n remaining -= 32;\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn memchr2_dispatch(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n memchr2_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n memchr2_lsx\n } else {\n memchr2_fallback\n };\n unsafe { MEMCHR2_DISPATCH = func };\n unsafe { func(needle1, needle2, beg, end) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn memchr2_lasx(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let n1 = lasx_xvreplgr2vr_b(needle1 as i32);\n let n2 = lasx_xvreplgr2vr_b(needle2 as i32);\n\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n beg = memchr2_lsx(needle1, needle2, beg, beg.add(off));\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = lasx_xvld::<0>(beg as *const _);\n let a = lasx_xvseq_b(v, n1);\n let b = lasx_xvseq_b(v, n2);\n let c = lasx_xvor_v(T(a), T(b));\n let m = lasx_xvmskltz_b(T(c));\n let l = lasx_xvpickve2gr_wu::<0>(T(m));\n let h = lasx_xvpickve2gr_wu::<4>(T(m));\n let m = (h << 16) | l;\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(32);\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn memchr2_lsx(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let n1 = lsx_vreplgr2vr_b(needle1 as i32);\n let n2 = lsx_vreplgr2vr_b(needle2 as i32);\n\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n beg = memchr2_fallback(needle1, needle2, beg, beg.add(off));\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = lsx_vld::<0>(beg as *const _);\n let a = lsx_vseq_b(v, n1);\n let b = lsx_vseq_b(v, n2);\n let c = lsx_vor_v(T(a), T(b));\n let m = lsx_vmskltz_b(T(c));\n let m = lsx_vpickve2gr_wu::<0>(T(m));\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(16);\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn memchr2_neon(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::aarch64::*;\n\n if end.offset_from_unsigned(beg) >= 16 {\n let n1 = vdupq_n_u8(needle1);\n let n2 = vdupq_n_u8(needle2);\n\n loop {\n let v = vld1q_u8(beg as *const _);\n let a = vceqq_u8(v, n1);\n let b = vceqq_u8(v, n2);\n let c = vorrq_u8(a, b);\n\n // https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon\n let m = vreinterpretq_u16_u8(c);\n let m = vshrn_n_u16(m, 4);\n let m = vreinterpret_u64_u8(m);\n let m = vget_lane_u64(m, 0);\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize >> 2);\n }\n\n beg = beg.add(16);\n if end.offset_from_unsigned(beg) < 16 {\n break;\n }\n }\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::slice;\n\n use super::*;\n use crate::sys;\n\n #[test]\n fn test_empty() {\n assert_eq!(memchr2(b'a', b'b', b\"\", 0), 0);\n }\n\n #[test]\n fn test_basic() {\n let haystack = b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n let haystack = &haystack[..43];\n\n assert_eq!(memchr2(b'a', b'z', haystack, 0), 0);\n assert_eq!(memchr2(b'p', b'q', haystack, 0), 15);\n assert_eq!(memchr2(b'Q', b'Z', haystack, 0), 42);\n assert_eq!(memchr2(b'0', b'9', haystack, 0), haystack.len());\n }\n\n // Test that it doesn't match before/after the start offset respectively.\n #[test]\n fn test_with_offset() {\n let haystack = b\"abcdefghabcdefghabcdefghabcdefghabcdefgh\";\n\n assert_eq!(memchr2(b'a', b'b', haystack, 0), 0);\n assert_eq!(memchr2(b'a', b'b', haystack, 1), 1);\n assert_eq!(memchr2(b'a', b'b', haystack, 2), 8);\n assert_eq!(memchr2(b'a', b'b', haystack, 9), 9);\n assert_eq!(memchr2(b'a', b'b', haystack, 16), 16);\n assert_eq!(memchr2(b'a', b'b', haystack, 41), 40);\n }\n\n // Test memory access safety at page boundaries.\n // The test is a success if it doesn't segfault.\n #[test]\n fn test_page_boundary() {\n let page = unsafe {\n const PAGE_SIZE: usize = 64 * 1024; // 64 KiB to cover many architectures.\n\n // 3 pages: uncommitted, committed, uncommitted\n let ptr = sys::virtual_reserve(PAGE_SIZE * 3).unwrap();\n sys::virtual_commit(ptr.add(PAGE_SIZE), PAGE_SIZE).unwrap();\n slice::from_raw_parts_mut(ptr.add(PAGE_SIZE).as_ptr(), PAGE_SIZE)\n };\n\n page.fill(b'a');\n\n // Test if it seeks beyond the page boundary.\n assert_eq!(memchr2(b'\\0', b'\\0', &page[page.len() - 40..], 0), 40);\n // Test if it seeks before the page boundary for the masked/partial load.\n assert_eq!(memchr2(b'\\0', b'\\0', &page[..10], 0), 10);\n }\n}\n"], ["/edit/src/helpers.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Random assortment of helpers I didn't know where to put.\n\nuse std::alloc::Allocator;\nuse std::cmp::Ordering;\nuse std::io::Read;\nuse std::mem::{self, MaybeUninit};\nuse std::ops::{Bound, Range, RangeBounds};\nuse std::{fmt, ptr, slice, str};\n\nuse crate::apperr;\n\npub const KILO: usize = 1000;\npub const MEGA: usize = 1000 * 1000;\npub const GIGA: usize = 1000 * 1000 * 1000;\n\npub const KIBI: usize = 1024;\npub const MEBI: usize = 1024 * 1024;\npub const GIBI: usize = 1024 * 1024 * 1024;\n\npub struct MetricFormatter(pub T);\n\nimpl fmt::Display for MetricFormatter {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let mut value = self.0;\n let mut suffix = \"B\";\n if value >= GIGA {\n value /= GIGA;\n suffix = \"GB\";\n } else if value >= MEGA {\n value /= MEGA;\n suffix = \"MB\";\n } else if value >= KILO {\n value /= KILO;\n suffix = \"kB\";\n }\n write!(f, \"{value}{suffix}\")\n }\n}\n\n/// A viewport coordinate type used throughout the application.\npub type CoordType = isize;\n\n/// To avoid overflow issues because you're adding two [`CoordType::MAX`]\n/// values together, you can use [`COORD_TYPE_SAFE_MAX`] instead.\n///\n/// It equates to half the bits contained in [`CoordType`], which\n/// for instance is 32767 (0x7FFF) when [`CoordType`] is a [`i32`].\npub const COORD_TYPE_SAFE_MAX: CoordType = (1 << (CoordType::BITS / 2 - 1)) - 1;\n\n/// A 2D point. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Point {\n pub x: CoordType,\n pub y: CoordType,\n}\n\nimpl Point {\n pub const MIN: Self = Self { x: CoordType::MIN, y: CoordType::MIN };\n pub const MAX: Self = Self { x: CoordType::MAX, y: CoordType::MAX };\n}\n\nimpl PartialOrd for Point {\n fn partial_cmp(&self, other: &Self) -> Option {\n Some(self.cmp(other))\n }\n}\n\nimpl Ord for Point {\n fn cmp(&self, other: &Self) -> Ordering {\n self.y.cmp(&other.y).then(self.x.cmp(&other.x))\n }\n}\n\n/// A 2D size. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Size {\n pub width: CoordType,\n pub height: CoordType,\n}\n\nimpl Size {\n pub fn as_rect(&self) -> Rect {\n Rect { left: 0, top: 0, right: self.width, bottom: self.height }\n }\n}\n\n/// A 2D rectangle. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Rect {\n pub left: CoordType,\n pub top: CoordType,\n pub right: CoordType,\n pub bottom: CoordType,\n}\n\nimpl Rect {\n /// Mimics CSS's `padding` property where `padding: a` is `a a a a`.\n pub fn one(value: CoordType) -> Self {\n Self { left: value, top: value, right: value, bottom: value }\n }\n\n /// Mimics CSS's `padding` property where `padding: a b` is `a b a b`,\n /// and `a` is top/bottom and `b` is left/right.\n pub fn two(top_bottom: CoordType, left_right: CoordType) -> Self {\n Self { left: left_right, top: top_bottom, right: left_right, bottom: top_bottom }\n }\n\n /// Mimics CSS's `padding` property where `padding: a b c` is `a b c b`,\n /// and `a` is top, `b` is left/right, and `c` is bottom.\n pub fn three(top: CoordType, left_right: CoordType, bottom: CoordType) -> Self {\n Self { left: left_right, top, right: left_right, bottom }\n }\n\n /// Is the rectangle empty?\n pub fn is_empty(&self) -> bool {\n self.left >= self.right || self.top >= self.bottom\n }\n\n /// Width of the rectangle.\n pub fn width(&self) -> CoordType {\n self.right - self.left\n }\n\n /// Height of the rectangle.\n pub fn height(&self) -> CoordType {\n self.bottom - self.top\n }\n\n /// Check if it contains a point.\n pub fn contains(&self, point: Point) -> bool {\n point.x >= self.left && point.x < self.right && point.y >= self.top && point.y < self.bottom\n }\n\n /// Intersect two rectangles.\n pub fn intersect(&self, rhs: Self) -> Self {\n let l = self.left.max(rhs.left);\n let t = self.top.max(rhs.top);\n let r = self.right.min(rhs.right);\n let b = self.bottom.min(rhs.bottom);\n\n // Ensure that the size is non-negative. This avoids bugs,\n // because some height/width is negative all of a sudden.\n let r = l.max(r);\n let b = t.max(b);\n\n Self { left: l, top: t, right: r, bottom: b }\n }\n}\n\n/// [`std::cmp::minmax`] is unstable, as per usual.\npub fn minmax(v1: T, v2: T) -> [T; 2]\nwhere\n T: Ord,\n{\n if v2 < v1 { [v2, v1] } else { [v1, v2] }\n}\n\n#[inline(always)]\n#[allow(clippy::ptr_eq)]\nfn opt_ptr(a: Option<&T>) -> *const T {\n unsafe { mem::transmute(a) }\n}\n\n/// Surprisingly, there's no way in Rust to do a `ptr::eq` on `Option<&T>`.\n/// Uses `unsafe` so that the debug performance isn't too bad.\n#[inline(always)]\n#[allow(clippy::ptr_eq)]\npub fn opt_ptr_eq(a: Option<&T>, b: Option<&T>) -> bool {\n opt_ptr(a) == opt_ptr(b)\n}\n\n/// Creates a `&str` from a pointer and a length.\n/// Exists, because `std::str::from_raw_parts` is unstable, par for the course.\n///\n/// # Safety\n///\n/// The given data must be valid UTF-8.\n/// The given data must outlive the returned reference.\n#[inline]\n#[must_use]\npub const unsafe fn str_from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str {\n unsafe { str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) }\n}\n\n/// [`<[T]>::copy_from_slice`] panics if the two slices have different lengths.\n/// This one just returns the copied amount.\npub fn slice_copy_safe(dst: &mut [T], src: &[T]) -> usize {\n let len = src.len().min(dst.len());\n unsafe { ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len) };\n len\n}\n\n/// [`Vec::splice`] results in really bad assembly.\n/// This doesn't. Don't use [`Vec::splice`].\npub trait ReplaceRange {\n fn replace_range>(&mut self, range: R, src: &[T]);\n}\n\nimpl ReplaceRange for Vec {\n fn replace_range>(&mut self, range: R, src: &[T]) {\n let start = match range.start_bound() {\n Bound::Included(&start) => start,\n Bound::Excluded(start) => start + 1,\n Bound::Unbounded => 0,\n };\n let end = match range.end_bound() {\n Bound::Included(end) => end + 1,\n Bound::Excluded(&end) => end,\n Bound::Unbounded => usize::MAX,\n };\n vec_replace_impl(self, start..end, src);\n }\n}\n\nfn vec_replace_impl(dst: &mut Vec, range: Range, src: &[T]) {\n unsafe {\n let dst_len = dst.len();\n let src_len = src.len();\n let off = range.start.min(dst_len);\n let del_len = range.end.saturating_sub(off).min(dst_len - off);\n\n if del_len == 0 && src_len == 0 {\n return; // nothing to do\n }\n\n let tail_len = dst_len - off - del_len;\n let new_len = dst_len - del_len + src_len;\n\n if src_len > del_len {\n dst.reserve(src_len - del_len);\n }\n\n // NOTE: drop_in_place() is not needed here, because T is constrained to Copy.\n\n // SAFETY: as_mut_ptr() must called after reserve() to ensure that the pointer is valid.\n let ptr = dst.as_mut_ptr().add(off);\n\n // Shift the tail.\n if tail_len > 0 && src_len != del_len {\n ptr::copy(ptr.add(del_len), ptr.add(src_len), tail_len);\n }\n\n // Copy in the replacement.\n ptr::copy_nonoverlapping(src.as_ptr(), ptr, src_len);\n dst.set_len(new_len);\n }\n}\n\n/// [`Read`] but with [`MaybeUninit`] buffers.\npub fn file_read_uninit(\n file: &mut T,\n buf: &mut [MaybeUninit],\n) -> apperr::Result {\n unsafe {\n let buf_slice = slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, buf.len());\n let n = file.read(buf_slice)?;\n Ok(n)\n }\n}\n\n/// Turns a [`&[u8]`] into a [`&[MaybeUninit]`].\n#[inline(always)]\npub const fn slice_as_uninit_ref(slice: &[T]) -> &[MaybeUninit] {\n unsafe { slice::from_raw_parts(slice.as_ptr() as *const MaybeUninit, slice.len()) }\n}\n\n/// Turns a [`&mut [T]`] into a [`&mut [MaybeUninit]`].\n#[inline(always)]\npub const fn slice_as_uninit_mut(slice: &mut [T]) -> &mut [MaybeUninit] {\n unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut MaybeUninit, slice.len()) }\n}\n\n/// Helpers for ASCII string comparisons.\npub trait AsciiStringHelpers {\n /// Tests if a string starts with a given ASCII prefix.\n ///\n /// This function name really is a mouthful, but it's a combination\n /// of [`str::starts_with`] and [`str::eq_ignore_ascii_case`].\n fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool;\n}\n\nimpl AsciiStringHelpers for str {\n fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool {\n // Casting to bytes first ensures we skip any UTF8 boundary checks.\n // Since the comparison is ASCII, we don't need to worry about that.\n let s = self.as_bytes();\n let p = prefix.as_bytes();\n p.len() <= s.len() && s[..p.len()].eq_ignore_ascii_case(p)\n }\n}\n"], ["/edit/src/buffer/gap_buffer.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Range;\nuse std::ptr::{self, NonNull};\nuse std::slice;\n\nuse crate::document::{ReadableDocument, WriteableDocument};\nuse crate::helpers::*;\nuse crate::{apperr, sys};\n\n#[cfg(target_pointer_width = \"32\")]\nconst LARGE_CAPACITY: usize = 128 * MEBI;\n#[cfg(target_pointer_width = \"64\")]\nconst LARGE_CAPACITY: usize = 4 * GIBI;\nconst LARGE_ALLOC_CHUNK: usize = 64 * KIBI;\nconst LARGE_GAP_CHUNK: usize = 4 * KIBI;\n\nconst SMALL_CAPACITY: usize = 128 * KIBI;\nconst SMALL_ALLOC_CHUNK: usize = 256;\nconst SMALL_GAP_CHUNK: usize = 16;\n\n// TODO: Instead of having a specialization for small buffers here,\n// tui.rs could also just keep a MRU set of large buffers around.\nenum BackingBuffer {\n VirtualMemory(NonNull, usize),\n Vec(Vec),\n}\n\nimpl Drop for BackingBuffer {\n fn drop(&mut self) {\n unsafe {\n if let Self::VirtualMemory(ptr, reserve) = *self {\n sys::virtual_release(ptr, reserve);\n }\n }\n }\n}\n\n/// Most people know how `Vec` works: It has some spare capacity at the end,\n/// so that pushing into it doesn't reallocate every single time. A gap buffer\n/// is the same thing, but the spare capacity can be anywhere in the buffer.\n/// This variant is optimized for large buffers and uses virtual memory.\npub struct GapBuffer {\n /// Pointer to the buffer.\n text: NonNull,\n /// Maximum size of the buffer, including gap.\n reserve: usize,\n /// Size of the buffer, including gap.\n commit: usize,\n /// Length of the stored text, NOT including gap.\n text_length: usize,\n /// Gap offset.\n gap_off: usize,\n /// Gap length.\n gap_len: usize,\n /// Increments every time the buffer is modified.\n generation: u32,\n /// If `Vec(..)`, the buffer is optimized for small amounts of text\n /// and uses the standard heap. Otherwise, it uses virtual memory.\n buffer: BackingBuffer,\n}\n\nimpl GapBuffer {\n pub fn new(small: bool) -> apperr::Result {\n let reserve;\n let buffer;\n let text;\n\n if small {\n reserve = SMALL_CAPACITY;\n text = NonNull::dangling();\n buffer = BackingBuffer::Vec(Vec::new());\n } else {\n reserve = LARGE_CAPACITY;\n text = unsafe { sys::virtual_reserve(reserve)? };\n buffer = BackingBuffer::VirtualMemory(text, reserve);\n }\n\n Ok(Self {\n text,\n reserve,\n commit: 0,\n text_length: 0,\n gap_off: 0,\n gap_len: 0,\n generation: 0,\n buffer,\n })\n }\n\n #[allow(clippy::len_without_is_empty)]\n pub fn len(&self) -> usize {\n self.text_length\n }\n\n pub fn generation(&self) -> u32 {\n self.generation\n }\n\n pub fn set_generation(&mut self, generation: u32) {\n self.generation = generation;\n }\n\n /// WARNING: The returned slice must not necessarily be the same length as `len` (due to OOM).\n pub fn allocate_gap(&mut self, off: usize, len: usize, delete: usize) -> &mut [u8] {\n // Sanitize parameters\n let off = off.min(self.text_length);\n let delete = delete.min(self.text_length - off);\n\n // Move the existing gap if it exists\n if off != self.gap_off {\n self.move_gap(off);\n }\n\n // Delete the text\n if delete > 0 {\n self.delete_text(delete);\n }\n\n // Enlarge the gap if needed\n if len > self.gap_len {\n self.enlarge_gap(len);\n }\n\n self.generation = self.generation.wrapping_add(1);\n unsafe { slice::from_raw_parts_mut(self.text.add(self.gap_off).as_ptr(), self.gap_len) }\n }\n\n fn move_gap(&mut self, off: usize) {\n if self.gap_len > 0 {\n //\n // v gap_off\n // left: |ABCDEFGHIJKLMN OPQRSTUVWXYZ|\n // |ABCDEFGHI JKLMNOPQRSTUVWXYZ|\n // ^ off\n // move: JKLMN\n //\n // v gap_off\n // !left: |ABCDEFGHIJKLMN OPQRSTUVWXYZ|\n // |ABCDEFGHIJKLMNOPQRS TUVWXYZ|\n // ^ off\n // move: OPQRS\n //\n let left = off < self.gap_off;\n let move_src = if left { off } else { self.gap_off + self.gap_len };\n let move_dst = if left { off + self.gap_len } else { self.gap_off };\n let move_len = if left { self.gap_off - off } else { off - self.gap_off };\n\n unsafe { self.text.add(move_src).copy_to(self.text.add(move_dst), move_len) };\n\n if cfg!(debug_assertions) {\n // Fill the moved-out bytes with 0xCD to make debugging easier.\n unsafe { self.text.add(off).write_bytes(0xCD, self.gap_len) };\n }\n }\n\n self.gap_off = off;\n }\n\n fn delete_text(&mut self, delete: usize) {\n if cfg!(debug_assertions) {\n // Fill the deleted bytes with 0xCD to make debugging easier.\n unsafe { self.text.add(self.gap_off + self.gap_len).write_bytes(0xCD, delete) };\n }\n\n self.gap_len += delete;\n self.text_length -= delete;\n }\n\n fn enlarge_gap(&mut self, len: usize) {\n let gap_chunk;\n let alloc_chunk;\n\n if matches!(self.buffer, BackingBuffer::VirtualMemory(..)) {\n gap_chunk = LARGE_GAP_CHUNK;\n alloc_chunk = LARGE_ALLOC_CHUNK;\n } else {\n gap_chunk = SMALL_GAP_CHUNK;\n alloc_chunk = SMALL_ALLOC_CHUNK;\n }\n\n let gap_len_old = self.gap_len;\n let gap_len_new = (len + gap_chunk + gap_chunk - 1) & !(gap_chunk - 1);\n\n let bytes_old = self.commit;\n let bytes_new = self.text_length + gap_len_new;\n\n if bytes_new > bytes_old {\n let bytes_new = (bytes_new + alloc_chunk - 1) & !(alloc_chunk - 1);\n\n if bytes_new > self.reserve {\n return;\n }\n\n match &mut self.buffer {\n BackingBuffer::VirtualMemory(ptr, _) => unsafe {\n if sys::virtual_commit(ptr.add(bytes_old), bytes_new - bytes_old).is_err() {\n return;\n }\n },\n BackingBuffer::Vec(v) => {\n v.resize(bytes_new, 0);\n self.text = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };\n }\n }\n\n self.commit = bytes_new;\n }\n\n let gap_beg = unsafe { self.text.add(self.gap_off) };\n unsafe {\n ptr::copy(\n gap_beg.add(gap_len_old).as_ptr(),\n gap_beg.add(gap_len_new).as_ptr(),\n self.text_length - self.gap_off,\n )\n };\n\n if cfg!(debug_assertions) {\n // Fill the moved-out bytes with 0xCD to make debugging easier.\n unsafe { gap_beg.add(gap_len_old).write_bytes(0xCD, gap_len_new - gap_len_old) };\n }\n\n self.gap_len = gap_len_new;\n }\n\n pub fn commit_gap(&mut self, len: usize) {\n assert!(len <= self.gap_len);\n self.text_length += len;\n self.gap_off += len;\n self.gap_len -= len;\n }\n\n pub fn replace(&mut self, range: Range, src: &[u8]) {\n let gap = self.allocate_gap(range.start, src.len(), range.end.saturating_sub(range.start));\n let len = slice_copy_safe(gap, src);\n self.commit_gap(len);\n }\n\n pub fn clear(&mut self) {\n self.gap_off = 0;\n self.gap_len += self.text_length;\n self.generation = self.generation.wrapping_add(1);\n self.text_length = 0;\n }\n\n pub fn extract_raw(&self, range: Range, out: &mut Vec, mut out_off: usize) {\n let end = range.end.min(self.text_length);\n let mut beg = range.start.min(end);\n out_off = out_off.min(out.len());\n\n if beg >= end {\n return;\n }\n\n out.reserve(end - beg);\n\n while beg < end {\n let chunk = self.read_forward(beg);\n let chunk = &chunk[..chunk.len().min(end - beg)];\n out.replace_range(out_off..out_off, chunk);\n beg += chunk.len();\n out_off += chunk.len();\n }\n }\n\n /// Replaces the entire buffer contents with the given `text`.\n /// The method is optimized for the case where the given `text` already matches\n /// the existing contents. Returns `true` if the buffer contents were changed.\n pub fn copy_from(&mut self, src: &dyn ReadableDocument) -> bool {\n let mut off = 0;\n\n // Find the position at which the contents change.\n loop {\n let dst_chunk = self.read_forward(off);\n let src_chunk = src.read_forward(off);\n\n let dst_len = dst_chunk.len();\n let src_len = src_chunk.len();\n let len = dst_len.min(src_len);\n let mismatch = dst_chunk[..len] != src_chunk[..len];\n\n if mismatch {\n break; // The contents differ.\n }\n if len == 0 {\n if dst_len == src_len {\n return false; // Both done simultaneously. -> Done.\n }\n break; // One of the two is shorter.\n }\n\n off += len;\n }\n\n // Update the buffer starting at `off`.\n loop {\n let chunk = src.read_forward(off);\n self.replace(off..usize::MAX, chunk);\n off += chunk.len();\n\n // No more data to copy -> Done. By checking this _after_ the replace()\n // call, we ensure that the initial `off..usize::MAX` range is deleted.\n // This fixes going from some buffer contents to being empty.\n if chunk.is_empty() {\n return true;\n }\n }\n }\n\n /// Copies the contents of the buffer into a string.\n pub fn copy_into(&self, dst: &mut dyn WriteableDocument) {\n let mut beg = 0;\n let mut off = 0;\n\n while {\n let chunk = self.read_forward(off);\n\n // The first write will be 0..usize::MAX and effectively clear() the destination.\n // Every subsequent write will be usize::MAX..usize::MAX and thus effectively append().\n dst.replace(beg..usize::MAX, chunk);\n beg = usize::MAX;\n\n off += chunk.len();\n off < self.text_length\n } {}\n }\n}\n\nimpl ReadableDocument for GapBuffer {\n fn read_forward(&self, off: usize) -> &[u8] {\n let off = off.min(self.text_length);\n let beg;\n let len;\n\n if off < self.gap_off {\n // Cursor is before the gap: We can read until the start of the gap.\n beg = off;\n len = self.gap_off - off;\n } else {\n // Cursor is after the gap: We can read until the end of the buffer.\n beg = off + self.gap_len;\n len = self.text_length - off;\n }\n\n unsafe { slice::from_raw_parts(self.text.add(beg).as_ptr(), len) }\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let off = off.min(self.text_length);\n let beg;\n let len;\n\n if off <= self.gap_off {\n // Cursor is before the gap: We can read until the beginning of the buffer.\n beg = 0;\n len = off;\n } else {\n // Cursor is after the gap: We can read until the end of the gap.\n beg = self.gap_off + self.gap_len;\n // The cursor_off doesn't account of the gap_len.\n // (This allows us to move the gap without recalculating the cursor position.)\n len = off - self.gap_off;\n }\n\n unsafe { slice::from_raw_parts(self.text.add(beg).as_ptr(), len) }\n }\n}\n"], ["/edit/src/unicode/utf8.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::{hint, iter};\n\n/// An iterator over UTF-8 encoded characters.\n///\n/// This differs from [`std::str::Chars`] in that it works on unsanitized\n/// byte slices and transparently replaces invalid UTF-8 sequences with U+FFFD.\n///\n/// This follows ICU's bitmask approach for `U8_NEXT_OR_FFFD` relatively\n/// closely. This is important for compatibility, because it implements the\n/// WHATWG recommendation for UTF8 error recovery. It's also helpful, because\n/// the excellent folks at ICU have probably spent a lot of time optimizing it.\n#[derive(Clone, Copy)]\npub struct Utf8Chars<'a> {\n source: &'a [u8],\n offset: usize,\n}\n\nimpl<'a> Utf8Chars<'a> {\n /// Creates a new `Utf8Chars` iterator starting at the given `offset`.\n pub fn new(source: &'a [u8], offset: usize) -> Self {\n Self { source, offset }\n }\n\n /// Returns the byte slice this iterator was created with.\n pub fn source(&self) -> &'a [u8] {\n self.source\n }\n\n /// Checks if the source is empty.\n pub fn is_empty(&self) -> bool {\n self.source.is_empty()\n }\n\n /// Returns the length of the source.\n pub fn len(&self) -> usize {\n self.source.len()\n }\n\n /// Returns the current offset in the byte slice.\n ///\n /// This will be past the last returned character.\n pub fn offset(&self) -> usize {\n self.offset\n }\n\n /// Sets the offset to continue iterating from.\n pub fn seek(&mut self, offset: usize) {\n self.offset = offset;\n }\n\n /// Returns true if `next` will return another character.\n pub fn has_next(&self) -> bool {\n self.offset < self.source.len()\n }\n\n // I found that on mixed 50/50 English/Non-English text,\n // performance actually suffers when this gets inlined.\n #[cold]\n fn next_slow(&mut self, c: u8) -> char {\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n\n let mut cp = c as u32;\n\n if cp < 0xE0 {\n // UTF8-2 = %xC2-DF UTF8-tail\n\n if cp < 0xC2 {\n return Self::fffd();\n }\n\n // The lead byte is 110xxxxx\n // -> Strip off the 110 prefix\n cp &= !0xE0;\n } else if cp < 0xF0 {\n // UTF8-3 =\n // %xE0 %xA0-BF UTF8-tail\n // %xE1-EC UTF8-tail UTF8-tail\n // %xED %x80-9F UTF8-tail\n // %xEE-EF UTF8-tail UTF8-tail\n\n // This is a pretty neat approach seen in ICU4C, because it's a 1:1 translation of the RFC.\n // I don't understand why others don't do the same thing. It's rather performant.\n const BITS_80_9F: u8 = 1 << 0b100; // 0x80-9F, aka 0b100xxxxx\n const BITS_A0_BF: u8 = 1 << 0b101; // 0xA0-BF, aka 0b101xxxxx\n const BITS_BOTH: u8 = BITS_80_9F | BITS_A0_BF;\n const LEAD_TRAIL1_BITS: [u8; 16] = [\n // v-- lead byte\n BITS_A0_BF, // 0xE0\n BITS_BOTH, // 0xE1\n BITS_BOTH, // 0xE2\n BITS_BOTH, // 0xE3\n BITS_BOTH, // 0xE4\n BITS_BOTH, // 0xE5\n BITS_BOTH, // 0xE6\n BITS_BOTH, // 0xE7\n BITS_BOTH, // 0xE8\n BITS_BOTH, // 0xE9\n BITS_BOTH, // 0xEA\n BITS_BOTH, // 0xEB\n BITS_BOTH, // 0xEC\n BITS_80_9F, // 0xED\n BITS_BOTH, // 0xEE\n BITS_BOTH, // 0xEF\n ];\n\n // The lead byte is 1110xxxx\n // -> Strip off the 1110 prefix\n cp &= !0xF0;\n\n let t = self.source[self.offset] as u32;\n if LEAD_TRAIL1_BITS[cp as usize] & (1 << (t >> 5)) == 0 {\n return Self::fffd();\n }\n cp = (cp << 6) | (t & 0x3F);\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n } else {\n // UTF8-4 =\n // %xF0 %x90-BF UTF8-tail UTF8-tail\n // %xF1-F3 UTF8-tail UTF8-tail UTF8-tail\n // %xF4 %x80-8F UTF8-tail UTF8-tail\n\n // This is similar to the above, but with the indices flipped:\n // The trail byte is the index and the lead byte mask is the value.\n // This is because the split at 0x90 requires more bits than fit into an u8.\n const TRAIL1_LEAD_BITS: [u8; 16] = [\n // --------- 0xF4 lead\n // | ...\n // | +---- 0xF0 lead\n // v v\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, // trail bytes:\n 0b_00000, //\n 0b_11110, // 0x80-8F -> 0x80-8F can be preceded by 0xF1-F4\n 0b_01111, // 0x90-9F -v\n 0b_01111, // 0xA0-AF -> 0x90-BF can be preceded by 0xF0-F3\n 0b_01111, // 0xB0-BF -^\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n ];\n\n // The lead byte *may* be 11110xxx, but could also be e.g. 11111xxx.\n // -> Only strip off the 1111 prefix\n cp &= !0xF0;\n\n // Now we can verify if it's actually <= 0xF4.\n // Curiously, this if condition does a lot of heavy lifting for\n // performance (+13%). I think it's just a coincidence though.\n if cp > 4 {\n return Self::fffd();\n }\n\n let t = self.source[self.offset] as u32;\n if TRAIL1_LEAD_BITS[(t >> 4) as usize] & (1 << cp) == 0 {\n return Self::fffd();\n }\n cp = (cp << 6) | (t & 0x3F);\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n\n // UTF8-tail = %x80-BF\n let t = (self.source[self.offset] as u32).wrapping_sub(0x80);\n if t > 0x3F {\n return Self::fffd();\n }\n cp = (cp << 6) | t;\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n }\n\n // SAFETY: All branches above check for `if self.offset >= self.source.len()`\n // one way or another. This is here because the compiler doesn't get it otherwise.\n unsafe { hint::assert_unchecked(self.offset < self.source.len()) };\n\n // UTF8-tail = %x80-BF\n let t = (self.source[self.offset] as u32).wrapping_sub(0x80);\n if t > 0x3F {\n return Self::fffd();\n }\n cp = (cp << 6) | t;\n\n self.offset += 1;\n\n // SAFETY: If `cp` wasn't a valid codepoint, we already returned U+FFFD above.\n unsafe { char::from_u32_unchecked(cp) }\n }\n\n // This simultaneously serves as a `cold_path` marker.\n // It improves performance by ~5% and reduces code size.\n #[cold]\n #[inline(always)]\n fn fffd() -> char {\n '\\u{FFFD}'\n }\n}\n\nimpl Iterator for Utf8Chars<'_> {\n type Item = char;\n\n #[inline]\n fn next(&mut self) -> Option {\n if self.offset >= self.source.len() {\n return None;\n }\n\n let c = self.source[self.offset];\n self.offset += 1;\n\n // Fast-passing ASCII allows this function to be trivially inlined everywhere,\n // as the full decoder is a little too large for that.\n if (c & 0x80) == 0 {\n // UTF8-1 = %x00-7F\n Some(c as char)\n } else {\n // Weirdly enough, adding a hint here to assert that `next_slow`\n // only returns codepoints >= 0x80 makes `ucd` ~5% slower.\n Some(self.next_slow(c))\n }\n }\n\n #[inline]\n fn size_hint(&self) -> (usize, Option) {\n // Lower bound: All remaining bytes are 4-byte sequences.\n // Upper bound: All remaining bytes are ASCII.\n let remaining = self.source.len() - self.offset;\n (remaining / 4, Some(remaining))\n }\n}\n\nimpl iter::FusedIterator for Utf8Chars<'_> {}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_broken_utf8() {\n let source = [b'a', 0xED, 0xA0, 0x80, b'b'];\n let mut chars = Utf8Chars::new(&source, 0);\n let mut offset = 0;\n for chunk in source.utf8_chunks() {\n for ch in chunk.valid().chars() {\n offset += ch.len_utf8();\n assert_eq!(chars.next(), Some(ch));\n assert_eq!(chars.offset(), offset);\n }\n if !chunk.invalid().is_empty() {\n offset += chunk.invalid().len();\n assert_eq!(chars.next(), Some('\\u{FFFD}'));\n assert_eq!(chars.offset(), offset);\n }\n }\n }\n}\n"], ["/edit/src/arena/string.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::fmt;\nuse std::ops::{Bound, Deref, DerefMut, RangeBounds};\n\nuse super::Arena;\nuse crate::helpers::*;\n\n/// A custom string type, because `std` lacks allocator support for [`String`].\n///\n/// To keep things simple, this one is hardcoded to [`Arena`].\n#[derive(Clone)]\npub struct ArenaString<'a> {\n vec: Vec,\n}\n\nimpl<'a> ArenaString<'a> {\n /// Creates a new [`ArenaString`] in the given arena.\n #[must_use]\n pub const fn new_in(arena: &'a Arena) -> Self {\n Self { vec: Vec::new_in(arena) }\n }\n\n #[must_use]\n pub fn with_capacity_in(capacity: usize, arena: &'a Arena) -> Self {\n Self { vec: Vec::with_capacity_in(capacity, arena) }\n }\n\n /// Turns a [`str`] into an [`ArenaString`].\n #[must_use]\n pub fn from_str(arena: &'a Arena, s: &str) -> Self {\n let mut res = Self::new_in(arena);\n res.push_str(s);\n res\n }\n\n /// It says right here that you checked if `bytes` is valid UTF-8\n /// and you are sure it is. Presto! Here's an `ArenaString`!\n ///\n /// # Safety\n ///\n /// You fool! It says \"unchecked\" right there. Now the house is burning.\n #[inline]\n #[must_use]\n pub unsafe fn from_utf8_unchecked(bytes: Vec) -> Self {\n Self { vec: bytes }\n }\n\n /// Checks whether `text` contains only valid UTF-8.\n /// If the entire string is valid, it returns `Ok(text)`.\n /// Otherwise, it returns `Err(ArenaString)` with all invalid sequences replaced with U+FFFD.\n pub fn from_utf8_lossy<'s>(arena: &'a Arena, text: &'s [u8]) -> Result<&'s str, Self> {\n let mut iter = text.utf8_chunks();\n let Some(mut chunk) = iter.next() else {\n return Ok(\"\");\n };\n\n let valid = chunk.valid();\n if chunk.invalid().is_empty() {\n debug_assert_eq!(valid.len(), text.len());\n return Ok(unsafe { str::from_utf8_unchecked(text) });\n }\n\n const REPLACEMENT: &str = \"\\u{FFFD}\";\n\n let mut res = Self::new_in(arena);\n res.reserve(text.len());\n\n loop {\n res.push_str(chunk.valid());\n if !chunk.invalid().is_empty() {\n res.push_str(REPLACEMENT);\n }\n chunk = match iter.next() {\n Some(chunk) => chunk,\n None => break,\n };\n }\n\n Err(res)\n }\n\n /// Turns a [`Vec`] into an [`ArenaString`], replacing invalid UTF-8 sequences with U+FFFD.\n #[must_use]\n pub fn from_utf8_lossy_owned(v: Vec) -> Self {\n match Self::from_utf8_lossy(v.allocator(), &v) {\n Ok(..) => unsafe { Self::from_utf8_unchecked(v) },\n Err(s) => s,\n }\n }\n\n /// It's empty.\n pub fn is_empty(&self) -> bool {\n self.vec.is_empty()\n }\n\n /// It's lengthy.\n pub fn len(&self) -> usize {\n self.vec.len()\n }\n\n /// It's capacatity.\n pub fn capacity(&self) -> usize {\n self.vec.capacity()\n }\n\n /// It's a [`String`], now it's a [`str`]. Wow!\n pub fn as_str(&self) -> &str {\n unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }\n }\n\n /// It's a [`String`], now it's a [`str`]. And it's mutable! WOW!\n pub fn as_mut_str(&mut self) -> &mut str {\n unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }\n }\n\n /// Now it's bytes!\n pub fn as_bytes(&self) -> &[u8] {\n self.vec.as_slice()\n }\n\n /// Returns a mutable reference to the contents of this `String`.\n ///\n /// # Safety\n ///\n /// The underlying `&mut Vec` allows writing bytes which are not valid UTF-8.\n pub unsafe fn as_mut_vec(&mut self) -> &mut Vec {\n &mut self.vec\n }\n\n /// Reserves *additional* memory. For you old folks out there (totally not me),\n /// this is different from C++'s `reserve` which reserves a total size.\n pub fn reserve(&mut self, additional: usize) {\n self.vec.reserve(additional)\n }\n\n /// Just like [`ArenaString::reserve`], but it doesn't overallocate.\n pub fn reserve_exact(&mut self, additional: usize) {\n self.vec.reserve_exact(additional)\n }\n\n /// Now it's small! Alarming!\n ///\n /// *Do not* call this unless this string is the last thing on the arena.\n /// Arenas are stacks, they can't deallocate what's in the middle.\n pub fn shrink_to_fit(&mut self) {\n self.vec.shrink_to_fit()\n }\n\n /// To no surprise, this clears the string.\n pub fn clear(&mut self) {\n self.vec.clear()\n }\n\n /// Append some text.\n pub fn push_str(&mut self, string: &str) {\n self.vec.extend_from_slice(string.as_bytes())\n }\n\n /// Append a single character.\n #[inline]\n pub fn push(&mut self, ch: char) {\n match ch.len_utf8() {\n 1 => self.vec.push(ch as u8),\n _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),\n }\n }\n\n /// Same as `push(char)` but with a specified number of character copies.\n /// Shockingly absent from the standard library.\n pub fn push_repeat(&mut self, ch: char, total_copies: usize) {\n if total_copies == 0 {\n return;\n }\n\n let buf = unsafe { self.as_mut_vec() };\n\n if ch.is_ascii() {\n // Compiles down to `memset()`.\n buf.extend(std::iter::repeat_n(ch as u8, total_copies));\n } else {\n // Implements efficient string padding using quadratic duplication.\n let mut utf8_buf = [0; 4];\n let utf8 = ch.encode_utf8(&mut utf8_buf).as_bytes();\n let initial_len = buf.len();\n let added_len = utf8.len() * total_copies;\n let final_len = initial_len + added_len;\n\n buf.reserve(added_len);\n buf.extend_from_slice(utf8);\n\n while buf.len() != final_len {\n let end = (final_len - buf.len() + initial_len).min(buf.len());\n buf.extend_from_within(initial_len..end);\n }\n }\n }\n\n /// Replaces a range of characters with a new string.\n pub fn replace_range>(&mut self, range: R, replace_with: &str) {\n match range.start_bound() {\n Bound::Included(&n) => assert!(self.is_char_boundary(n)),\n Bound::Excluded(&n) => assert!(self.is_char_boundary(n + 1)),\n Bound::Unbounded => {}\n };\n match range.end_bound() {\n Bound::Included(&n) => assert!(self.is_char_boundary(n + 1)),\n Bound::Excluded(&n) => assert!(self.is_char_boundary(n)),\n Bound::Unbounded => {}\n };\n unsafe { self.as_mut_vec() }.replace_range(range, replace_with.as_bytes());\n }\n\n /// Finds `old` in the string and replaces it with `new`.\n /// Only performs one replacement.\n pub fn replace_once_in_place(&mut self, old: &str, new: &str) {\n if let Some(beg) = self.find(old) {\n unsafe { self.as_mut_vec() }.replace_range(beg..beg + old.len(), new.as_bytes());\n }\n }\n}\n\nimpl fmt::Debug for ArenaString<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n fmt::Debug::fmt(&**self, f)\n }\n}\n\nimpl PartialEq<&str> for ArenaString<'_> {\n fn eq(&self, other: &&str) -> bool {\n self.as_str() == *other\n }\n}\n\nimpl Deref for ArenaString<'_> {\n type Target = str;\n\n fn deref(&self) -> &Self::Target {\n self.as_str()\n }\n}\n\nimpl DerefMut for ArenaString<'_> {\n fn deref_mut(&mut self) -> &mut Self::Target {\n self.as_mut_str()\n }\n}\n\nimpl fmt::Display for ArenaString<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.write_str(self.as_str())\n }\n}\n\nimpl fmt::Write for ArenaString<'_> {\n #[inline]\n fn write_str(&mut self, s: &str) -> fmt::Result {\n self.push_str(s);\n Ok(())\n }\n\n #[inline]\n fn write_char(&mut self, c: char) -> fmt::Result {\n self.push(c);\n Ok(())\n }\n}\n\n#[macro_export]\nmacro_rules! arena_format {\n ($arena:expr, $($arg:tt)*) => {{\n use std::fmt::Write as _;\n let mut output = $crate::arena::ArenaString::new_in($arena);\n output.write_fmt(format_args!($($arg)*)).unwrap();\n output\n }}\n}\n"], ["/edit/src/simd/lines_fwd.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ptr;\n\nuse crate::helpers::CoordType;\n\n/// Starting from the `offset` in `haystack` with a current line index of\n/// `line`, this seeks to the `line_stop`-nth line and returns the\n/// new offset and the line index at that point.\n///\n/// It returns an offset *past* the newline.\n/// If `line` is already at or past `line_stop`, it returns immediately.\npub fn lines_fwd(\n haystack: &[u8],\n offset: usize,\n line: CoordType,\n line_stop: CoordType,\n) -> (usize, CoordType) {\n unsafe {\n let beg = haystack.as_ptr();\n let end = beg.add(haystack.len());\n let it = beg.add(offset.min(haystack.len()));\n let (it, line) = lines_fwd_raw(it, end, line, line_stop);\n (it.offset_from_unsigned(beg), line)\n }\n}\n\nunsafe fn lines_fwd_raw(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n #[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { LINES_FWD_DISPATCH(beg, end, line, line_stop) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { lines_fwd_neon(beg, end, line, line_stop) };\n\n #[allow(unreachable_code)]\n return unsafe { lines_fwd_fallback(beg, end, line, line_stop) };\n}\n\nunsafe fn lines_fwd_fallback(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n if line < line_stop {\n while !ptr::eq(beg, end) {\n let c = *beg;\n beg = beg.add(1);\n if c == b'\\n' {\n line += 1;\n if line == line_stop {\n break;\n }\n }\n }\n }\n (beg, line)\n }\n}\n\n#[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut LINES_FWD_DISPATCH: unsafe fn(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) = lines_fwd_dispatch;\n\n#[cfg(target_arch = \"x86_64\")]\nunsafe fn lines_fwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n let func = if is_x86_feature_detected!(\"avx2\") { lines_fwd_avx2 } else { lines_fwd_fallback };\n unsafe { LINES_FWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"x86_64\")]\n#[target_feature(enable = \"avx2\")]\nunsafe fn lines_fwd_avx2(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::x86_64::*;\n\n #[inline(always)]\n unsafe fn horizontal_sum_i64(v: __m256i) -> i64 {\n unsafe {\n let hi = _mm256_extracti128_si256::<1>(v);\n let lo = _mm256_castsi256_si128(v);\n let sum = _mm_add_epi64(lo, hi);\n let shuf = _mm_shuffle_epi32::<0b11_10_11_10>(sum);\n let sum = _mm_add_epi64(sum, shuf);\n _mm_cvtsi128_si64(sum)\n }\n }\n\n let lf = _mm256_set1_epi8(b'\\n' as i8);\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n // Unrolling the loop by 4x speeds things up by >3x.\n // It allows us to accumulate matches before doing a single `vpsadbw`.\n while end.offset_from_unsigned(beg) >= 128 {\n let v1 = _mm256_loadu_si256(beg.add(0) as *const _);\n let v2 = _mm256_loadu_si256(beg.add(32) as *const _);\n let v3 = _mm256_loadu_si256(beg.add(64) as *const _);\n let v4 = _mm256_loadu_si256(beg.add(96) as *const _);\n\n // `vpcmpeqb` leaves each comparison result byte as 0 or -1 (0xff).\n // This allows us to accumulate the comparisons by subtracting them.\n let mut sum = _mm256_setzero_si256();\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v1, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v2, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v3, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v4, lf));\n\n // Calculate the total number of matches in this chunk.\n let sum = _mm256_sad_epu8(sum, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(128);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = _mm256_loadu_si256(beg as *const _);\n let c = _mm256_cmpeq_epi8(v, lf);\n\n // If you ask an LLM, the best way to do this is\n // to do a `vpmovmskb` followed by `popcnt`.\n // One contemporary hardware that's a bad idea though.\n let ones = _mm256_and_si256(c, _mm256_set1_epi8(0x01));\n let sum = _mm256_sad_epu8(ones, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(32);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn lines_fwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n lines_fwd_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n lines_fwd_lsx\n } else {\n lines_fwd_fallback\n };\n unsafe { LINES_FWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn lines_fwd_lasx(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v32i8) -> u32 {\n unsafe {\n let sum = lasx_xvhaddw_h_b(sum, sum);\n let sum = lasx_xvhaddw_w_h(sum, sum);\n let sum = lasx_xvhaddw_d_w(sum, sum);\n let sum = lasx_xvhaddw_q_d(sum, sum);\n let tmp = lasx_xvpermi_q::<1>(T(sum), T(sum));\n let sum = lasx_xvadd_w(T(sum), T(tmp));\n lasx_xvpickve2gr_wu::<0>(sum)\n }\n }\n\n let lf = lasx_xvrepli_b(b'\\n' as i32);\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 128 {\n let v1 = lasx_xvld::<0>(beg as *const _);\n let v2 = lasx_xvld::<32>(beg as *const _);\n let v3 = lasx_xvld::<64>(beg as *const _);\n let v4 = lasx_xvld::<96>(beg as *const _);\n\n let mut sum = lasx_xvrepli_b(0);\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v1, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v2, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v3, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(128);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = lasx_xvld::<0>(beg as *const _);\n let c = lasx_xvseq_b(v, lf);\n\n let ones = lasx_xvand_v(T(c), T(lasx_xvrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(32);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn lines_fwd_lsx(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v16i8) -> u32 {\n unsafe {\n let sum = lsx_vhaddw_h_b(sum, sum);\n let sum = lsx_vhaddw_w_h(sum, sum);\n let sum = lsx_vhaddw_d_w(sum, sum);\n let sum = lsx_vhaddw_q_d(sum, sum);\n lsx_vpickve2gr_wu::<0>(T(sum))\n }\n }\n\n let lf = lsx_vrepli_b(b'\\n' as i32);\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 64 {\n let v1 = lsx_vld::<0>(beg as *const _);\n let v2 = lsx_vld::<16>(beg as *const _);\n let v3 = lsx_vld::<32>(beg as *const _);\n let v4 = lsx_vld::<48>(beg as *const _);\n\n let mut sum = lsx_vrepli_b(0);\n sum = lsx_vsub_b(sum, lsx_vseq_b(v1, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v2, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v3, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(64);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = lsx_vld::<0>(beg as *const _);\n let c = lsx_vseq_b(v, lf);\n\n let ones = lsx_vand_v(T(c), T(lsx_vrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(16);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn lines_fwd_neon(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::aarch64::*;\n\n let lf = vdupq_n_u8(b'\\n');\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 64 {\n let v1 = vld1q_u8(beg.add(0));\n let v2 = vld1q_u8(beg.add(16));\n let v3 = vld1q_u8(beg.add(32));\n let v4 = vld1q_u8(beg.add(48));\n\n // `vceqq_u8` leaves each comparison result byte as 0 or -1 (0xff).\n // This allows us to accumulate the comparisons by subtracting them.\n let mut sum = vdupq_n_u8(0);\n sum = vsubq_u8(sum, vceqq_u8(v1, lf));\n sum = vsubq_u8(sum, vceqq_u8(v2, lf));\n sum = vsubq_u8(sum, vceqq_u8(v3, lf));\n sum = vsubq_u8(sum, vceqq_u8(v4, lf));\n\n let sum = vaddvq_u8(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(64);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = vld1q_u8(beg);\n let c = vceqq_u8(v, lf);\n let c = vandq_u8(c, vdupq_n_u8(0x01));\n let sum = vaddvq_u8(c);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(16);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n use crate::helpers::CoordType;\n use crate::simd::test::*;\n\n #[test]\n fn pseudo_fuzz() {\n let text = generate_random_text(1024);\n let lines = count_lines(&text);\n let mut offset_rng = make_rng();\n let mut line_rng = make_rng();\n let mut line_distance_rng = make_rng();\n\n for _ in 0..1000 {\n let offset = offset_rng() % (text.len() + 1);\n let line = line_rng() % 100;\n let line_stop = (line + line_distance_rng() % (lines + 1)).saturating_sub(5);\n\n let line = line as CoordType;\n let line_stop = line_stop as CoordType;\n\n let expected = reference_lines_fwd(text.as_bytes(), offset, line, line_stop);\n let actual = lines_fwd(text.as_bytes(), offset, line, line_stop);\n\n assert_eq!(expected, actual);\n }\n }\n\n fn reference_lines_fwd(\n haystack: &[u8],\n mut offset: usize,\n mut line: CoordType,\n line_stop: CoordType,\n ) -> (usize, CoordType) {\n if line < line_stop {\n while offset < haystack.len() {\n let c = haystack[offset];\n offset += 1;\n if c == b'\\n' {\n line += 1;\n if line == line_stop {\n break;\n }\n }\n }\n }\n (offset, line)\n }\n}\n"], ["/edit/src/simd/memset.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! `memchr` for arbitrary sizes (1/2/4/8 bytes).\n//!\n//! Clang calls the C `memset` function only for byte-sized types (or 0 fills).\n//! We however need to fill other types as well. For that, clang generates\n//! SIMD loops under higher optimization levels. With `-Os` however, it only\n//! generates a trivial loop which is too slow for our needs.\n//!\n//! This implementation uses SWAR to only have a single implementation for all\n//! 4 sizes: By duplicating smaller types into a larger `u64` register we can\n//! treat all sizes as if they were `u64`. The only thing we need to take care\n//! of is the tail end of the array, which needs to write 0-7 additional bytes.\n\nuse std::mem;\n\n/// A marker trait for types that are safe to `memset`.\n///\n/// # Safety\n///\n/// Just like with C's `memset`, bad things happen\n/// if you use this with non-trivial types.\npub unsafe trait MemsetSafe: Copy {}\n\nunsafe impl MemsetSafe for u8 {}\nunsafe impl MemsetSafe for u16 {}\nunsafe impl MemsetSafe for u32 {}\nunsafe impl MemsetSafe for u64 {}\nunsafe impl MemsetSafe for usize {}\n\nunsafe impl MemsetSafe for i8 {}\nunsafe impl MemsetSafe for i16 {}\nunsafe impl MemsetSafe for i32 {}\nunsafe impl MemsetSafe for i64 {}\nunsafe impl MemsetSafe for isize {}\n\n/// Fills a slice with the given value.\n#[inline]\npub fn memset(dst: &mut [T], val: T) {\n unsafe {\n match mem::size_of::() {\n 1 => {\n // LLVM will compile this to a call to `memset`,\n // which hopefully should be better optimized than my code.\n let beg = dst.as_mut_ptr();\n let val = mem::transmute_copy::<_, u8>(&val);\n beg.write_bytes(val, dst.len());\n }\n 2 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u16>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val as u64 * 0x0001000100010001);\n }\n 4 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u32>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val as u64 * 0x0000000100000001);\n }\n 8 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u64>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val);\n }\n _ => unreachable!(),\n }\n }\n}\n\n#[inline]\nfn memset_raw(beg: *mut u8, end: *mut u8, val: u64) {\n #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { MEMSET_DISPATCH(beg, end, val) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { memset_neon(beg, end, val) };\n\n #[allow(unreachable_code)]\n return unsafe { memset_fallback(beg, end, val) };\n}\n\n#[inline(never)]\nunsafe fn memset_fallback(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n let mut remaining = end.offset_from_unsigned(beg);\n\n while remaining >= 8 {\n (beg as *mut u64).write_unaligned(val);\n beg = beg.add(8);\n remaining -= 8;\n }\n\n if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut MEMSET_DISPATCH: unsafe fn(beg: *mut u8, end: *mut u8, val: u64) = memset_dispatch;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn memset_dispatch(beg: *mut u8, end: *mut u8, val: u64) {\n let func = if is_x86_feature_detected!(\"avx2\") { memset_avx2 } else { memset_sse2 };\n unsafe { MEMSET_DISPATCH = func };\n unsafe { func(beg, end, val) }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"sse2\")]\nunsafe fn memset_sse2(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 16 {\n let fill = _mm_set1_epi64x(val as i64);\n\n while remaining >= 32 {\n _mm_storeu_si128(beg as *mut _, fill);\n _mm_storeu_si128(beg.add(16) as *mut _, fill);\n\n beg = beg.add(32);\n remaining -= 32;\n }\n\n if remaining >= 16 {\n // 16-31 bytes remaining\n _mm_storeu_si128(beg as *mut _, fill);\n _mm_storeu_si128(end.sub(16) as *mut _, fill);\n return;\n }\n }\n\n if remaining >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"avx2\")]\nfn memset_avx2(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n use std::hint::black_box;\n\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 128 {\n let fill = _mm256_set1_epi64x(val as i64);\n\n loop {\n _mm256_storeu_si256(beg as *mut _, fill);\n _mm256_storeu_si256(beg.add(32) as *mut _, fill);\n _mm256_storeu_si256(beg.add(64) as *mut _, fill);\n _mm256_storeu_si256(beg.add(96) as *mut _, fill);\n\n beg = beg.add(128);\n remaining -= 128;\n if remaining < 128 {\n break;\n }\n }\n }\n\n if remaining >= 16 {\n let fill = _mm_set1_epi64x(val as i64);\n\n loop {\n // LLVM is _very_ eager to unroll loops. In the absence of an unroll attribute, black_box does the job.\n // Note that this must not be applied to the intrinsic parameters, as they're otherwise misoptimized.\n #[allow(clippy::unit_arg)]\n black_box(_mm_storeu_si128(beg as *mut _, fill));\n\n beg = beg.add(16);\n remaining -= 16;\n if remaining < 16 {\n break;\n }\n }\n }\n\n // `remaining` is between 0 and 15 at this point.\n // By overlapping the stores we can write all of them in at most 2 stores. This approach\n // can be seen in various libraries, such as wyhash which uses it for loading data in `wyr3`.\n if remaining >= 8 {\n // 8-15 bytes\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nfn memset_dispatch(beg: *mut u8, end: *mut u8, val: u64) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n memset_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n memset_lsx\n } else {\n memset_fallback\n };\n unsafe { MEMSET_DISPATCH = func };\n unsafe { func(beg, end, val) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nfn memset_lasx(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let fill: v32i8 = T(lasx_xvreplgr2vr_d(val as i64));\n\n if end.offset_from_unsigned(beg) >= 32 {\n lasx_xvst::<0>(fill, beg as *mut _);\n let off = beg.align_offset(32);\n beg = beg.add(off);\n }\n\n if end.offset_from_unsigned(beg) >= 128 {\n loop {\n lasx_xvst::<0>(fill, beg as *mut _);\n lasx_xvst::<32>(fill, beg as *mut _);\n lasx_xvst::<64>(fill, beg as *mut _);\n lasx_xvst::<96>(fill, beg as *mut _);\n\n beg = beg.add(128);\n if end.offset_from_unsigned(beg) < 128 {\n break;\n }\n }\n }\n\n if end.offset_from_unsigned(beg) >= 16 {\n let fill: v16i8 = T(lsx_vreplgr2vr_d(val as i64));\n\n loop {\n lsx_vst::<0>(fill, beg as *mut _);\n\n beg = beg.add(16);\n if end.offset_from_unsigned(beg) < 16 {\n break;\n }\n }\n }\n\n if end.offset_from_unsigned(beg) >= 8 {\n // 8-15 bytes\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if end.offset_from_unsigned(beg) >= 4 {\n // 4-7 bytes\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if end.offset_from_unsigned(beg) >= 2 {\n // 2-3 bytes\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if end.offset_from_unsigned(beg) >= 1 {\n // 1 byte\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn memset_lsx(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n if end.offset_from_unsigned(beg) >= 16 {\n let fill: v16i8 = T(lsx_vreplgr2vr_d(val as i64));\n\n lsx_vst::<0>(fill, beg as *mut _);\n let off = beg.align_offset(16);\n beg = beg.add(off);\n\n while end.offset_from_unsigned(beg) >= 32 {\n lsx_vst::<0>(fill, beg as *mut _);\n lsx_vst::<16>(fill, beg as *mut _);\n\n beg = beg.add(32);\n }\n\n if end.offset_from_unsigned(beg) >= 16 {\n // 16-31 bytes remaining\n lsx_vst::<0>(fill, beg as *mut _);\n lsx_vst::<-16>(fill, end as *mut _);\n return;\n }\n }\n\n if end.offset_from_unsigned(beg) >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if end.offset_from_unsigned(beg) >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if end.offset_from_unsigned(beg) >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if end.offset_from_unsigned(beg) >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn memset_neon(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::aarch64::*;\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 32 {\n let fill = vdupq_n_u64(val);\n\n loop {\n // Compiles to a single `stp` instruction.\n vst1q_u64(beg as *mut _, fill);\n vst1q_u64(beg.add(16) as *mut _, fill);\n\n beg = beg.add(32);\n remaining -= 32;\n if remaining < 32 {\n break;\n }\n }\n }\n\n if remaining >= 16 {\n // 16-31 bytes remaining\n let fill = vdupq_n_u64(val);\n vst1q_u64(beg as *mut _, fill);\n vst1q_u64(end.sub(16) as *mut _, fill);\n } else if remaining >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::fmt;\n use std::ops::Not;\n\n use super::*;\n\n fn check_memset(val: T, len: usize)\n where\n T: MemsetSafe + Not + PartialEq + fmt::Debug,\n {\n let mut buf = vec![!val; len];\n memset(&mut buf, val);\n assert!(buf.iter().all(|&x| x == val));\n }\n\n #[test]\n fn test_memset_empty() {\n check_memset(0u8, 0);\n check_memset(0u16, 0);\n check_memset(0u32, 0);\n check_memset(0u64, 0);\n }\n\n #[test]\n fn test_memset_single() {\n check_memset(0u8, 1);\n check_memset(0xFFu8, 1);\n check_memset(0xABu16, 1);\n check_memset(0x12345678u32, 1);\n check_memset(0xDEADBEEFu64, 1);\n }\n\n #[test]\n fn test_memset_small() {\n for &len in &[2, 3, 4, 5, 7, 8, 9] {\n check_memset(0xAAu8, len);\n check_memset(0xBEEFu16, len);\n check_memset(0xCAFEBABEu32, len);\n check_memset(0x1234567890ABCDEFu64, len);\n }\n }\n\n #[test]\n fn test_memset_large() {\n check_memset(0u8, 1000);\n check_memset(0xFFu8, 1024);\n check_memset(0xBEEFu16, 512);\n check_memset(0xCAFEBABEu32, 256);\n check_memset(0x1234567890ABCDEFu64, 128);\n }\n\n #[test]\n fn test_memset_various_values() {\n check_memset(0u8, 17);\n check_memset(0x7Fu8, 17);\n check_memset(0x8001u16, 17);\n check_memset(0xFFFFFFFFu32, 17);\n check_memset(0x8000000000000001u64, 17);\n }\n\n #[test]\n fn test_memset_signed_types() {\n check_memset(-1i8, 8);\n check_memset(-2i16, 8);\n check_memset(-3i32, 8);\n check_memset(-4i64, 8);\n check_memset(-5isize, 8);\n }\n\n #[test]\n fn test_memset_usize_isize() {\n check_memset(0usize, 4);\n check_memset(usize::MAX, 4);\n check_memset(0isize, 4);\n check_memset(isize::MIN, 4);\n }\n\n #[test]\n fn test_memset_alignment() {\n // Check that memset works for slices not aligned to 8 bytes\n let mut buf = [0u8; 15];\n for offset in 0..8 {\n let slice = &mut buf[offset..(offset + 7)];\n memset(slice, 0x5A);\n assert!(slice.iter().all(|&x| x == 0x5A));\n }\n }\n}\n"], ["/edit/src/input.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Parses VT sequences into input events.\n//!\n//! In the future this allows us to take apart the application and\n//! support input schemes that aren't VT, such as UEFI, or GUI.\n\nuse std::mem;\n\nuse crate::helpers::{CoordType, Point, Size};\nuse crate::vt;\n\n/// Represents a key/modifier combination.\n///\n/// TODO: Is this a good idea? I did it to allow typing `kbmod::CTRL | vk::A`.\n/// The reason it's an awkward u32 and not a struct is to hopefully make ABIs easier later.\n/// Of course you could just translate on the ABI boundary, but my hope is that this\n/// design lets me realize some restrictions early on that I can't foresee yet.\n#[repr(transparent)]\n#[derive(Clone, Copy, PartialEq, Eq)]\npub struct InputKey(u32);\n\nimpl InputKey {\n pub(crate) const fn new(v: u32) -> Self {\n Self(v)\n }\n\n pub(crate) const fn from_ascii(ch: char) -> Option {\n if ch == ' ' || (ch >= '0' && ch <= '9') {\n Some(Self(ch as u32))\n } else if ch >= 'a' && ch <= 'z' {\n Some(Self(ch as u32 & !0x20)) // Shift a-z to A-Z\n } else if ch >= 'A' && ch <= 'Z' {\n Some(Self(kbmod::SHIFT.0 | ch as u32))\n } else {\n None\n }\n }\n\n pub(crate) const fn value(&self) -> u32 {\n self.0\n }\n\n pub(crate) const fn key(&self) -> Self {\n Self(self.0 & 0x00FFFFFF)\n }\n\n pub(crate) const fn modifiers(&self) -> InputKeyMod {\n InputKeyMod(self.0 & 0xFF000000)\n }\n\n pub(crate) const fn modifiers_contains(&self, modifier: InputKeyMod) -> bool {\n (self.0 & modifier.0) != 0\n }\n\n pub(crate) const fn with_modifiers(&self, modifiers: InputKeyMod) -> Self {\n Self(self.0 | modifiers.0)\n }\n}\n\n/// A keyboard modifier. Ctrl/Alt/Shift.\n#[repr(transparent)]\n#[derive(Clone, Copy, PartialEq, Eq)]\npub struct InputKeyMod(u32);\n\nimpl InputKeyMod {\n const fn new(v: u32) -> Self {\n Self(v)\n }\n\n pub(crate) const fn contains(&self, modifier: Self) -> bool {\n (self.0 & modifier.0) != 0\n }\n}\n\nimpl std::ops::BitOr for InputKey {\n type Output = Self;\n\n fn bitor(self, rhs: InputKeyMod) -> Self {\n Self(self.0 | rhs.0)\n }\n}\n\nimpl std::ops::BitOr for InputKeyMod {\n type Output = InputKey;\n\n fn bitor(self, rhs: InputKey) -> InputKey {\n InputKey(self.0 | rhs.0)\n }\n}\n\nimpl std::ops::BitOrAssign for InputKeyMod {\n fn bitor_assign(&mut self, rhs: Self) {\n self.0 |= rhs.0;\n }\n}\n\n/// Keyboard keys.\n///\n/// The codes defined here match the VK_* constants on Windows.\n/// It's a convenient way to handle keyboard input, even on other platforms.\npub mod vk {\n use super::InputKey;\n\n pub const NULL: InputKey = InputKey::new('\\0' as u32);\n pub const BACK: InputKey = InputKey::new(0x08);\n pub const TAB: InputKey = InputKey::new('\\t' as u32);\n pub const RETURN: InputKey = InputKey::new('\\r' as u32);\n pub const ESCAPE: InputKey = InputKey::new(0x1B);\n pub const SPACE: InputKey = InputKey::new(' ' as u32);\n pub const PRIOR: InputKey = InputKey::new(0x21);\n pub const NEXT: InputKey = InputKey::new(0x22);\n\n pub const END: InputKey = InputKey::new(0x23);\n pub const HOME: InputKey = InputKey::new(0x24);\n\n pub const LEFT: InputKey = InputKey::new(0x25);\n pub const UP: InputKey = InputKey::new(0x26);\n pub const RIGHT: InputKey = InputKey::new(0x27);\n pub const DOWN: InputKey = InputKey::new(0x28);\n\n pub const INSERT: InputKey = InputKey::new(0x2D);\n pub const DELETE: InputKey = InputKey::new(0x2E);\n\n pub const N0: InputKey = InputKey::new('0' as u32);\n pub const N1: InputKey = InputKey::new('1' as u32);\n pub const N2: InputKey = InputKey::new('2' as u32);\n pub const N3: InputKey = InputKey::new('3' as u32);\n pub const N4: InputKey = InputKey::new('4' as u32);\n pub const N5: InputKey = InputKey::new('5' as u32);\n pub const N6: InputKey = InputKey::new('6' as u32);\n pub const N7: InputKey = InputKey::new('7' as u32);\n pub const N8: InputKey = InputKey::new('8' as u32);\n pub const N9: InputKey = InputKey::new('9' as u32);\n\n pub const A: InputKey = InputKey::new('A' as u32);\n pub const B: InputKey = InputKey::new('B' as u32);\n pub const C: InputKey = InputKey::new('C' as u32);\n pub const D: InputKey = InputKey::new('D' as u32);\n pub const E: InputKey = InputKey::new('E' as u32);\n pub const F: InputKey = InputKey::new('F' as u32);\n pub const G: InputKey = InputKey::new('G' as u32);\n pub const H: InputKey = InputKey::new('H' as u32);\n pub const I: InputKey = InputKey::new('I' as u32);\n pub const J: InputKey = InputKey::new('J' as u32);\n pub const K: InputKey = InputKey::new('K' as u32);\n pub const L: InputKey = InputKey::new('L' as u32);\n pub const M: InputKey = InputKey::new('M' as u32);\n pub const N: InputKey = InputKey::new('N' as u32);\n pub const O: InputKey = InputKey::new('O' as u32);\n pub const P: InputKey = InputKey::new('P' as u32);\n pub const Q: InputKey = InputKey::new('Q' as u32);\n pub const R: InputKey = InputKey::new('R' as u32);\n pub const S: InputKey = InputKey::new('S' as u32);\n pub const T: InputKey = InputKey::new('T' as u32);\n pub const U: InputKey = InputKey::new('U' as u32);\n pub const V: InputKey = InputKey::new('V' as u32);\n pub const W: InputKey = InputKey::new('W' as u32);\n pub const X: InputKey = InputKey::new('X' as u32);\n pub const Y: InputKey = InputKey::new('Y' as u32);\n pub const Z: InputKey = InputKey::new('Z' as u32);\n\n pub const NUMPAD0: InputKey = InputKey::new(0x60);\n pub const NUMPAD1: InputKey = InputKey::new(0x61);\n pub const NUMPAD2: InputKey = InputKey::new(0x62);\n pub const NUMPAD3: InputKey = InputKey::new(0x63);\n pub const NUMPAD4: InputKey = InputKey::new(0x64);\n pub const NUMPAD5: InputKey = InputKey::new(0x65);\n pub const NUMPAD6: InputKey = InputKey::new(0x66);\n pub const NUMPAD7: InputKey = InputKey::new(0x67);\n pub const NUMPAD8: InputKey = InputKey::new(0x68);\n pub const NUMPAD9: InputKey = InputKey::new(0x69);\n pub const MULTIPLY: InputKey = InputKey::new(0x6A);\n pub const ADD: InputKey = InputKey::new(0x6B);\n pub const SEPARATOR: InputKey = InputKey::new(0x6C);\n pub const SUBTRACT: InputKey = InputKey::new(0x6D);\n pub const DECIMAL: InputKey = InputKey::new(0x6E);\n pub const DIVIDE: InputKey = InputKey::new(0x6F);\n\n pub const F1: InputKey = InputKey::new(0x70);\n pub const F2: InputKey = InputKey::new(0x71);\n pub const F3: InputKey = InputKey::new(0x72);\n pub const F4: InputKey = InputKey::new(0x73);\n pub const F5: InputKey = InputKey::new(0x74);\n pub const F6: InputKey = InputKey::new(0x75);\n pub const F7: InputKey = InputKey::new(0x76);\n pub const F8: InputKey = InputKey::new(0x77);\n pub const F9: InputKey = InputKey::new(0x78);\n pub const F10: InputKey = InputKey::new(0x79);\n pub const F11: InputKey = InputKey::new(0x7A);\n pub const F12: InputKey = InputKey::new(0x7B);\n pub const F13: InputKey = InputKey::new(0x7C);\n pub const F14: InputKey = InputKey::new(0x7D);\n pub const F15: InputKey = InputKey::new(0x7E);\n pub const F16: InputKey = InputKey::new(0x7F);\n pub const F17: InputKey = InputKey::new(0x80);\n pub const F18: InputKey = InputKey::new(0x81);\n pub const F19: InputKey = InputKey::new(0x82);\n pub const F20: InputKey = InputKey::new(0x83);\n pub const F21: InputKey = InputKey::new(0x84);\n pub const F22: InputKey = InputKey::new(0x85);\n pub const F23: InputKey = InputKey::new(0x86);\n pub const F24: InputKey = InputKey::new(0x87);\n}\n\n/// Keyboard modifiers.\npub mod kbmod {\n use super::InputKeyMod;\n\n pub const NONE: InputKeyMod = InputKeyMod::new(0x00000000);\n pub const CTRL: InputKeyMod = InputKeyMod::new(0x01000000);\n pub const ALT: InputKeyMod = InputKeyMod::new(0x02000000);\n pub const SHIFT: InputKeyMod = InputKeyMod::new(0x04000000);\n\n pub const CTRL_ALT: InputKeyMod = InputKeyMod::new(0x03000000);\n pub const CTRL_SHIFT: InputKeyMod = InputKeyMod::new(0x05000000);\n pub const ALT_SHIFT: InputKeyMod = InputKeyMod::new(0x06000000);\n pub const CTRL_ALT_SHIFT: InputKeyMod = InputKeyMod::new(0x07000000);\n}\n\n/// Mouse input state. Up/Down, Left/Right, etc.\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]\npub enum InputMouseState {\n #[default]\n None,\n\n // These 3 carry their state between frames.\n Left,\n Middle,\n Right,\n\n // These 2 get reset to None on the next frame.\n Release,\n Scroll,\n}\n\n/// Mouse input.\n#[derive(Clone, Copy)]\npub struct InputMouse {\n /// The state of the mouse.Up/Down, Left/Right, etc.\n pub state: InputMouseState,\n /// Any keyboard modifiers that are held down.\n pub modifiers: InputKeyMod,\n /// Position of the mouse in the viewport.\n pub position: Point,\n /// Scroll delta.\n pub scroll: Point,\n}\n\n/// Primary result type of the parser.\npub enum Input<'input> {\n /// Window resize event.\n Resize(Size),\n /// Text input.\n /// Note that [`Input::Keyboard`] events can also be text.\n Text(&'input str),\n /// A clipboard paste.\n Paste(Vec),\n /// Keyboard input.\n Keyboard(InputKey),\n /// Mouse input.\n Mouse(InputMouse),\n}\n\n/// Parses VT sequences into input events.\npub struct Parser {\n bracketed_paste: bool,\n bracketed_paste_buf: Vec,\n x10_mouse_want: bool,\n x10_mouse_buf: [u8; 3],\n x10_mouse_len: usize,\n}\n\nimpl Parser {\n /// Creates a new parser that turns VT sequences into input events.\n ///\n /// Keep the instance alive for the lifetime of the input stream.\n pub fn new() -> Self {\n Self {\n bracketed_paste: false,\n bracketed_paste_buf: Vec::new(),\n x10_mouse_want: false,\n x10_mouse_buf: [0; 3],\n x10_mouse_len: 0,\n }\n }\n\n /// Takes an [`vt::Stream`] and returns a [`Stream`]\n /// that turns VT sequences into input events.\n pub fn parse<'parser, 'vt, 'input>(\n &'parser mut self,\n stream: vt::Stream<'vt, 'input>,\n ) -> Stream<'parser, 'vt, 'input> {\n Stream { parser: self, stream }\n }\n}\n\n/// An iterator that parses VT sequences into input events.\npub struct Stream<'parser, 'vt, 'input> {\n parser: &'parser mut Parser,\n stream: vt::Stream<'vt, 'input>,\n}\n\nimpl<'input> Iterator for Stream<'_, '_, 'input> {\n type Item = Input<'input>;\n\n fn next(&mut self) -> Option> {\n loop {\n if self.parser.bracketed_paste {\n return self.handle_bracketed_paste();\n }\n\n if self.parser.x10_mouse_want {\n return self.parse_x10_mouse_coordinates();\n }\n\n const KEYPAD_LUT: [u8; 8] = [\n vk::UP.value() as u8, // A\n vk::DOWN.value() as u8, // B\n vk::RIGHT.value() as u8, // C\n vk::LEFT.value() as u8, // D\n 0, // E\n vk::END.value() as u8, // F\n 0, // G\n vk::HOME.value() as u8, // H\n ];\n\n match self.stream.next()? {\n vt::Token::Text(text) => {\n return Some(Input::Text(text));\n }\n vt::Token::Ctrl(ch) => match ch {\n '\\0' | '\\t' | '\\r' => return Some(Input::Keyboard(InputKey::new(ch as u32))),\n '\\n' => return Some(Input::Keyboard(kbmod::CTRL | vk::RETURN)),\n ..='\\x1a' => {\n // Shift control code to A-Z\n let key = ch as u32 | 0x40;\n return Some(Input::Keyboard(kbmod::CTRL | InputKey::new(key)));\n }\n '\\x7f' => return Some(Input::Keyboard(vk::BACK)),\n _ => {}\n },\n vt::Token::Esc(ch) => {\n match ch {\n '\\0' => return Some(Input::Keyboard(vk::ESCAPE)),\n '\\n' => return Some(Input::Keyboard(kbmod::CTRL_ALT | vk::RETURN)),\n ' '..='~' => {\n let ch = ch as u32;\n let key = ch & !0x20; // Shift a-z to A-Z\n let modifiers =\n if (ch & 0x20) != 0 { kbmod::ALT } else { kbmod::ALT_SHIFT };\n return Some(Input::Keyboard(modifiers | InputKey::new(key)));\n }\n _ => {}\n }\n }\n vt::Token::SS3(ch) => match ch {\n 'A'..='H' => {\n let vk = KEYPAD_LUT[ch as usize - 'A' as usize];\n if vk != 0 {\n return Some(Input::Keyboard(InputKey::new(vk as u32)));\n }\n }\n 'P'..='S' => {\n let key = vk::F1.value() + ch as u32 - 'P' as u32;\n return Some(Input::Keyboard(InputKey::new(key)));\n }\n _ => {}\n },\n vt::Token::Csi(csi) => {\n match csi.final_byte {\n 'A'..='H' => {\n let vk = KEYPAD_LUT[csi.final_byte as usize - 'A' as usize];\n if vk != 0 {\n return Some(Input::Keyboard(\n InputKey::new(vk as u32) | Self::parse_modifiers(csi),\n ));\n }\n }\n 'Z' => return Some(Input::Keyboard(kbmod::SHIFT | vk::TAB)),\n '~' => {\n const LUT: [u8; 35] = [\n 0,\n vk::HOME.value() as u8, // 1\n vk::INSERT.value() as u8, // 2\n vk::DELETE.value() as u8, // 3\n vk::END.value() as u8, // 4\n vk::PRIOR.value() as u8, // 5\n vk::NEXT.value() as u8, // 6\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n vk::F5.value() as u8, // 15\n 0,\n vk::F6.value() as u8, // 17\n vk::F7.value() as u8, // 18\n vk::F8.value() as u8, // 19\n vk::F9.value() as u8, // 20\n vk::F10.value() as u8, // 21\n 0,\n vk::F11.value() as u8, // 23\n vk::F12.value() as u8, // 24\n vk::F13.value() as u8, // 25\n vk::F14.value() as u8, // 26\n 0,\n vk::F15.value() as u8, // 28\n vk::F16.value() as u8, // 29\n 0,\n vk::F17.value() as u8, // 31\n vk::F18.value() as u8, // 32\n vk::F19.value() as u8, // 33\n vk::F20.value() as u8, // 34\n ];\n const LUT_LEN: u16 = LUT.len() as u16;\n\n match csi.params[0] {\n 0..LUT_LEN => {\n let vk = LUT[csi.params[0] as usize];\n if vk != 0 {\n return Some(Input::Keyboard(\n InputKey::new(vk as u32) | Self::parse_modifiers(csi),\n ));\n }\n }\n 200 => self.parser.bracketed_paste = true,\n _ => {}\n }\n }\n 'm' | 'M' if csi.private_byte == '<' => {\n let btn = csi.params[0];\n let mut mouse = InputMouse {\n state: InputMouseState::None,\n modifiers: kbmod::NONE,\n position: Default::default(),\n scroll: Default::default(),\n };\n\n mouse.state = InputMouseState::None;\n if (btn & 0x40) != 0 {\n mouse.state = InputMouseState::Scroll;\n mouse.scroll.y += if (btn & 0x01) != 0 { 3 } else { -3 };\n } else if csi.final_byte == 'M' {\n const STATES: [InputMouseState; 4] = [\n InputMouseState::Left,\n InputMouseState::Middle,\n InputMouseState::Right,\n InputMouseState::None,\n ];\n mouse.state = STATES[(btn as usize) & 0x03];\n }\n\n mouse.modifiers = kbmod::NONE;\n mouse.modifiers |=\n if (btn & 0x04) != 0 { kbmod::SHIFT } else { kbmod::NONE };\n mouse.modifiers |=\n if (btn & 0x08) != 0 { kbmod::ALT } else { kbmod::NONE };\n mouse.modifiers |=\n if (btn & 0x10f) != 0 { kbmod::CTRL } else { kbmod::NONE };\n\n mouse.position.x = csi.params[1] as CoordType - 1;\n mouse.position.y = csi.params[2] as CoordType - 1;\n return Some(Input::Mouse(mouse));\n }\n 'M' if csi.param_count == 0 => {\n self.parser.x10_mouse_want = true;\n }\n 't' if csi.params[0] == 8 => {\n // Window Size\n let width = (csi.params[2] as CoordType).clamp(1, 32767);\n let height = (csi.params[1] as CoordType).clamp(1, 32767);\n return Some(Input::Resize(Size { width, height }));\n }\n _ => {}\n }\n }\n _ => {}\n }\n }\n }\n}\n\nimpl<'input> Stream<'_, '_, 'input> {\n /// Once we encounter the start of a bracketed paste\n /// we seek to the end of the paste in this function.\n ///\n /// A bracketed paste is basically:\n /// ```text\n /// [201~ lots of text [201~\n /// ```\n ///\n /// That in between text is then expected to be taken literally.\n /// It can be in between anything though, including other escape sequences.\n /// This is the reason why this is a separate method.\n #[cold]\n fn handle_bracketed_paste(&mut self) -> Option> {\n let beg = self.stream.offset();\n let mut end = beg;\n\n while let Some(token) = self.stream.next() {\n if let vt::Token::Csi(csi) = token\n && csi.final_byte == '~'\n && csi.params[0] == 201\n {\n self.parser.bracketed_paste = false;\n break;\n }\n end = self.stream.offset();\n }\n\n if end != beg {\n self.parser\n .bracketed_paste_buf\n .extend_from_slice(&self.stream.input().as_bytes()[beg..end]);\n }\n\n if !self.parser.bracketed_paste {\n Some(Input::Paste(mem::take(&mut self.parser.bracketed_paste_buf)))\n } else {\n None\n }\n }\n\n /// Implements the X10 mouse protocol via `CSI M CbCxCy`.\n ///\n /// You want to send numeric mouse coordinates.\n /// You have CSI sequences with numeric parameters.\n /// So, of course you put the coordinates as shifted ASCII characters after\n /// the end of the sequence. Limited coordinate range and complicated parsing!\n /// This is so puzzling to me. The existence of this function makes me unhappy.\n #[cold]\n fn parse_x10_mouse_coordinates(&mut self) -> Option> {\n self.parser.x10_mouse_len +=\n self.stream.read(&mut self.parser.x10_mouse_buf[self.parser.x10_mouse_len..]);\n if self.parser.x10_mouse_len < 3 {\n return None;\n }\n\n let button = self.parser.x10_mouse_buf[0] & 0b11;\n let modifier = self.parser.x10_mouse_buf[0] & 0b11100;\n let x = self.parser.x10_mouse_buf[1] as CoordType - 0x21;\n let y = self.parser.x10_mouse_buf[2] as CoordType - 0x21;\n let action = match button {\n 0 => InputMouseState::Left,\n 1 => InputMouseState::Middle,\n 2 => InputMouseState::Right,\n _ => InputMouseState::None,\n };\n let modifiers = match modifier {\n 4 => kbmod::SHIFT,\n 8 => kbmod::ALT,\n 16 => kbmod::CTRL,\n _ => kbmod::NONE,\n };\n\n self.parser.x10_mouse_want = false;\n self.parser.x10_mouse_len = 0;\n\n Some(Input::Mouse(InputMouse {\n state: action,\n modifiers,\n position: Point { x, y },\n scroll: Default::default(),\n }))\n }\n\n fn parse_modifiers(csi: &vt::Csi) -> InputKeyMod {\n let mut modifiers = kbmod::NONE;\n let p1 = csi.params[1].saturating_sub(1);\n if (p1 & 0x01) != 0 {\n modifiers |= kbmod::SHIFT;\n }\n if (p1 & 0x02) != 0 {\n modifiers |= kbmod::ALT;\n }\n if (p1 & 0x04) != 0 {\n modifiers |= kbmod::CTRL;\n }\n modifiers\n }\n}\n"], ["/edit/src/buffer/line_cache.rs", "use std::ops::Range;\n\nuse crate::{document::ReadableDocument, simd::memchr2};\n\n/// Cache a line/offset pair every CACHE_EVERY lines to speed up line/offset calculations\nconst CACHE_EVERY: usize = 1024 * 64;\n\n#[derive(Clone)]\npub struct CachePoint {\n pub index: usize,\n pub line: usize,\n // pub snapshot: ParserSnapshot\n}\n\npub struct LineCache {\n cache: Vec,\n}\n\nimpl LineCache {\n pub fn new() -> Self {\n Self { cache: vec![] }\n }\n\n pub fn from_document(&mut self, document: &T) {\n self.cache.clear();\n\n let mut offset = 0;\n let mut line = 0;\n loop {\n let text = document.read_forward(offset);\n if text.is_empty() { return; }\n \n let mut off = 0;\n loop {\n off = memchr2(b'\\n', b'\\n', text, off);\n if off == text.len() { break; }\n\n if line % CACHE_EVERY == 0 {\n self.cache.push(CachePoint { index: offset+off, line });\n }\n line += 1;\n off += 1;\n }\n\n offset += text.len();\n }\n }\n\n /// Updates the cache after a deletion.\n /// `range` is the deleted byte range, and `text` is the content that was deleted.\n pub fn delete(&mut self, range: Range, text: &Vec) {\n let mut newlines = 0;\n for c in text {\n if *c == b'\\n' {\n newlines += 1;\n }\n }\n\n let mut beg_del = None;\n let mut end_del = None;\n for (i, point) in self.cache.iter_mut().enumerate() {\n if point.index >= range.start {\n if point.index < range.end {\n // cache point is within the deleted range\n if beg_del.is_none() { beg_del = Some(i); }\n end_del = Some(i + 1);\n }\n else {\n point.index -= text.len();\n point.line -= newlines;\n }\n }\n }\n\n if let (Some(beg), Some(end)) = (beg_del, end_del) {\n self.cache.drain(beg..end);\n }\n }\n\n /// Updates the cache after an insertion.\n /// `offset` is where the insertion occurs, and `text` is the inserted content.\n pub fn insert(&mut self, offset: usize, text: &[u8]) {\n // Count how many newlines were inserted\n let mut newlines = 0;\n for c in text {\n if *c == b'\\n' {\n newlines += 1;\n }\n }\n\n let len = text.len();\n for point in &mut self.cache {\n if point.index > offset {\n point.index += len;\n point.line += newlines;\n }\n }\n\n // TODO: This also needs to insert new cache points\n }\n\n /// Finds the nearest cached line-offset pair relative to a target line.\n /// If `reverse` is false, it returns the closest *before* the target.\n /// If `reverse` is true, it returns the closest *after or at* the target.\n pub fn nearest_offset(&self, target_count: usize, reverse: bool) -> Option {\n match self.cache.binary_search_by_key(&target_count, |p| p.line) {\n Ok(i) => Some(self.cache[i].clone()),\n Err(i) => {\n if i == 0 || i == self.cache.len() { None } // target < lowest cache point || target > highest cache point\n else {\n Some(self.cache[ if reverse {i} else {i-1} ].clone())\n }\n }\n }\n }\n}\n"], ["/edit/src/bin/edit/state.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::borrow::Cow;\nuse std::ffi::{OsStr, OsString};\nuse std::mem;\nuse std::path::{Path, PathBuf};\n\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::tui::*;\nuse edit::{apperr, buffer, icu, sys};\n\nuse crate::documents::DocumentManager;\nuse crate::localization::*;\n\n#[repr(transparent)]\npub struct FormatApperr(apperr::Error);\n\nimpl From for FormatApperr {\n fn from(err: apperr::Error) -> Self {\n Self(err)\n }\n}\n\nimpl std::fmt::Display for FormatApperr {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self.0 {\n apperr::APP_ICU_MISSING => f.write_str(loc(LocId::ErrorIcuMissing)),\n apperr::Error::App(code) => write!(f, \"Unknown app error code: {code}\"),\n apperr::Error::Icu(code) => icu::apperr_format(f, code),\n apperr::Error::Sys(code) => sys::apperr_format(f, code),\n }\n }\n}\n\npub struct DisplayablePathBuf {\n value: PathBuf,\n str: Cow<'static, str>,\n}\n\nimpl DisplayablePathBuf {\n #[allow(dead_code, reason = \"only used on Windows\")]\n pub fn from_string(string: String) -> Self {\n let str = Cow::Borrowed(string.as_str());\n let str = unsafe { mem::transmute::, Cow<'_, str>>(str) };\n let value = PathBuf::from(string);\n Self { value, str }\n }\n\n pub fn from_path(value: PathBuf) -> Self {\n let str = value.to_string_lossy();\n let str = unsafe { mem::transmute::, Cow<'_, str>>(str) };\n Self { value, str }\n }\n\n pub fn as_path(&self) -> &Path {\n &self.value\n }\n\n pub fn as_str(&self) -> &str {\n &self.str\n }\n\n pub fn as_bytes(&self) -> &[u8] {\n self.value.as_os_str().as_encoded_bytes()\n }\n}\n\nimpl Default for DisplayablePathBuf {\n fn default() -> Self {\n Self { value: Default::default(), str: Cow::Borrowed(\"\") }\n }\n}\n\nimpl Clone for DisplayablePathBuf {\n fn clone(&self) -> Self {\n Self::from_path(self.value.clone())\n }\n}\n\nimpl From for DisplayablePathBuf {\n fn from(s: OsString) -> Self {\n Self::from_path(PathBuf::from(s))\n }\n}\n\nimpl> From<&T> for DisplayablePathBuf {\n fn from(s: &T) -> Self {\n Self::from_path(PathBuf::from(s))\n }\n}\n\npub struct StateSearch {\n pub kind: StateSearchKind,\n pub focus: bool,\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateSearchKind {\n Hidden,\n Disabled,\n Search,\n Replace,\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateFilePicker {\n None,\n Open,\n SaveAs,\n\n SaveAsShown, // Transitioned from SaveAs\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateEncodingChange {\n None,\n Convert,\n Reopen,\n}\n\n#[derive(Default)]\npub struct OscTitleFileStatus {\n pub filename: String,\n pub dirty: bool,\n}\n\npub struct State {\n pub menubar_color_bg: u32,\n pub menubar_color_fg: u32,\n\n pub documents: DocumentManager,\n\n // A ring buffer of the last 10 errors.\n pub error_log: [String; 10],\n pub error_log_index: usize,\n pub error_log_count: usize,\n\n pub wants_file_picker: StateFilePicker,\n pub file_picker_pending_dir: DisplayablePathBuf,\n pub file_picker_pending_dir_revision: u64, // Bumped every time `file_picker_pending_dir` changes.\n pub file_picker_pending_name: PathBuf,\n pub file_picker_entries: Option<[Vec; 3]>, // [\"..\", directories, files]\n pub file_picker_overwrite_warning: Option, // The path the warning is about.\n pub file_picker_autocomplete: Vec,\n\n pub wants_search: StateSearch,\n pub search_needle: String,\n pub search_replacement: String,\n pub search_options: buffer::SearchOptions,\n pub search_success: bool,\n\n pub wants_encoding_picker: bool,\n pub wants_encoding_change: StateEncodingChange,\n pub encoding_picker_needle: String,\n pub encoding_picker_results: Option>,\n\n pub wants_save: bool,\n pub wants_statusbar_focus: bool,\n pub wants_indentation_picker: bool,\n pub wants_go_to_file: bool,\n pub wants_about: bool,\n pub wants_close: bool,\n pub wants_exit: bool,\n pub wants_goto: bool,\n pub goto_target: String,\n pub goto_invalid: bool,\n\n pub osc_title_file_status: OscTitleFileStatus,\n pub osc_clipboard_sync: bool,\n pub osc_clipboard_always_send: bool,\n pub exit: bool,\n}\n\nimpl State {\n pub fn new() -> apperr::Result {\n Ok(Self {\n menubar_color_bg: 0,\n menubar_color_fg: 0,\n\n documents: Default::default(),\n\n error_log: [const { String::new() }; 10],\n error_log_index: 0,\n error_log_count: 0,\n\n wants_file_picker: StateFilePicker::None,\n file_picker_pending_dir: Default::default(),\n file_picker_pending_dir_revision: 0,\n file_picker_pending_name: Default::default(),\n file_picker_entries: None,\n file_picker_overwrite_warning: None,\n file_picker_autocomplete: Vec::new(),\n\n wants_search: StateSearch { kind: StateSearchKind::Hidden, focus: false },\n search_needle: Default::default(),\n search_replacement: Default::default(),\n search_options: Default::default(),\n search_success: true,\n\n wants_encoding_picker: false,\n encoding_picker_needle: Default::default(),\n encoding_picker_results: Default::default(),\n\n wants_save: false,\n wants_statusbar_focus: false,\n wants_encoding_change: StateEncodingChange::None,\n wants_indentation_picker: false,\n wants_go_to_file: false,\n wants_about: false,\n wants_close: false,\n wants_exit: false,\n wants_goto: false,\n goto_target: Default::default(),\n goto_invalid: false,\n\n osc_title_file_status: Default::default(),\n osc_clipboard_sync: false,\n osc_clipboard_always_send: false,\n exit: false,\n })\n }\n}\n\npub fn draw_add_untitled_document(ctx: &mut Context, state: &mut State) {\n if let Err(err) = state.documents.add_untitled() {\n error_log_add(ctx, state, err);\n }\n}\n\npub fn error_log_add(ctx: &mut Context, state: &mut State, err: apperr::Error) {\n let msg = format!(\"{}\", FormatApperr::from(err));\n if !msg.is_empty() {\n state.error_log[state.error_log_index] = msg;\n state.error_log_index = (state.error_log_index + 1) % state.error_log.len();\n state.error_log_count = state.error_log.len().min(state.error_log_count + 1);\n ctx.needs_rerender();\n }\n}\n\npub fn draw_error_log(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"error\", loc(LocId::ErrorDialogTitle));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n ctx.block_begin(\"content\");\n ctx.attr_padding(Rect::three(0, 2, 1));\n {\n let off = state.error_log_index + state.error_log.len() - state.error_log_count;\n\n for i in 0..state.error_log_count {\n let idx = (off + i) % state.error_log.len();\n let msg = &state.error_log[idx][..];\n\n if !msg.is_empty() {\n ctx.next_block_id_mixin(i as u64);\n ctx.label(\"error\", msg);\n ctx.attr_overflow(Overflow::TruncateTail);\n }\n }\n }\n ctx.block_end();\n\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n state.error_log_count = 0;\n }\n ctx.attr_position(Position::Center);\n ctx.inherit_focus();\n }\n if ctx.modal_end() {\n state.error_log_count = 0;\n }\n}\n"], ["/edit/src/simd/lines_bwd.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ptr;\n\nuse crate::helpers::CoordType;\n\n/// Starting from the `offset` in `haystack` with a current line index of\n/// `line`, this seeks backwards to the `line_stop`-nth line and returns the\n/// new offset and the line index at that point.\n///\n/// Note that this function differs from `lines_fwd` in that it\n/// seeks backwards even if the `line` is already at `line_stop`.\n/// This allows you to ensure (or test) whether `offset` is at a line start.\n///\n/// It returns an offset *past* a newline and thus at the start of a line.\npub fn lines_bwd(\n haystack: &[u8],\n offset: usize,\n line: CoordType,\n line_stop: CoordType,\n) -> (usize, CoordType) {\n unsafe {\n let beg = haystack.as_ptr();\n let it = beg.add(offset.min(haystack.len()));\n let (it, line) = lines_bwd_raw(beg, it, line, line_stop);\n (it.offset_from_unsigned(beg), line)\n }\n}\n\nunsafe fn lines_bwd_raw(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n #[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { LINES_BWD_DISPATCH(beg, end, line, line_stop) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { lines_bwd_neon(beg, end, line, line_stop) };\n\n #[allow(unreachable_code)]\n return unsafe { lines_bwd_fallback(beg, end, line, line_stop) };\n}\n\nunsafe fn lines_bwd_fallback(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n while !ptr::eq(end, beg) {\n let n = end.sub(1);\n if *n == b'\\n' {\n if line <= line_stop {\n break;\n }\n line -= 1;\n }\n end = n;\n }\n (end, line)\n }\n}\n\n#[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut LINES_BWD_DISPATCH: unsafe fn(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) = lines_bwd_dispatch;\n\n#[cfg(target_arch = \"x86_64\")]\nunsafe fn lines_bwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n let func = if is_x86_feature_detected!(\"avx2\") { lines_bwd_avx2 } else { lines_bwd_fallback };\n unsafe { LINES_BWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"x86_64\")]\n#[target_feature(enable = \"avx2\")]\nunsafe fn lines_bwd_avx2(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::x86_64::*;\n\n #[inline(always)]\n unsafe fn horizontal_sum_i64(v: __m256i) -> i64 {\n unsafe {\n let hi = _mm256_extracti128_si256::<1>(v);\n let lo = _mm256_castsi256_si128(v);\n let sum = _mm_add_epi64(lo, hi);\n let shuf = _mm_shuffle_epi32::<0b11_10_11_10>(sum);\n let sum = _mm_add_epi64(sum, shuf);\n _mm_cvtsi128_si64(sum)\n }\n }\n\n let lf = _mm256_set1_epi8(b'\\n' as i8);\n let off = end.addr() & 31;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 128 {\n let chunk_start = end.sub(128);\n\n let v1 = _mm256_loadu_si256(chunk_start.add(0) as *const _);\n let v2 = _mm256_loadu_si256(chunk_start.add(32) as *const _);\n let v3 = _mm256_loadu_si256(chunk_start.add(64) as *const _);\n let v4 = _mm256_loadu_si256(chunk_start.add(96) as *const _);\n\n let mut sum = _mm256_setzero_si256();\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v1, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v2, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v3, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v4, lf));\n\n let sum = _mm256_sad_epu8(sum, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let chunk_start = end.sub(32);\n let v = _mm256_loadu_si256(chunk_start as *const _);\n let c = _mm256_cmpeq_epi8(v, lf);\n\n let ones = _mm256_and_si256(c, _mm256_set1_epi8(0x01));\n let sum = _mm256_sad_epu8(ones, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn lines_bwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n lines_bwd_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n lines_bwd_lsx\n } else {\n lines_bwd_fallback\n };\n unsafe { LINES_BWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn lines_bwd_lasx(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v32i8) -> u32 {\n unsafe {\n let sum = lasx_xvhaddw_h_b(sum, sum);\n let sum = lasx_xvhaddw_w_h(sum, sum);\n let sum = lasx_xvhaddw_d_w(sum, sum);\n let sum = lasx_xvhaddw_q_d(sum, sum);\n let tmp = lasx_xvpermi_q::<1>(T(sum), T(sum));\n let sum = lasx_xvadd_w(T(sum), T(tmp));\n lasx_xvpickve2gr_wu::<0>(sum)\n }\n }\n\n let lf = lasx_xvrepli_b(b'\\n' as i32);\n let line_stop = line_stop.min(line);\n let off = end.addr() & 31;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 128 {\n let chunk_start = end.sub(128);\n\n let v1 = lasx_xvld::<0>(chunk_start as *const _);\n let v2 = lasx_xvld::<32>(chunk_start as *const _);\n let v3 = lasx_xvld::<64>(chunk_start as *const _);\n let v4 = lasx_xvld::<96>(chunk_start as *const _);\n\n let mut sum = lasx_xvrepli_b(0);\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v1, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v2, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v3, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let chunk_start = end.sub(32);\n let v = lasx_xvld::<0>(chunk_start as *const _);\n let c = lasx_xvseq_b(v, lf);\n\n let ones = lasx_xvand_v(T(c), T(lasx_xvrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn lines_bwd_lsx(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v16i8) -> u32 {\n unsafe {\n let sum = lsx_vhaddw_h_b(sum, sum);\n let sum = lsx_vhaddw_w_h(sum, sum);\n let sum = lsx_vhaddw_d_w(sum, sum);\n let sum = lsx_vhaddw_q_d(sum, sum);\n lsx_vpickve2gr_wu::<0>(T(sum))\n }\n }\n\n let lf = lsx_vrepli_b(b'\\n' as i32);\n let line_stop = line_stop.min(line);\n let off = end.addr() & 15;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 64 {\n let chunk_start = end.sub(64);\n\n let v1 = lsx_vld::<0>(chunk_start as *const _);\n let v2 = lsx_vld::<16>(chunk_start as *const _);\n let v3 = lsx_vld::<32>(chunk_start as *const _);\n let v4 = lsx_vld::<48>(chunk_start as *const _);\n\n let mut sum = lsx_vrepli_b(0);\n sum = lsx_vsub_b(sum, lsx_vseq_b(v1, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v2, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v3, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let chunk_start = end.sub(16);\n let v = lsx_vld::<0>(chunk_start as *const _);\n let c = lsx_vseq_b(v, lf);\n\n let ones = lsx_vand_v(T(c), T(lsx_vrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn lines_bwd_neon(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::aarch64::*;\n\n let lf = vdupq_n_u8(b'\\n');\n let line_stop = line_stop.min(line);\n let off = end.addr() & 15;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 64 {\n let chunk_start = end.sub(64);\n\n let v1 = vld1q_u8(chunk_start.add(0));\n let v2 = vld1q_u8(chunk_start.add(16));\n let v3 = vld1q_u8(chunk_start.add(32));\n let v4 = vld1q_u8(chunk_start.add(48));\n\n let mut sum = vdupq_n_u8(0);\n sum = vsubq_u8(sum, vceqq_u8(v1, lf));\n sum = vsubq_u8(sum, vceqq_u8(v2, lf));\n sum = vsubq_u8(sum, vceqq_u8(v3, lf));\n sum = vsubq_u8(sum, vceqq_u8(v4, lf));\n\n let sum = vaddvq_u8(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let chunk_start = end.sub(16);\n let v = vld1q_u8(chunk_start);\n let c = vceqq_u8(v, lf);\n let c = vandq_u8(c, vdupq_n_u8(0x01));\n let sum = vaddvq_u8(c);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n use crate::helpers::CoordType;\n use crate::simd::test::*;\n\n #[test]\n fn pseudo_fuzz() {\n let text = generate_random_text(1024);\n let lines = count_lines(&text);\n let mut offset_rng = make_rng();\n let mut line_rng = make_rng();\n let mut line_distance_rng = make_rng();\n\n for _ in 0..1000 {\n let offset = offset_rng() % (text.len() + 1);\n let line_stop = line_distance_rng() % (lines + 1);\n let line = (line_stop + line_rng() % 100).saturating_sub(5);\n\n let line = line as CoordType;\n let line_stop = line_stop as CoordType;\n\n let expected = reference_lines_bwd(text.as_bytes(), offset, line, line_stop);\n let actual = lines_bwd(text.as_bytes(), offset, line, line_stop);\n\n assert_eq!(expected, actual);\n }\n }\n\n fn reference_lines_bwd(\n haystack: &[u8],\n mut offset: usize,\n mut line: CoordType,\n line_stop: CoordType,\n ) -> (usize, CoordType) {\n while offset > 0 {\n let c = haystack[offset - 1];\n if c == b'\\n' {\n if line <= line_stop {\n break;\n }\n line -= 1;\n }\n offset -= 1;\n }\n (offset, line)\n }\n\n #[test]\n fn seeks_to_start() {\n for i in 6..=11 {\n let (off, line) = lines_bwd(b\"Hello\\nWorld\\n\", i, 123, 456);\n assert_eq!(off, 6); // After \"Hello\\n\"\n assert_eq!(line, 123); // Still on the same line\n }\n }\n}\n"], ["/edit/src/bin/edit/documents.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::collections::LinkedList;\nuse std::ffi::OsStr;\nuse std::fs::File;\nuse std::path::{Path, PathBuf};\n\nuse edit::buffer::{RcTextBuffer, TextBuffer};\nuse edit::helpers::{CoordType, Point};\nuse edit::{apperr, path, sys};\n\nuse crate::state::DisplayablePathBuf;\n\npub struct Document {\n pub buffer: RcTextBuffer,\n pub path: Option,\n pub dir: Option,\n pub filename: String,\n pub file_id: Option,\n pub new_file_counter: usize,\n}\n\nimpl Document {\n pub fn save(&mut self, new_path: Option) -> apperr::Result<()> {\n let path = new_path.as_deref().unwrap_or_else(|| self.path.as_ref().unwrap().as_path());\n let mut file = DocumentManager::open_for_writing(path)?;\n\n {\n let mut tb = self.buffer.borrow_mut();\n tb.write_file(&mut file)?;\n }\n\n if let Ok(id) = sys::file_id(None, path) {\n self.file_id = Some(id);\n }\n\n if let Some(path) = new_path {\n self.set_path(path);\n }\n\n Ok(())\n }\n\n pub fn reread(&mut self, encoding: Option<&'static str>) -> apperr::Result<()> {\n let path = self.path.as_ref().unwrap().as_path();\n let mut file = DocumentManager::open_for_reading(path)?;\n\n {\n let mut tb = self.buffer.borrow_mut();\n tb.read_file(&mut file, encoding)?;\n }\n\n if let Ok(id) = sys::file_id(None, path) {\n self.file_id = Some(id);\n }\n\n Ok(())\n }\n\n fn set_path(&mut self, path: PathBuf) {\n let filename = path.file_name().unwrap_or_default().to_string_lossy().into_owned();\n let dir = path.parent().map(ToOwned::to_owned).unwrap_or_default();\n self.filename = filename;\n self.dir = Some(DisplayablePathBuf::from_path(dir));\n self.path = Some(path);\n self.update_file_mode();\n }\n\n fn update_file_mode(&mut self) {\n let mut tb = self.buffer.borrow_mut();\n tb.set_ruler(if self.filename == \"COMMIT_EDITMSG\" { 72 } else { 0 });\n }\n}\n\n#[derive(Default)]\npub struct DocumentManager {\n list: LinkedList,\n}\n\nimpl DocumentManager {\n #[inline]\n pub fn len(&self) -> usize {\n self.list.len()\n }\n\n #[inline]\n pub fn active(&self) -> Option<&Document> {\n self.list.front()\n }\n\n #[inline]\n pub fn active_mut(&mut self) -> Option<&mut Document> {\n self.list.front_mut()\n }\n\n #[inline]\n pub fn update_active bool>(&mut self, mut func: F) -> bool {\n let mut cursor = self.list.cursor_front_mut();\n while let Some(doc) = cursor.current() {\n if func(doc) {\n let list = cursor.remove_current_as_list().unwrap();\n self.list.cursor_front_mut().splice_before(list);\n return true;\n }\n cursor.move_next();\n }\n false\n }\n\n pub fn remove_active(&mut self) {\n self.list.pop_front();\n }\n\n pub fn add_untitled(&mut self) -> apperr::Result<&mut Document> {\n let buffer = Self::create_buffer()?;\n let mut doc = Document {\n buffer,\n path: None,\n dir: Default::default(),\n filename: Default::default(),\n file_id: None,\n new_file_counter: 0,\n };\n self.gen_untitled_name(&mut doc);\n\n self.list.push_front(doc);\n Ok(self.list.front_mut().unwrap())\n }\n\n pub fn gen_untitled_name(&self, doc: &mut Document) {\n let mut new_file_counter = 0;\n for doc in &self.list {\n new_file_counter = new_file_counter.max(doc.new_file_counter);\n }\n new_file_counter += 1;\n\n doc.filename = format!(\"Untitled-{new_file_counter}.txt\");\n doc.new_file_counter = new_file_counter;\n }\n\n pub fn add_file_path(&mut self, path: &Path) -> apperr::Result<&mut Document> {\n let (path, goto) = Self::parse_filename_goto(path);\n let path = path::normalize(path);\n\n let mut file = match Self::open_for_reading(&path) {\n Ok(file) => Some(file),\n Err(err) if sys::apperr_is_not_found(err) => None,\n Err(err) => return Err(err),\n };\n\n let file_id = if file.is_some() { Some(sys::file_id(file.as_ref(), &path)?) } else { None };\n\n // Check if the file is already open.\n if file_id.is_some() && self.update_active(|doc| doc.file_id == file_id) {\n let doc = self.active_mut().unwrap();\n if let Some(goto) = goto {\n doc.buffer.borrow_mut().cursor_move_to_logical(goto);\n }\n return Ok(doc);\n }\n\n let buffer = Self::create_buffer()?;\n {\n if let Some(file) = &mut file {\n let mut tb = buffer.borrow_mut();\n tb.read_file(file, None)?;\n\n if let Some(goto) = goto\n && goto != Default::default()\n {\n tb.cursor_move_to_logical(goto);\n }\n }\n }\n\n let mut doc = Document {\n buffer,\n path: None,\n dir: None,\n filename: Default::default(),\n file_id,\n new_file_counter: 0,\n };\n doc.set_path(path);\n\n if let Some(active) = self.active()\n && active.path.is_none()\n && active.file_id.is_none()\n && !active.buffer.borrow().is_dirty()\n {\n // If the current document is a pristine Untitled document with no\n // name and no ID, replace it with the new document.\n self.remove_active();\n }\n\n self.list.push_front(doc);\n Ok(self.list.front_mut().unwrap())\n }\n\n pub fn reflow_all(&self) {\n for doc in &self.list {\n let mut tb = doc.buffer.borrow_mut();\n tb.reflow();\n }\n }\n\n pub fn open_for_reading(path: &Path) -> apperr::Result {\n File::open(path).map_err(apperr::Error::from)\n }\n\n pub fn open_for_writing(path: &Path) -> apperr::Result {\n File::create(path).map_err(apperr::Error::from)\n }\n\n fn create_buffer() -> apperr::Result {\n let buffer = TextBuffer::new_rc(false)?;\n {\n let mut tb = buffer.borrow_mut();\n tb.set_insert_final_newline(!cfg!(windows)); // As mandated by POSIX.\n tb.set_margin_enabled(true);\n tb.set_line_highlight_enabled(true);\n }\n Ok(buffer)\n }\n\n // Parse a filename in the form of \"filename:line:char\".\n // Returns the position of the first colon and the line/char coordinates.\n fn parse_filename_goto(path: &Path) -> (&Path, Option) {\n fn parse(s: &[u8]) -> Option {\n if s.is_empty() {\n return None;\n }\n\n let mut num: CoordType = 0;\n for &b in s {\n if !b.is_ascii_digit() {\n return None;\n }\n let digit = (b - b'0') as CoordType;\n num = num.checked_mul(10)?.checked_add(digit)?;\n }\n Some(num)\n }\n\n fn find_colon_rev(bytes: &[u8], offset: usize) -> Option {\n (0..offset.min(bytes.len())).rev().find(|&i| bytes[i] == b':')\n }\n\n let bytes = path.as_os_str().as_encoded_bytes();\n let colend = match find_colon_rev(bytes, bytes.len()) {\n // Reject filenames that would result in an empty filename after stripping off the :line:char suffix.\n // For instance, a filename like \":123:456\" will not be processed by this function.\n Some(colend) if colend > 0 => colend,\n _ => return (path, None),\n };\n\n let last = match parse(&bytes[colend + 1..]) {\n Some(last) => last,\n None => return (path, None),\n };\n let last = (last - 1).max(0);\n let mut len = colend;\n let mut goto = Point { x: 0, y: last };\n\n if let Some(colbeg) = find_colon_rev(bytes, colend) {\n // Same here: Don't allow empty filenames.\n if colbeg != 0\n && let Some(first) = parse(&bytes[colbeg + 1..colend])\n {\n let first = (first - 1).max(0);\n len = colbeg;\n goto = Point { x: last, y: first };\n }\n }\n\n // Strip off the :line:char suffix.\n let path = &bytes[..len];\n let path = unsafe { OsStr::from_encoded_bytes_unchecked(path) };\n let path = Path::new(path);\n (path, Some(goto))\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_parse_last_numbers() {\n fn parse(s: &str) -> (&str, Option) {\n let (p, g) = DocumentManager::parse_filename_goto(Path::new(s));\n (p.to_str().unwrap(), g)\n }\n\n assert_eq!(parse(\"123\"), (\"123\", None));\n assert_eq!(parse(\"abc\"), (\"abc\", None));\n assert_eq!(parse(\":123\"), (\":123\", None));\n assert_eq!(parse(\"abc:123\"), (\"abc\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"45:123\"), (\"45\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\":45:123\"), (\":45\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"abc:45:123\"), (\"abc\", Some(Point { x: 122, y: 44 })));\n assert_eq!(parse(\"abc:def:123\"), (\"abc:def\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"1:2:3\"), (\"1\", Some(Point { x: 2, y: 1 })));\n assert_eq!(parse(\"::3\"), (\":\", Some(Point { x: 0, y: 2 })));\n assert_eq!(parse(\"1::3\"), (\"1:\", Some(Point { x: 0, y: 2 })));\n assert_eq!(parse(\"\"), (\"\", None));\n assert_eq!(parse(\":\"), (\":\", None));\n assert_eq!(parse(\"::\"), (\"::\", None));\n assert_eq!(parse(\"a:1\"), (\"a\", Some(Point { x: 0, y: 0 })));\n assert_eq!(parse(\"1:a\"), (\"1:a\", None));\n assert_eq!(parse(\"file.txt:10\"), (\"file.txt\", Some(Point { x: 0, y: 9 })));\n assert_eq!(parse(\"file.txt:10:5\"), (\"file.txt\", Some(Point { x: 4, y: 9 })));\n }\n}\n"], ["/edit/src/arena/release.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![allow(clippy::mut_from_ref)]\n\nuse std::alloc::{AllocError, Allocator, Layout};\nuse std::cell::Cell;\nuse std::hint::cold_path;\nuse std::mem::MaybeUninit;\nuse std::ptr::{self, NonNull};\nuse std::{mem, slice};\n\nuse crate::helpers::*;\nuse crate::{apperr, sys};\n\nconst ALLOC_CHUNK_SIZE: usize = 64 * KIBI;\n\n/// An arena allocator.\n///\n/// If you have never used an arena allocator before, think of it as\n/// allocating objects on the stack, but the stack is *really* big.\n/// Each time you allocate, memory gets pushed at the end of the stack,\n/// each time you deallocate, memory gets popped from the end of the stack.\n///\n/// One reason you'd want to use this is obviously performance: It's very simple\n/// and so it's also very fast, >10x faster than your system allocator.\n///\n/// However, modern allocators such as `mimalloc` are just as fast, so why not use them?\n/// Because their performance comes at the cost of binary size and we can't have that.\n///\n/// The biggest benefit though is that it sometimes massively simplifies lifetime\n/// and memory management. This can best be seen by this project's UI code, which\n/// uses an arena to allocate a tree of UI nodes. This is infamously difficult\n/// to do in Rust, but not so when you got an arena allocator:\n/// All nodes have the same lifetime, so you can just use references.\n///\n///
\n///\n/// **Do not** push objects into the arena that require destructors.\n/// Destructors are not executed. Use a pool allocator for that.\n///\n///
\npub struct Arena {\n base: NonNull,\n capacity: usize,\n commit: Cell,\n offset: Cell,\n\n /// See [`super::debug`], which uses this for borrow tracking.\n #[cfg(debug_assertions)]\n pub(super) borrows: Cell,\n}\n\nimpl Arena {\n pub const fn empty() -> Self {\n Self {\n base: NonNull::dangling(),\n capacity: 0,\n commit: Cell::new(0),\n offset: Cell::new(0),\n\n #[cfg(debug_assertions)]\n borrows: Cell::new(0),\n }\n }\n\n pub fn new(capacity: usize) -> apperr::Result {\n let capacity = (capacity.max(1) + ALLOC_CHUNK_SIZE - 1) & !(ALLOC_CHUNK_SIZE - 1);\n let base = unsafe { sys::virtual_reserve(capacity)? };\n\n Ok(Self {\n base,\n capacity,\n commit: Cell::new(0),\n offset: Cell::new(0),\n\n #[cfg(debug_assertions)]\n borrows: Cell::new(0),\n })\n }\n\n pub fn is_empty(&self) -> bool {\n self.base == NonNull::dangling()\n }\n\n pub fn offset(&self) -> usize {\n self.offset.get()\n }\n\n /// \"Deallocates\" the memory in the arena down to the given offset.\n ///\n /// # Safety\n ///\n /// Obviously, this is GIGA UNSAFE. It runs no destructors and does not check\n /// whether the offset is valid. You better take care when using this function.\n pub unsafe fn reset(&self, to: usize) {\n // Fill the deallocated memory with 0xDD to aid debugging.\n if cfg!(debug_assertions) && self.offset.get() > to {\n let commit = self.commit.get();\n let len = (self.offset.get() + 128).min(commit) - to;\n unsafe { slice::from_raw_parts_mut(self.base.add(to).as_ptr(), len).fill(0xDD) };\n }\n\n self.offset.replace(to);\n }\n\n #[inline]\n pub(super) fn alloc_raw(\n &self,\n bytes: usize,\n alignment: usize,\n ) -> Result, AllocError> {\n let commit = self.commit.get();\n let offset = self.offset.get();\n\n let beg = (offset + alignment - 1) & !(alignment - 1);\n let end = beg + bytes;\n\n if end > commit {\n return self.alloc_raw_bump(beg, end);\n }\n\n if cfg!(debug_assertions) {\n let ptr = unsafe { self.base.add(offset) };\n let len = (end + 128).min(self.commit.get()) - offset;\n unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len).fill(0xCD) };\n }\n\n self.offset.replace(end);\n Ok(unsafe { NonNull::slice_from_raw_parts(self.base.add(beg), bytes) })\n }\n\n // With the code in `alloc_raw_bump()` out of the way, `alloc_raw()` compiles down to some super tight assembly.\n #[cold]\n fn alloc_raw_bump(&self, beg: usize, end: usize) -> Result, AllocError> {\n let offset = self.offset.get();\n let commit_old = self.commit.get();\n let commit_new = (end + ALLOC_CHUNK_SIZE - 1) & !(ALLOC_CHUNK_SIZE - 1);\n\n if commit_new > self.capacity\n || unsafe {\n sys::virtual_commit(self.base.add(commit_old), commit_new - commit_old).is_err()\n }\n {\n return Err(AllocError);\n }\n\n if cfg!(debug_assertions) {\n let ptr = unsafe { self.base.add(offset) };\n let len = (end + 128).min(self.commit.get()) - offset;\n unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len).fill(0xCD) };\n }\n\n self.commit.replace(commit_new);\n self.offset.replace(end);\n Ok(unsafe { NonNull::slice_from_raw_parts(self.base.add(beg), end - beg) })\n }\n\n #[allow(clippy::mut_from_ref)]\n pub fn alloc_uninit(&self) -> &mut MaybeUninit {\n let bytes = mem::size_of::();\n let alignment = mem::align_of::();\n let ptr = self.alloc_raw(bytes, alignment).unwrap();\n unsafe { ptr.cast().as_mut() }\n }\n\n #[allow(clippy::mut_from_ref)]\n pub fn alloc_uninit_slice(&self, count: usize) -> &mut [MaybeUninit] {\n let bytes = mem::size_of::() * count;\n let alignment = mem::align_of::();\n let ptr = self.alloc_raw(bytes, alignment).unwrap();\n unsafe { slice::from_raw_parts_mut(ptr.cast().as_ptr(), count) }\n }\n}\n\nimpl Drop for Arena {\n fn drop(&mut self) {\n if !self.is_empty() {\n unsafe { sys::virtual_release(self.base, self.capacity) };\n }\n }\n}\n\nimpl Default for Arena {\n fn default() -> Self {\n Self::empty()\n }\n}\n\nunsafe impl Allocator for Arena {\n fn allocate(&self, layout: Layout) -> Result, AllocError> {\n self.alloc_raw(layout.size(), layout.align())\n }\n\n fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> {\n let p = self.alloc_raw(layout.size(), layout.align())?;\n unsafe { p.cast::().as_ptr().write_bytes(0, p.len()) }\n Ok(p)\n }\n\n // While it is possible to shrink the tail end of the arena, it is\n // not very useful given the existence of scoped scratch arenas.\n unsafe fn deallocate(&self, _: NonNull, _: Layout) {}\n\n unsafe fn grow(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n debug_assert!(new_layout.size() >= old_layout.size());\n debug_assert!(new_layout.align() <= old_layout.align());\n\n let new_ptr;\n\n // Growing the given area is possible if it is at the end of the arena.\n if unsafe { ptr.add(old_layout.size()) == self.base.add(self.offset.get()) } {\n new_ptr = ptr;\n let delta = new_layout.size() - old_layout.size();\n // Assuming that the given ptr/length area is at the end of the arena,\n // we can just push more memory to the end of the arena to grow it.\n self.alloc_raw(delta, 1)?;\n } else {\n cold_path();\n\n new_ptr = self.allocate(new_layout)?.cast();\n\n // SAFETY: It's weird to me that this doesn't assert new_layout.size() >= old_layout.size(),\n // but neither does the stdlib code at the time of writing.\n // So, assuming that is not needed, this code is safe since it just copies the old data over.\n unsafe {\n ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), old_layout.size());\n self.deallocate(ptr, old_layout);\n }\n }\n\n Ok(NonNull::slice_from_raw_parts(new_ptr, new_layout.size()))\n }\n\n unsafe fn grow_zeroed(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe {\n // SAFETY: Same as grow().\n let ptr = self.grow(ptr, old_layout, new_layout)?;\n\n // SAFETY: At this point, `ptr` must be valid for `new_layout.size()` bytes,\n // allowing us to safely zero out the delta since `old_layout.size()`.\n ptr.cast::()\n .add(old_layout.size())\n .write_bytes(0, new_layout.size() - old_layout.size());\n\n Ok(ptr)\n }\n }\n\n unsafe fn shrink(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n debug_assert!(new_layout.size() <= old_layout.size());\n debug_assert!(new_layout.align() <= old_layout.align());\n\n let mut len = old_layout.size();\n\n // Shrinking the given area is possible if it is at the end of the arena.\n if unsafe { ptr.add(len) == self.base.add(self.offset.get()) } {\n self.offset.set(self.offset.get() - len + new_layout.size());\n len = new_layout.size();\n } else {\n debug_assert!(\n false,\n \"Did you call shrink_to_fit()? Only the last allocation can be shrunk!\"\n );\n }\n\n Ok(NonNull::slice_from_raw_parts(ptr, len))\n }\n}\n"], ["/edit/src/base64.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Base64 facilities.\n\nuse crate::arena::ArenaString;\n\nconst CHARSET: [u8; 64] = *b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/// One aspect of base64 is that the encoded length can be\n/// calculated accurately in advance, which is what this returns.\n#[inline]\npub fn encode_len(src_len: usize) -> usize {\n src_len.div_ceil(3) * 4\n}\n\n/// Encodes the given bytes as base64 and appends them to the destination string.\npub fn encode(dst: &mut ArenaString, src: &[u8]) {\n unsafe {\n let mut inp = src.as_ptr();\n let mut remaining = src.len();\n let dst = dst.as_mut_vec();\n\n let out_len = encode_len(src.len());\n // ... we can then use this fact to reserve space all at once.\n dst.reserve(out_len);\n\n // SAFETY: Getting a pointer to the reserved space is only safe\n // *after* calling `reserve()` as it may change the pointer.\n let mut out = dst.as_mut_ptr().add(dst.len());\n\n if remaining != 0 {\n // Translate chunks of 3 source bytes into 4 base64-encoded bytes.\n while remaining > 3 {\n // SAFETY: Thanks to `remaining > 3`, reading 4 bytes at once is safe.\n // This improves performance massively over a byte-by-byte approach,\n // because it allows us to byte-swap the read and use simple bit-shifts below.\n let val = u32::from_be((inp as *const u32).read_unaligned());\n inp = inp.add(3);\n remaining -= 3;\n\n *out = CHARSET[(val >> 26) as usize];\n out = out.add(1);\n *out = CHARSET[(val >> 20) as usize & 0x3f];\n out = out.add(1);\n *out = CHARSET[(val >> 14) as usize & 0x3f];\n out = out.add(1);\n *out = CHARSET[(val >> 8) as usize & 0x3f];\n out = out.add(1);\n }\n\n // Convert the remaining 1-3 bytes.\n let mut in1 = 0;\n let mut in2 = 0;\n\n // We can simplify the following logic by assuming that there's only 1\n // byte left. If there's >1 byte left, these two '=' will be overwritten.\n *out.add(3) = b'=';\n *out.add(2) = b'=';\n\n if remaining >= 3 {\n in2 = inp.add(2).read() as usize;\n *out.add(3) = CHARSET[in2 & 0x3f];\n }\n\n if remaining >= 2 {\n in1 = inp.add(1).read() as usize;\n *out.add(2) = CHARSET[(in1 << 2 | in2 >> 6) & 0x3f];\n }\n\n let in0 = inp.add(0).read() as usize;\n *out.add(1) = CHARSET[(in0 << 4 | in1 >> 4) & 0x3f];\n *out.add(0) = CHARSET[in0 >> 2];\n }\n\n dst.set_len(dst.len() + out_len);\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::encode;\n use crate::arena::{Arena, ArenaString};\n\n #[test]\n fn test_basic() {\n let arena = Arena::new(4 * 1024).unwrap();\n let enc = |s: &[u8]| {\n let mut dst = ArenaString::new_in(&arena);\n encode(&mut dst, s);\n dst\n };\n assert_eq!(enc(b\"\"), \"\");\n assert_eq!(enc(b\"a\"), \"YQ==\");\n assert_eq!(enc(b\"ab\"), \"YWI=\");\n assert_eq!(enc(b\"abc\"), \"YWJj\");\n assert_eq!(enc(b\"abcd\"), \"YWJjZA==\");\n assert_eq!(enc(b\"abcde\"), \"YWJjZGU=\");\n assert_eq!(enc(b\"abcdef\"), \"YWJjZGVm\");\n assert_eq!(enc(b\"abcdefg\"), \"YWJjZGVmZw==\");\n assert_eq!(enc(b\"abcdefgh\"), \"YWJjZGVmZ2g=\");\n assert_eq!(enc(b\"abcdefghi\"), \"YWJjZGVmZ2hp\");\n assert_eq!(enc(b\"abcdefghij\"), \"YWJjZGVmZ2hpag==\");\n assert_eq!(enc(b\"abcdefghijk\"), \"YWJjZGVmZ2hpams=\");\n assert_eq!(enc(b\"abcdefghijkl\"), \"YWJjZGVmZ2hpamts\");\n assert_eq!(enc(b\"abcdefghijklm\"), \"YWJjZGVmZ2hpamtsbQ==\");\n assert_eq!(enc(b\"abcdefghijklmN\"), \"YWJjZGVmZ2hpamtsbU4=\");\n assert_eq!(enc(b\"abcdefghijklmNO\"), \"YWJjZGVmZ2hpamtsbU5P\");\n assert_eq!(enc(b\"abcdefghijklmNOP\"), \"YWJjZGVmZ2hpamtsbU5PUA==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQ\"), \"YWJjZGVmZ2hpamtsbU5PUFE=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQR\"), \"YWJjZGVmZ2hpamtsbU5PUFFS\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRS\"), \"YWJjZGVmZ2hpamtsbU5PUFFSUw==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRST\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1Q=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTU\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RV\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUV\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVg==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVW\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVlc=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWX\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldY\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWXY\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldYWQ==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWXYZ\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldYWVo=\");\n }\n}\n"], ["/edit/src/bin/edit/draw_editor.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::num::ParseIntError;\n\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::icu;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_editor(ctx: &mut Context, state: &mut State) {\n if !matches!(state.wants_search.kind, StateSearchKind::Hidden | StateSearchKind::Disabled) {\n draw_search(ctx, state);\n }\n\n let size = ctx.size();\n // TODO: The layout code should be able to just figure out the height on its own.\n let height_reduction = match state.wants_search.kind {\n StateSearchKind::Search => 4,\n StateSearchKind::Replace => 5,\n _ => 2,\n };\n\n if let Some(doc) = state.documents.active() {\n ctx.textarea(\"textarea\", doc.buffer.clone());\n ctx.inherit_focus();\n } else {\n ctx.block_begin(\"empty\");\n ctx.block_end();\n }\n\n ctx.attr_intrinsic_size(Size { width: 0, height: size.height - height_reduction });\n}\n\nfn draw_search(ctx: &mut Context, state: &mut State) {\n if let Err(err) = icu::init() {\n error_log_add(ctx, state, err);\n state.wants_search.kind = StateSearchKind::Disabled;\n return;\n }\n\n let Some(doc) = state.documents.active() else {\n state.wants_search.kind = StateSearchKind::Hidden;\n return;\n };\n\n let mut action = None;\n let mut focus = StateSearchKind::Hidden;\n\n if state.wants_search.focus {\n state.wants_search.focus = false;\n focus = StateSearchKind::Search;\n\n // If the selection is empty, focus the search input field.\n // Otherwise, focus the replace input field, if it exists.\n if let Some(selection) = doc.buffer.borrow_mut().extract_user_selection(false) {\n state.search_needle = String::from_utf8_lossy_owned(selection);\n focus = state.wants_search.kind;\n }\n }\n\n ctx.block_begin(\"search\");\n ctx.attr_focus_well();\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::White));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::Black));\n {\n if ctx.contains_focus() && ctx.consume_shortcut(vk::ESCAPE) {\n state.wants_search.kind = StateSearchKind::Hidden;\n }\n\n ctx.table_begin(\"needle\");\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n {\n {\n ctx.table_next_row();\n ctx.label(\"label\", loc(LocId::SearchNeedleLabel));\n\n if ctx.editline(\"needle\", &mut state.search_needle) {\n action = Some(SearchAction::Search);\n }\n if !state.search_success {\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n }\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n if focus == StateSearchKind::Search {\n ctx.steal_focus();\n }\n if ctx.is_focused() && ctx.consume_shortcut(vk::RETURN) {\n action = Some(SearchAction::Search);\n }\n }\n\n if state.wants_search.kind == StateSearchKind::Replace {\n ctx.table_next_row();\n ctx.label(\"label\", loc(LocId::SearchReplacementLabel));\n\n ctx.editline(\"replacement\", &mut state.search_replacement);\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n if focus == StateSearchKind::Replace {\n ctx.steal_focus();\n }\n if ctx.is_focused() {\n if ctx.consume_shortcut(vk::RETURN) {\n action = Some(SearchAction::Replace);\n } else if ctx.consume_shortcut(kbmod::CTRL_ALT | vk::RETURN) {\n action = Some(SearchAction::ReplaceAll);\n }\n }\n }\n }\n ctx.table_end();\n\n ctx.table_begin(\"options\");\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n let mut change = false;\n let mut change_action = Some(SearchAction::Search);\n\n ctx.table_next_row();\n\n change |= ctx.checkbox(\n \"match-case\",\n loc(LocId::SearchMatchCase),\n &mut state.search_options.match_case,\n );\n change |= ctx.checkbox(\n \"whole-word\",\n loc(LocId::SearchWholeWord),\n &mut state.search_options.whole_word,\n );\n change |= ctx.checkbox(\n \"use-regex\",\n loc(LocId::SearchUseRegex),\n &mut state.search_options.use_regex,\n );\n if state.wants_search.kind == StateSearchKind::Replace\n && ctx.button(\"replace-all\", loc(LocId::SearchReplaceAll), ButtonStyle::default())\n {\n change = true;\n change_action = Some(SearchAction::ReplaceAll);\n }\n if ctx.button(\"close\", loc(LocId::SearchClose), ButtonStyle::default()) {\n state.wants_search.kind = StateSearchKind::Hidden;\n }\n\n if change {\n action = change_action;\n state.wants_search.focus = true;\n ctx.needs_rerender();\n }\n }\n ctx.table_end();\n }\n ctx.block_end();\n\n if let Some(action) = action {\n search_execute(ctx, state, action);\n }\n}\n\npub enum SearchAction {\n Search,\n Replace,\n ReplaceAll,\n}\n\npub fn search_execute(ctx: &mut Context, state: &mut State, action: SearchAction) {\n let Some(doc) = state.documents.active_mut() else {\n return;\n };\n\n state.search_success = match action {\n SearchAction::Search => {\n doc.buffer.borrow_mut().find_and_select(&state.search_needle, state.search_options)\n }\n SearchAction::Replace => doc.buffer.borrow_mut().find_and_replace(\n &state.search_needle,\n state.search_options,\n state.search_replacement.as_bytes(),\n ),\n SearchAction::ReplaceAll => doc.buffer.borrow_mut().find_and_replace_all(\n &state.search_needle,\n state.search_options,\n state.search_replacement.as_bytes(),\n ),\n }\n .is_ok();\n\n ctx.needs_rerender();\n}\n\npub fn draw_handle_save(ctx: &mut Context, state: &mut State) {\n if let Some(doc) = state.documents.active_mut() {\n if doc.path.is_some() {\n if let Err(err) = doc.save(None) {\n error_log_add(ctx, state, err);\n }\n } else {\n // No path? Show the file picker.\n state.wants_file_picker = StateFilePicker::SaveAs;\n state.wants_save = false;\n ctx.needs_rerender();\n }\n }\n\n state.wants_save = false;\n}\n\npub fn draw_handle_wants_close(ctx: &mut Context, state: &mut State) {\n let Some(doc) = state.documents.active() else {\n state.wants_close = false;\n return;\n };\n\n if !doc.buffer.borrow().is_dirty() {\n state.documents.remove_active();\n state.wants_close = false;\n ctx.needs_rerender();\n return;\n }\n\n enum Action {\n None,\n Save,\n Discard,\n Cancel,\n }\n let mut action = Action::None;\n\n ctx.modal_begin(\"unsaved-changes\", loc(LocId::UnsavedChangesDialogTitle));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n let contains_focus = ctx.contains_focus();\n\n ctx.label(\"description\", loc(LocId::UnsavedChangesDialogDescription));\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n if ctx.button(\n \"yes\",\n loc(LocId::UnsavedChangesDialogYes),\n ButtonStyle::default().accelerator('S'),\n ) {\n action = Action::Save;\n }\n ctx.inherit_focus();\n if ctx.button(\n \"no\",\n loc(LocId::UnsavedChangesDialogNo),\n ButtonStyle::default().accelerator('N'),\n ) {\n action = Action::Discard;\n }\n if ctx.button(\"cancel\", loc(LocId::Cancel), ButtonStyle::default()) {\n action = Action::Cancel;\n }\n\n // Handle accelerator shortcuts\n if contains_focus {\n if ctx.consume_shortcut(vk::S) {\n action = Action::Save;\n } else if ctx.consume_shortcut(vk::N) {\n action = Action::Discard;\n }\n }\n }\n ctx.table_end();\n }\n if ctx.modal_end() {\n action = Action::Cancel;\n }\n\n match action {\n Action::None => return,\n Action::Save => {\n state.wants_save = true;\n }\n Action::Discard => {\n state.documents.remove_active();\n state.wants_close = false;\n }\n Action::Cancel => {\n state.wants_exit = false;\n state.wants_close = false;\n }\n }\n\n ctx.needs_rerender();\n}\n\npub fn draw_goto_menu(ctx: &mut Context, state: &mut State) {\n let mut done = false;\n\n if let Some(doc) = state.documents.active_mut() {\n ctx.modal_begin(\"goto\", loc(LocId::FileGoto));\n {\n if ctx.editline(\"goto-line\", &mut state.goto_target) {\n state.goto_invalid = false;\n }\n if state.goto_invalid {\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n }\n\n ctx.attr_intrinsic_size(Size { width: 24, height: 1 });\n ctx.steal_focus();\n\n if ctx.consume_shortcut(vk::RETURN) {\n match validate_goto_point(&state.goto_target) {\n Ok(point) => {\n let mut buf = doc.buffer.borrow_mut();\n buf.cursor_move_to_logical(point);\n buf.make_cursor_visible();\n done = true;\n }\n Err(_) => state.goto_invalid = true,\n }\n ctx.needs_rerender();\n }\n }\n done |= ctx.modal_end();\n } else {\n done = true;\n }\n\n if done {\n state.wants_goto = false;\n state.goto_target.clear();\n state.goto_invalid = false;\n ctx.needs_rerender();\n }\n}\n\nfn validate_goto_point(line: &str) -> Result {\n let mut coords = [0; 2];\n let (y, x) = line.split_once(':').unwrap_or((line, \"0\"));\n // Using a loop here avoids 2 copies of the str->int code.\n // This makes the binary more compact.\n for (i, s) in [x, y].iter().enumerate() {\n coords[i] = s.parse::()?.saturating_sub(1);\n }\n Ok(Point { x: coords[0], y: coords[1] })\n}\n"], ["/edit/src/arena/debug.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![allow(clippy::missing_safety_doc, clippy::mut_from_ref)]\n\nuse std::alloc::{AllocError, Allocator, Layout};\nuse std::mem::{self, MaybeUninit};\nuse std::ptr::NonNull;\n\nuse super::release;\nuse crate::apperr;\n\n/// A debug wrapper for [`release::Arena`].\n///\n/// The problem with [`super::ScratchArena`] is that it only \"borrows\" an underlying\n/// [`release::Arena`]. Once the [`super::ScratchArena`] is dropped it resets the watermark\n/// of the underlying [`release::Arena`], freeing all allocations done since borrowing it.\n///\n/// It is completely valid for the same [`release::Arena`] to be borrowed multiple times at once,\n/// *as long as* you only use the most recent borrow. Bad example:\n/// ```should_panic\n/// use edit::arena::scratch_arena;\n///\n/// let mut scratch1 = scratch_arena(None);\n/// let mut scratch2 = scratch_arena(None);\n///\n/// let foo = scratch1.alloc_uninit::();\n///\n/// // This will also reset `scratch1`'s allocation.\n/// drop(scratch2);\n///\n/// *foo; // BOOM! ...if it wasn't for our debug wrapper.\n/// ```\n///\n/// To avoid this, this wraps the real [`release::Arena`] in a \"debug\" one, which pretends as if every\n/// instance of itself is a distinct [`release::Arena`] instance. Then we use this \"debug\" [`release::Arena`]\n/// for [`super::ScratchArena`] which allows us to track which borrow is the most recent one.\npub enum Arena {\n // Delegate is 'static, because release::Arena requires no lifetime\n // annotations, and so this mere debug helper cannot use them either.\n Delegated { delegate: &'static release::Arena, borrow: usize },\n Owned { arena: release::Arena },\n}\n\nimpl Drop for Arena {\n fn drop(&mut self) {\n if let Self::Delegated { delegate, borrow } = self {\n let borrows = delegate.borrows.get();\n assert_eq!(*borrow, borrows);\n delegate.borrows.set(borrows - 1);\n }\n }\n}\n\nimpl Default for Arena {\n fn default() -> Self {\n Self::empty()\n }\n}\n\nimpl Arena {\n pub const fn empty() -> Self {\n Self::Owned { arena: release::Arena::empty() }\n }\n\n pub fn new(capacity: usize) -> apperr::Result {\n Ok(Self::Owned { arena: release::Arena::new(capacity)? })\n }\n\n pub(super) fn delegated(delegate: &release::Arena) -> Self {\n let borrow = delegate.borrows.get() + 1;\n delegate.borrows.set(borrow);\n Self::Delegated { delegate: unsafe { mem::transmute(delegate) }, borrow }\n }\n\n #[inline]\n pub(super) fn delegate_target(&self) -> &release::Arena {\n match *self {\n Self::Delegated { delegate, borrow } => {\n assert!(\n borrow == delegate.borrows.get(),\n \"Arena already borrowed by a newer ScratchArena\"\n );\n delegate\n }\n Self::Owned { ref arena } => arena,\n }\n }\n\n #[inline]\n pub(super) fn delegate_target_unchecked(&self) -> &release::Arena {\n match self {\n Self::Delegated { delegate, .. } => delegate,\n Self::Owned { arena } => arena,\n }\n }\n\n pub fn offset(&self) -> usize {\n self.delegate_target().offset()\n }\n\n pub unsafe fn reset(&self, to: usize) {\n unsafe { self.delegate_target().reset(to) }\n }\n\n pub fn alloc_uninit(&self) -> &mut MaybeUninit {\n self.delegate_target().alloc_uninit()\n }\n\n pub fn alloc_uninit_slice(&self, count: usize) -> &mut [MaybeUninit] {\n self.delegate_target().alloc_uninit_slice(count)\n }\n}\n\nunsafe impl Allocator for Arena {\n fn allocate(&self, layout: Layout) -> Result, AllocError> {\n self.delegate_target().alloc_raw(layout.size(), layout.align())\n }\n\n fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> {\n self.delegate_target().allocate_zeroed(layout)\n }\n\n // While it is possible to shrink the tail end of the arena, it is\n // not very useful given the existence of scoped scratch arenas.\n unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) {\n unsafe { self.delegate_target().deallocate(ptr, layout) }\n }\n\n unsafe fn grow(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().grow(ptr, old_layout, new_layout) }\n }\n\n unsafe fn grow_zeroed(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().grow_zeroed(ptr, old_layout, new_layout) }\n }\n\n unsafe fn shrink(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().shrink(ptr, old_layout, new_layout) }\n }\n}\n"], ["/edit/src/arena/scratch.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Deref;\n\n#[cfg(debug_assertions)]\nuse super::debug;\nuse super::{Arena, release};\nuse crate::apperr;\nuse crate::helpers::*;\n\nstatic mut S_SCRATCH: [release::Arena; 2] =\n const { [release::Arena::empty(), release::Arena::empty()] };\n\n/// Initialize the scratch arenas with a given capacity.\n/// Call this before using [`scratch_arena`].\npub fn init(capacity: usize) -> apperr::Result<()> {\n unsafe {\n for s in &mut S_SCRATCH[..] {\n *s = release::Arena::new(capacity)?;\n }\n }\n Ok(())\n}\n\n/// Need an arena for temporary allocations? [`scratch_arena`] got you covered.\n/// Call [`scratch_arena`] and it'll return an [`Arena`] that resets when it goes out of scope.\n///\n/// ---\n///\n/// Most methods make just two kinds of allocations:\n/// * Interior: Temporary data that can be deallocated when the function returns.\n/// * Exterior: Data that is returned to the caller and must remain alive until the caller stops using it.\n///\n/// Such methods only have two lifetimes, for which you consequently also only need two arenas.\n/// ...even if your method calls other methods recursively! This is because the exterior allocations\n/// of a callee are simply interior allocations to the caller, and so on, recursively.\n///\n/// This works as long as the two arenas flip/flop between being used as interior/exterior allocator\n/// along the callstack. To ensure that is the case, we use a recursion counter in debug builds.\n///\n/// This approach was described among others at: \n///\n/// # Safety\n///\n/// If your function takes an [`Arena`] argument, you **MUST** pass it to `scratch_arena` as `Some(&arena)`.\npub fn scratch_arena(conflict: Option<&Arena>) -> ScratchArena<'static> {\n unsafe {\n #[cfg(test)]\n if S_SCRATCH[0].is_empty() {\n init(128 * 1024 * 1024).unwrap();\n }\n\n #[cfg(debug_assertions)]\n let conflict = conflict.map(|a| a.delegate_target_unchecked());\n\n let index = opt_ptr_eq(conflict, Some(&S_SCRATCH[0])) as usize;\n let arena = &S_SCRATCH[index];\n ScratchArena::new(arena)\n }\n}\n\n/// Borrows an [`Arena`] for temporary allocations.\n///\n/// See [`scratch_arena`].\n#[cfg(debug_assertions)]\npub struct ScratchArena<'a> {\n arena: debug::Arena,\n offset: usize,\n _phantom: std::marker::PhantomData<&'a ()>,\n}\n\n#[cfg(not(debug_assertions))]\npub struct ScratchArena<'a> {\n arena: &'a Arena,\n offset: usize,\n}\n\n#[cfg(debug_assertions)]\nimpl<'a> ScratchArena<'a> {\n fn new(arena: &'a release::Arena) -> Self {\n let offset = arena.offset();\n ScratchArena { arena: Arena::delegated(arena), _phantom: std::marker::PhantomData, offset }\n }\n}\n\n#[cfg(not(debug_assertions))]\nimpl<'a> ScratchArena<'a> {\n fn new(arena: &'a release::Arena) -> Self {\n let offset = arena.offset();\n ScratchArena { arena, offset }\n }\n}\n\nimpl Drop for ScratchArena<'_> {\n fn drop(&mut self) {\n unsafe { self.arena.reset(self.offset) };\n }\n}\n\n#[cfg(debug_assertions)]\nimpl Deref for ScratchArena<'_> {\n type Target = debug::Arena;\n\n fn deref(&self) -> &Self::Target {\n &self.arena\n }\n}\n\n#[cfg(not(debug_assertions))]\nimpl Deref for ScratchArena<'_> {\n type Target = Arena;\n\n fn deref(&self) -> &Self::Target {\n self.arena\n }\n}\n"], ["/edit/src/hash.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides fast, non-cryptographic hash functions.\n\n/// The venerable wyhash hash function.\n///\n/// It's fast, has good statistical properties, and is in the public domain.\n/// See: \n/// If you visit the link, you'll find that it was superseded by \"rapidhash\",\n/// but that's not particularly interesting for this project. rapidhash results\n/// in way larger assembly and isn't faster when hashing small amounts of data.\npub fn hash(mut seed: u64, data: &[u8]) -> u64 {\n unsafe {\n const S0: u64 = 0xa0761d6478bd642f;\n const S1: u64 = 0xe7037ed1a0b428db;\n const S2: u64 = 0x8ebc6af09c88c6e3;\n const S3: u64 = 0x589965cc75374cc3;\n\n let len = data.len();\n let mut p = data.as_ptr();\n let a;\n let b;\n\n seed ^= S0;\n\n if len <= 16 {\n if len >= 4 {\n a = (wyr4(p) << 32) | wyr4(p.add((len >> 3) << 2));\n b = (wyr4(p.add(len - 4)) << 32) | wyr4(p.add(len - 4 - ((len >> 3) << 2)));\n } else if len > 0 {\n a = wyr3(p, len);\n b = 0;\n } else {\n a = 0;\n b = 0;\n }\n } else {\n let mut i = len;\n if i > 48 {\n let mut seed1 = seed;\n let mut seed2 = seed;\n while {\n seed = wymix(wyr8(p) ^ S1, wyr8(p.add(8)) ^ seed);\n seed1 = wymix(wyr8(p.add(16)) ^ S2, wyr8(p.add(24)) ^ seed1);\n seed2 = wymix(wyr8(p.add(32)) ^ S3, wyr8(p.add(40)) ^ seed2);\n p = p.add(48);\n i -= 48;\n i > 48\n } {}\n seed ^= seed1 ^ seed2;\n }\n while i > 16 {\n seed = wymix(wyr8(p) ^ S1, wyr8(p.add(8)) ^ seed);\n i -= 16;\n p = p.add(16);\n }\n a = wyr8(p.offset(i as isize - 16));\n b = wyr8(p.offset(i as isize - 8));\n }\n\n wymix(S1 ^ (len as u64), wymix(a ^ S1, b ^ seed))\n }\n}\n\nunsafe fn wyr3(p: *const u8, k: usize) -> u64 {\n let p0 = unsafe { p.read() as u64 };\n let p1 = unsafe { p.add(k >> 1).read() as u64 };\n let p2 = unsafe { p.add(k - 1).read() as u64 };\n (p0 << 16) | (p1 << 8) | p2\n}\n\nunsafe fn wyr4(p: *const u8) -> u64 {\n unsafe { (p as *const u32).read_unaligned() as u64 }\n}\n\nunsafe fn wyr8(p: *const u8) -> u64 {\n unsafe { (p as *const u64).read_unaligned() }\n}\n\n// This is a weak mix function on its own. It may be worth considering\n// replacing external uses of this function with a stronger one.\n// On the other hand, it's very fast.\npub fn wymix(lhs: u64, rhs: u64) -> u64 {\n let lhs = lhs as u128;\n let rhs = rhs as u128;\n let r = lhs * rhs;\n (r >> 64) as u64 ^ (r as u64)\n}\n\npub fn hash_str(seed: u64, s: &str) -> u64 {\n hash(seed, s.as_bytes())\n}\n"], ["/edit/src/path.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Path related helpers.\n\nuse std::ffi::{OsStr, OsString};\nuse std::path::{Component, MAIN_SEPARATOR_STR, Path, PathBuf};\n\n/// Normalizes a given path by removing redundant components.\n/// The given path must be absolute (e.g. by joining it with the current working directory).\npub fn normalize(path: &Path) -> PathBuf {\n let mut res = PathBuf::with_capacity(path.as_os_str().as_encoded_bytes().len());\n let mut root_len = 0;\n\n for component in path.components() {\n match component {\n Component::Prefix(p) => res.push(p.as_os_str()),\n Component::RootDir => {\n res.push(OsStr::new(MAIN_SEPARATOR_STR));\n root_len = res.as_os_str().as_encoded_bytes().len();\n }\n Component::CurDir => {}\n Component::ParentDir => {\n // Get the length up to the parent directory\n if let Some(len) = res\n .parent()\n .map(|p| p.as_os_str().as_encoded_bytes().len())\n // Ensure we don't pop the root directory\n && len >= root_len\n {\n // Pop the last component from `res`.\n //\n // This can be replaced with a plain `res.as_mut_os_string().truncate(len)`\n // once `os_string_truncate` is stabilized (#133262).\n let mut bytes = res.into_os_string().into_encoded_bytes();\n bytes.truncate(len);\n res = PathBuf::from(unsafe { OsString::from_encoded_bytes_unchecked(bytes) });\n }\n }\n Component::Normal(p) => res.push(p),\n }\n }\n\n res\n}\n\n#[cfg(test)]\nmod tests {\n use std::ffi::OsString;\n use std::path::Path;\n\n use super::*;\n\n fn norm(s: &str) -> OsString {\n normalize(Path::new(s)).into_os_string()\n }\n\n #[cfg(unix)]\n #[test]\n fn test_unix() {\n assert_eq!(norm(\"/a/b/c\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/b/c/\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/./b\"), \"/a/b\");\n assert_eq!(norm(\"/a/b/../c\"), \"/a/c\");\n assert_eq!(norm(\"/../../a\"), \"/a\");\n assert_eq!(norm(\"/../\"), \"/\");\n assert_eq!(norm(\"/a//b/c\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/b/c/../../../../d\"), \"/d\");\n assert_eq!(norm(\"//\"), \"/\");\n }\n\n #[cfg(windows)]\n #[test]\n fn test_windows() {\n assert_eq!(norm(r\"C:\\a\\b\\c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\b\\c\\\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\.\\b\"), r\"C:\\a\\b\");\n assert_eq!(norm(r\"C:\\a\\b\\..\\c\"), r\"C:\\a\\c\");\n assert_eq!(norm(r\"C:\\..\\..\\a\"), r\"C:\\a\");\n assert_eq!(norm(r\"C:\\..\\\"), r\"C:\\\");\n assert_eq!(norm(r\"C:\\a\\\\b\\c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:/a\\b/c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\b\\c\\..\\..\\..\\..\\d\"), r\"C:\\d\");\n assert_eq!(norm(r\"\\\\server\\share\\path\"), r\"\\\\server\\share\\path\");\n }\n}\n"], ["/edit/src/document.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Abstractions over reading/writing arbitrary text containers.\n\nuse std::ffi::OsString;\nuse std::mem;\nuse std::ops::Range;\nuse std::path::PathBuf;\n\nuse crate::arena::{ArenaString, scratch_arena};\nuse crate::helpers::ReplaceRange as _;\n\n/// An abstraction over reading from text containers.\npub trait ReadableDocument {\n /// Read some bytes starting at (including) the given absolute offset.\n ///\n /// # Warning\n ///\n /// * Be lenient on inputs:\n /// * The given offset may be out of bounds and you MUST clamp it.\n /// * You should not assume that offsets are at grapheme cluster boundaries.\n /// * Be strict on outputs:\n /// * You MUST NOT break grapheme clusters across chunks.\n /// * You MUST NOT return an empty slice unless the offset is at or beyond the end.\n fn read_forward(&self, off: usize) -> &[u8];\n\n /// Read some bytes before (but not including) the given absolute offset.\n ///\n /// # Warning\n ///\n /// * Be lenient on inputs:\n /// * The given offset may be out of bounds and you MUST clamp it.\n /// * You should not assume that offsets are at grapheme cluster boundaries.\n /// * Be strict on outputs:\n /// * You MUST NOT break grapheme clusters across chunks.\n /// * You MUST NOT return an empty slice unless the offset is zero.\n fn read_backward(&self, off: usize) -> &[u8];\n}\n\n/// An abstraction over writing to text containers.\npub trait WriteableDocument: ReadableDocument {\n /// Replace the given range with the given bytes.\n ///\n /// # Warning\n ///\n /// * The given range may be out of bounds and you MUST clamp it.\n /// * The replacement may not be valid UTF8.\n fn replace(&mut self, range: Range, replacement: &[u8]);\n}\n\nimpl ReadableDocument for &[u8] {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = *self;\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = *self;\n &s[..off.min(s.len())]\n }\n}\n\nimpl ReadableDocument for String {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = self.as_bytes();\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = self.as_bytes();\n &s[..off.min(s.len())]\n }\n}\n\nimpl WriteableDocument for String {\n fn replace(&mut self, range: Range, replacement: &[u8]) {\n // `replacement` is not guaranteed to be valid UTF-8, so we need to sanitize it.\n let scratch = scratch_arena(None);\n let utf8 = ArenaString::from_utf8_lossy(&scratch, replacement);\n let src = match &utf8 {\n Ok(s) => s,\n Err(s) => s.as_str(),\n };\n\n // SAFETY: `range` is guaranteed to be on codepoint boundaries.\n unsafe { self.as_mut_vec() }.replace_range(range, src.as_bytes());\n }\n}\n\nimpl ReadableDocument for PathBuf {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = self.as_os_str().as_encoded_bytes();\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = self.as_os_str().as_encoded_bytes();\n &s[..off.min(s.len())]\n }\n}\n\nimpl WriteableDocument for PathBuf {\n fn replace(&mut self, range: Range, replacement: &[u8]) {\n let mut vec = mem::take(self).into_os_string().into_encoded_bytes();\n vec.replace_range(range, replacement);\n *self = unsafe { Self::from(OsString::from_encoded_bytes_unchecked(vec)) };\n }\n}\n"], ["/edit/src/oklab.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Oklab colorspace conversions.\n//!\n//! Implements Oklab as defined at: \n\n#![allow(clippy::excessive_precision)]\n\n/// An Oklab color with alpha.\npub struct Lab {\n pub l: f32,\n pub a: f32,\n pub b: f32,\n pub alpha: f32,\n}\n\n/// Converts a 32-bit sRGB color to Oklab.\npub fn srgb_to_oklab(color: u32) -> Lab {\n let r = SRGB_TO_RGB_LUT[(color & 0xff) as usize];\n let g = SRGB_TO_RGB_LUT[((color >> 8) & 0xff) as usize];\n let b = SRGB_TO_RGB_LUT[((color >> 16) & 0xff) as usize];\n let alpha = (color >> 24) as f32 * (1.0 / 255.0);\n\n let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;\n let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;\n let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;\n\n let l_ = cbrtf_est(l);\n let m_ = cbrtf_est(m);\n let s_ = cbrtf_est(s);\n\n Lab {\n l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,\n a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,\n b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,\n alpha,\n }\n}\n\n/// Converts an Oklab color to a 32-bit sRGB color.\npub fn oklab_to_srgb(c: Lab) -> u32 {\n let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;\n let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;\n let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;\n\n let l = l_ * l_ * l_;\n let m = m_ * m_ * m_;\n let s = s_ * s_ * s_;\n\n let r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;\n let g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;\n let b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s;\n\n let r = r.clamp(0.0, 1.0);\n let g = g.clamp(0.0, 1.0);\n let b = b.clamp(0.0, 1.0);\n let alpha = c.alpha.clamp(0.0, 1.0);\n\n let r = linear_to_srgb(r);\n let g = linear_to_srgb(g);\n let b = linear_to_srgb(b);\n let a = (alpha * 255.0) as u32;\n\n r | (g << 8) | (b << 16) | (a << 24)\n}\n\n/// Blends two 32-bit sRGB colors in the Oklab color space.\npub fn oklab_blend(dst: u32, src: u32) -> u32 {\n let dst = srgb_to_oklab(dst);\n let src = srgb_to_oklab(src);\n\n let inv_a = 1.0 - src.alpha;\n let l = src.l + dst.l * inv_a;\n let a = src.a + dst.a * inv_a;\n let b = src.b + dst.b * inv_a;\n let alpha = src.alpha + dst.alpha * inv_a;\n\n oklab_to_srgb(Lab { l, a, b, alpha })\n}\n\nfn linear_to_srgb(c: f32) -> u32 {\n (if c > 0.0031308 {\n 255.0 * 1.055 * c.powf(1.0 / 2.4) - 255.0 * 0.055\n } else {\n 255.0 * 12.92 * c\n }) as u32\n}\n\n#[inline]\nfn cbrtf_est(a: f32) -> f32 {\n // http://metamerist.com/cbrt/cbrt.htm showed a great estimator for the cube root:\n // f32_as_uint32_t / 3 + 709921077\n // It's similar to the well known \"fast inverse square root\" trick.\n // Lots of numbers around 709921077 perform at least equally well to 709921077,\n // and it is unknown how and why 709921077 was chosen specifically.\n let u: u32 = f32::to_bits(a); // evil f32ing point bit level hacking\n let u = u / 3 + 709921077; // what the fuck?\n let x: f32 = f32::from_bits(u);\n\n // One round of Newton's method. It follows the Wikipedia article at\n // https://en.wikipedia.org/wiki/Cube_root#Numerical_methods\n // For `a`s in the range between 0 and 1, this results in a maximum error of\n // less than 6.7e-4f, which is not good, but good enough for us, because\n // we're not an image editor. The benefit is that it's really fast.\n (1.0 / 3.0) * (a / (x * x) + (x + x)) // 1st iteration\n}\n\n#[rustfmt::skip]\n#[allow(clippy::excessive_precision)]\nconst SRGB_TO_RGB_LUT: [f32; 256] = [\n 0.0000000000, 0.0003035270, 0.0006070540, 0.0009105810, 0.0012141080, 0.0015176350, 0.0018211619, 0.0021246888, 0.0024282159, 0.0027317430, 0.0030352699, 0.0033465356, 0.0036765069, 0.0040247170, 0.0043914421, 0.0047769533,\n 0.0051815170, 0.0056053917, 0.0060488326, 0.0065120910, 0.0069954102, 0.0074990317, 0.0080231922, 0.0085681248, 0.0091340570, 0.0097212177, 0.0103298230, 0.0109600937, 0.0116122449, 0.0122864870, 0.0129830306, 0.0137020806,\n 0.0144438436, 0.0152085144, 0.0159962922, 0.0168073755, 0.0176419523, 0.0185002182, 0.0193823613, 0.0202885624, 0.0212190095, 0.0221738834, 0.0231533647, 0.0241576303, 0.0251868572, 0.0262412224, 0.0273208916, 0.0284260381,\n 0.0295568332, 0.0307134409, 0.0318960287, 0.0331047624, 0.0343398079, 0.0356013142, 0.0368894450, 0.0382043645, 0.0395462364, 0.0409151986, 0.0423114114, 0.0437350273, 0.0451862030, 0.0466650836, 0.0481718220, 0.0497065634,\n 0.0512694679, 0.0528606549, 0.0544802807, 0.0561284944, 0.0578054339, 0.0595112406, 0.0612460710, 0.0630100295, 0.0648032799, 0.0666259527, 0.0684781820, 0.0703601092, 0.0722718611, 0.0742135793, 0.0761853904, 0.0781874284,\n 0.0802198276, 0.0822827145, 0.0843762159, 0.0865004659, 0.0886556059, 0.0908417329, 0.0930589810, 0.0953074843, 0.0975873619, 0.0998987406, 0.1022417471, 0.1046164930, 0.1070231125, 0.1094617173, 0.1119324341, 0.1144353822,\n 0.1169706732, 0.1195384338, 0.1221387982, 0.1247718409, 0.1274376959, 0.1301364899, 0.1328683347, 0.1356333494, 0.1384316236, 0.1412633061, 0.1441284865, 0.1470272839, 0.1499598026, 0.1529261619, 0.1559264660, 0.1589608639,\n 0.1620294005, 0.1651322246, 0.1682693958, 0.1714410931, 0.1746473908, 0.1778884083, 0.1811642349, 0.1844749898, 0.1878207624, 0.1912016720, 0.1946178079, 0.1980693042, 0.2015562356, 0.2050787061, 0.2086368501, 0.2122307271,\n 0.2158605307, 0.2195262313, 0.2232279778, 0.2269658893, 0.2307400703, 0.2345506549, 0.2383976579, 0.2422811985, 0.2462013960, 0.2501583695, 0.2541521788, 0.2581829131, 0.2622507215, 0.2663556635, 0.2704978585, 0.2746773660,\n 0.2788943350, 0.2831487954, 0.2874408960, 0.2917706966, 0.2961383164, 0.3005438447, 0.3049873710, 0.3094689548, 0.3139887452, 0.3185468316, 0.3231432438, 0.3277781308, 0.3324515820, 0.3371636569, 0.3419144452, 0.3467040956,\n 0.3515326977, 0.3564002514, 0.3613068759, 0.3662526906, 0.3712377846, 0.3762622178, 0.3813261092, 0.3864295185, 0.3915725648, 0.3967553079, 0.4019778669, 0.4072403014, 0.4125427008, 0.4178851545, 0.4232677519, 0.4286905527,\n 0.4341537058, 0.4396572411, 0.4452012479, 0.4507858455, 0.4564110637, 0.4620770514, 0.4677838385, 0.4735315442, 0.4793202281, 0.4851499796, 0.4910208881, 0.4969330430, 0.5028865933, 0.5088814497, 0.5149177909, 0.5209956765,\n 0.5271152258, 0.5332764983, 0.5394796133, 0.5457245708, 0.5520114899, 0.5583404899, 0.5647116303, 0.5711249113, 0.5775805116, 0.5840784907, 0.5906189084, 0.5972018838, 0.6038274169, 0.6104956269, 0.6172066331, 0.6239604354,\n 0.6307572126, 0.6375969648, 0.6444797516, 0.6514056921, 0.6583748460, 0.6653873324, 0.6724432111, 0.6795425415, 0.6866854429, 0.6938719153, 0.7011020184, 0.7083759308, 0.7156936526, 0.7230552435, 0.7304608822, 0.7379105687,\n 0.7454043627, 0.7529423237, 0.7605246305, 0.7681512833, 0.7758223414, 0.7835379243, 0.7912980318, 0.7991028428, 0.8069523573, 0.8148466945, 0.8227858543, 0.8307699561, 0.8387991190, 0.8468732834, 0.8549926877, 0.8631572723,\n 0.8713672161, 0.8796223402, 0.8879231811, 0.8962693810, 0.9046613574, 0.9130986929, 0.9215820432, 0.9301108718, 0.9386858940, 0.9473065734, 0.9559735060, 0.9646862745, 0.9734454751, 0.9822505713, 0.9911022186, 1.0000000000,\n];\n"], ["/edit/src/bin/edit/localization.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena::scratch_arena;\nuse edit::helpers::AsciiStringHelpers;\nuse edit::sys;\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum LocId {\n Ctrl,\n Alt,\n Shift,\n\n Ok,\n Yes,\n No,\n Cancel,\n Always,\n\n // File menu\n File,\n FileNew,\n FileOpen,\n FileSave,\n FileSaveAs,\n FileClose,\n FileExit,\n FileGoto,\n\n // Edit menu\n Edit,\n EditUndo,\n EditRedo,\n EditCut,\n EditCopy,\n EditPaste,\n EditFind,\n EditReplace,\n EditSelectAll,\n\n // View menu\n View,\n ViewFocusStatusbar,\n ViewWordWrap,\n ViewGoToFile,\n\n // Help menu\n Help,\n HelpAbout,\n\n // Exit dialog\n UnsavedChangesDialogTitle,\n UnsavedChangesDialogDescription,\n UnsavedChangesDialogYes,\n UnsavedChangesDialogNo,\n\n // About dialog\n AboutDialogTitle,\n AboutDialogVersion,\n\n // Shown when the clipboard size exceeds the limit for OSC 52\n LargeClipboardWarningLine1,\n LargeClipboardWarningLine2,\n LargeClipboardWarningLine3,\n SuperLargeClipboardWarning,\n\n // Warning dialog\n WarningDialogTitle,\n\n // Error dialog\n ErrorDialogTitle,\n ErrorIcuMissing,\n\n SearchNeedleLabel,\n SearchReplacementLabel,\n SearchMatchCase,\n SearchWholeWord,\n SearchUseRegex,\n SearchReplaceAll,\n SearchClose,\n\n EncodingReopen,\n EncodingConvert,\n\n IndentationTabs,\n IndentationSpaces,\n\n SaveAsDialogPathLabel,\n SaveAsDialogNameLabel,\n\n FileOverwriteWarning,\n FileOverwriteWarningDescription,\n\n Count,\n}\n\n#[allow(non_camel_case_types)]\n#[derive(Clone, Copy, PartialEq, Eq)]\nenum LangId {\n // Base language. It's always the first one.\n en,\n\n // Other languages. Sorted alphabetically.\n de,\n es,\n fr,\n it,\n ja,\n ko,\n pt_br,\n ru,\n zh_hans,\n zh_hant,\n\n Count,\n}\n\n#[rustfmt::skip]\nconst S_LANG_LUT: [[&str; LangId::Count as usize]; LocId::Count as usize] = [\n // Ctrl (the keyboard key)\n [\n /* en */ \"Ctrl\",\n /* de */ \"Strg\",\n /* es */ \"Ctrl\",\n /* fr */ \"Ctrl\",\n /* it */ \"Ctrl\",\n /* ja */ \"Ctrl\",\n /* ko */ \"Ctrl\",\n /* pt_br */ \"Ctrl\",\n /* ru */ \"Ctrl\",\n /* zh_hans */ \"Ctrl\",\n /* zh_hant */ \"Ctrl\",\n ],\n // Alt (the keyboard key)\n [\n /* en */ \"Alt\",\n /* de */ \"Alt\",\n /* es */ \"Alt\",\n /* fr */ \"Alt\",\n /* it */ \"Alt\",\n /* ja */ \"Alt\",\n /* ko */ \"Alt\",\n /* pt_br */ \"Alt\",\n /* ru */ \"Alt\",\n /* zh_hans */ \"Alt\",\n /* zh_hant */ \"Alt\",\n ],\n // Shift (the keyboard key)\n [\n /* en */ \"Shift\",\n /* de */ \"Umschalt\",\n /* es */ \"Mayús\",\n /* fr */ \"Maj\",\n /* it */ \"Maiusc\",\n /* ja */ \"Shift\",\n /* ko */ \"Shift\",\n /* pt_br */ \"Shift\",\n /* ru */ \"Shift\",\n /* zh_hans */ \"Shift\",\n /* zh_hant */ \"Shift\",\n ],\n\n // Ok (used as a common dialog button)\n [\n /* en */ \"Ok\",\n /* de */ \"OK\",\n /* es */ \"Aceptar\",\n /* fr */ \"OK\",\n /* it */ \"OK\",\n /* ja */ \"OK\",\n /* ko */ \"확인\",\n /* pt_br */ \"OK\",\n /* ru */ \"ОК\",\n /* zh_hans */ \"确定\",\n /* zh_hant */ \"確定\",\n ],\n // Yes (used as a common dialog button)\n [\n /* en */ \"Yes\",\n /* de */ \"Ja\",\n /* es */ \"Sí\",\n /* fr */ \"Oui\",\n /* it */ \"Sì\",\n /* ja */ \"はい\",\n /* ko */ \"예\",\n /* pt_br */ \"Sim\",\n /* ru */ \"Да\",\n /* zh_hans */ \"是\",\n /* zh_hant */ \"是\",\n ],\n // No (used as a common dialog button)\n [\n /* en */ \"No\",\n /* de */ \"Nein\",\n /* es */ \"No\",\n /* fr */ \"Non\",\n /* it */ \"No\",\n /* ja */ \"いいえ\",\n /* ko */ \"아니오\",\n /* pt_br */ \"Não\",\n /* ru */ \"Нет\",\n /* zh_hans */ \"否\",\n /* zh_hant */ \"否\",\n ],\n // Cancel (used as a common dialog button)\n [\n /* en */ \"Cancel\",\n /* de */ \"Abbrechen\",\n /* es */ \"Cancelar\",\n /* fr */ \"Annuler\",\n /* it */ \"Annulla\",\n /* ja */ \"キャンセル\",\n /* ko */ \"취소\",\n /* pt_br */ \"Cancelar\",\n /* ru */ \"Отмена\",\n /* zh_hans */ \"取消\",\n /* zh_hant */ \"取消\",\n ],\n // Always (used as a common dialog button)\n [\n /* en */ \"Always\",\n /* de */ \"Immer\",\n /* es */ \"Siempre\",\n /* fr */ \"Toujours\",\n /* it */ \"Sempre\",\n /* ja */ \"常に\",\n /* ko */ \"항상\",\n /* pt_br */ \"Sempre\",\n /* ru */ \"Всегда\",\n /* zh_hans */ \"总是\",\n /* zh_hant */ \"總是\",\n ],\n\n // File (a menu bar item)\n [\n /* en */ \"File\",\n /* de */ \"Datei\",\n /* es */ \"Archivo\",\n /* fr */ \"Fichier\",\n /* it */ \"File\",\n /* ja */ \"ファイル\",\n /* ko */ \"파일\",\n /* pt_br */ \"Arquivo\",\n /* ru */ \"Файл\",\n /* zh_hans */ \"文件\",\n /* zh_hant */ \"檔案\",\n ],\n // FileNew\n [\n /* en */ \"New File\",\n /* de */ \"Neue Datei\",\n /* es */ \"Nuevo archivo\",\n /* fr */ \"Nouveau fichier\",\n /* it */ \"Nuovo file\",\n /* ja */ \"新規ファイル\",\n /* ko */ \"새 파일\",\n /* pt_br */ \"Novo arquivo\",\n /* ru */ \"Новый файл\",\n /* zh_hans */ \"新建文件\",\n /* zh_hant */ \"新增檔案\",\n ],\n // FileOpen\n [\n /* en */ \"Open File…\",\n /* de */ \"Datei öffnen…\",\n /* es */ \"Abrir archivo…\",\n /* fr */ \"Ouvrir un fichier…\",\n /* it */ \"Apri file…\",\n /* ja */ \"ファイルを開く…\",\n /* ko */ \"파일 열기…\",\n /* pt_br */ \"Abrir arquivo…\",\n /* ru */ \"Открыть файл…\",\n /* zh_hans */ \"打开文件…\",\n /* zh_hant */ \"開啟檔案…\",\n ],\n // FileSave\n [\n /* en */ \"Save\",\n /* de */ \"Speichern\",\n /* es */ \"Guardar\",\n /* fr */ \"Enregistrer\",\n /* it */ \"Salva\",\n /* ja */ \"保存\",\n /* ko */ \"저장\",\n /* pt_br */ \"Salvar\",\n /* ru */ \"Сохранить\",\n /* zh_hans */ \"保存\",\n /* zh_hant */ \"儲存\",\n ],\n // FileSaveAs\n [\n /* en */ \"Save As…\",\n /* de */ \"Speichern unter…\",\n /* es */ \"Guardar como…\",\n /* fr */ \"Enregistrer sous…\",\n /* it */ \"Salva come…\",\n /* ja */ \"名前を付けて保存…\",\n /* ko */ \"다른 이름으로 저장…\",\n /* pt_br */ \"Salvar como…\",\n /* ru */ \"Сохранить как…\",\n /* zh_hans */ \"另存为…\",\n /* zh_hant */ \"另存新檔…\",\n ],\n // FileClose\n [\n /* en */ \"Close File\",\n /* de */ \"Datei schließen\",\n /* es */ \"Cerrar archivo\",\n /* fr */ \"Fermer le fichier\",\n /* it */ \"Chiudi file\",\n /* ja */ \"ファイルを閉じる\",\n /* ko */ \"파일 닫기\",\n /* pt_br */ \"Fechar arquivo\",\n /* ru */ \"Закрыть файл\",\n /* zh_hans */ \"关闭文件\",\n /* zh_hant */ \"關閉檔案\",\n ],\n // FileExit\n [\n /* en */ \"Exit\",\n /* de */ \"Beenden\",\n /* es */ \"Salir\",\n /* fr */ \"Quitter\",\n /* it */ \"Esci\",\n /* ja */ \"終了\",\n /* ko */ \"종료\",\n /* pt_br */ \"Sair\",\n /* ru */ \"Выход\",\n /* zh_hans */ \"退出\",\n /* zh_hant */ \"退出\",\n ],\n // FileGoto\n [\n /* en */ \"Go to Line:Column…\",\n /* de */ \"Gehe zu Zeile:Spalte…\",\n /* es */ \"Ir a línea:columna…\",\n /* fr */ \"Aller à la ligne:colonne…\",\n /* it */ \"Vai a riga:colonna…\",\n /* ja */ \"行:列へ移動…\",\n /* ko */ \"행:열로 이동…\",\n /* pt_br */ \"Ir para linha:coluna…\",\n /* ru */ \"Перейти к строке:столбцу…\",\n /* zh_hans */ \"转到行:列…\",\n /* zh_hant */ \"跳至行:列…\",\n ],\n\n // Edit (a menu bar item)\n [\n /* en */ \"Edit\",\n /* de */ \"Bearbeiten\",\n /* es */ \"Editar\",\n /* fr */ \"Édition\",\n /* it */ \"Modifica\",\n /* ja */ \"編集\",\n /* ko */ \"편집\",\n /* pt_br */ \"Editar\",\n /* ru */ \"Правка\",\n /* zh_hans */ \"编辑\",\n /* zh_hant */ \"編輯\",\n ],\n // EditUndo\n [\n /* en */ \"Undo\",\n /* de */ \"Rückgängig\",\n /* es */ \"Deshacer\",\n /* fr */ \"Annuler\",\n /* it */ \"Annulla\",\n /* ja */ \"元に戻す\",\n /* ko */ \"실행 취소\",\n /* pt_br */ \"Desfazer\",\n /* ru */ \"Отменить\",\n /* zh_hans */ \"撤销\",\n /* zh_hant */ \"復原\",\n ],\n // EditRedo\n [\n /* en */ \"Redo\",\n /* de */ \"Wiederholen\",\n /* es */ \"Rehacer\",\n /* fr */ \"Rétablir\",\n /* it */ \"Ripeti\",\n /* ja */ \"やり直し\",\n /* ko */ \"다시 실행\",\n /* pt_br */ \"Refazer\",\n /* ru */ \"Повторить\",\n /* zh_hans */ \"重做\",\n /* zh_hant */ \"重做\",\n ],\n // EditCut\n [\n /* en */ \"Cut\",\n /* de */ \"Ausschneiden\",\n /* es */ \"Cortar\",\n /* fr */ \"Couper\",\n /* it */ \"Taglia\",\n /* ja */ \"切り取り\",\n /* ko */ \"잘라내기\",\n /* pt_br */ \"Cortar\",\n /* ru */ \"Вырезать\",\n /* zh_hans */ \"剪切\",\n /* zh_hant */ \"剪下\",\n ],\n // EditCopy\n [\n /* en */ \"Copy\",\n /* de */ \"Kopieren\",\n /* es */ \"Copiar\",\n /* fr */ \"Copier\",\n /* it */ \"Copia\",\n /* ja */ \"コピー\",\n /* ko */ \"복사\",\n /* pt_br */ \"Copiar\",\n /* ru */ \"Копировать\",\n /* zh_hans */ \"复制\",\n /* zh_hant */ \"複製\",\n ],\n // EditPaste\n [\n /* en */ \"Paste\",\n /* de */ \"Einfügen\",\n /* es */ \"Pegar\",\n /* fr */ \"Coller\",\n /* it */ \"Incolla\",\n /* ja */ \"貼り付け\",\n /* ko */ \"붙여넣기\",\n /* pt_br */ \"Colar\",\n /* ru */ \"Вставить\",\n /* zh_hans */ \"粘贴\",\n /* zh_hant */ \"貼上\",\n ],\n // EditFind\n [\n /* en */ \"Find\",\n /* de */ \"Suchen\",\n /* es */ \"Buscar\",\n /* fr */ \"Rechercher\",\n /* it */ \"Trova\",\n /* ja */ \"検索\",\n /* ko */ \"찾기\",\n /* pt_br */ \"Encontrar\",\n /* ru */ \"Найти\",\n /* zh_hans */ \"查找\",\n /* zh_hant */ \"尋找\",\n ],\n // EditReplace\n [\n /* en */ \"Replace\",\n /* de */ \"Ersetzen\",\n /* es */ \"Reemplazar\",\n /* fr */ \"Remplacer\",\n /* it */ \"Sostituisci\",\n /* ja */ \"置換\",\n /* ko */ \"바꾸기\",\n /* pt_br */ \"Substituir\",\n /* ru */ \"Заменить\",\n /* zh_hans */ \"替换\",\n /* zh_hant */ \"取代\",\n ],\n // EditSelectAll\n [\n /* en */ \"Select All\",\n /* de */ \"Alles auswählen\",\n /* es */ \"Seleccionar todo\",\n /* fr */ \"Tout sélectionner\",\n /* it */ \"Seleziona tutto\",\n /* ja */ \"すべて選択\",\n /* ko */ \"모두 선택\",\n /* pt_br */ \"Selecionar tudo\",\n /* ru */ \"Выделить всё\",\n /* zh_hans */ \"全选\",\n /* zh_hant */ \"全選\"\n ],\n\n // View (a menu bar item)\n [\n /* en */ \"View\",\n /* de */ \"Ansicht\",\n /* es */ \"Ver\",\n /* fr */ \"Affichage\",\n /* it */ \"Visualizza\",\n /* ja */ \"表示\",\n /* ko */ \"보기\",\n /* pt_br */ \"Exibir\",\n /* ru */ \"Вид\",\n /* zh_hans */ \"视图\",\n /* zh_hant */ \"檢視\",\n ],\n // ViewFocusStatusbar\n [\n /* en */ \"Focus Statusbar\",\n /* de */ \"Statusleiste fokussieren\",\n /* es */ \"Enfocar barra de estado\",\n /* fr */ \"Activer la barre d’état\",\n /* it */ \"Attiva barra di stato\",\n /* ja */ \"ステータスバーにフォーカス\",\n /* ko */ \"상태 표시줄로 포커스 이동\",\n /* pt_br */ \"Focar barra de status\",\n /* ru */ \"Фокус на строку состояния\",\n /* zh_hans */ \"聚焦状态栏\",\n /* zh_hant */ \"聚焦狀態列\",\n ],\n // ViewWordWrap\n [\n /* en */ \"Word Wrap\",\n /* de */ \"Zeilenumbruch\",\n /* es */ \"Ajuste de línea\",\n /* fr */ \"Retour automatique à la ligne\",\n /* it */ \"A capo automatico\",\n /* ja */ \"折り返し\",\n /* ko */ \"자동 줄 바꿈\",\n /* pt_br */ \"Quebra de linha\",\n /* ru */ \"Перенос слов\",\n /* zh_hans */ \"自动换行\",\n /* zh_hant */ \"自動換行\",\n ],\n // ViewGoToFile\n [\n /* en */ \"Go to File…\",\n /* de */ \"Gehe zu Datei…\",\n /* es */ \"Ir a archivo…\",\n /* fr */ \"Aller au fichier…\",\n /* it */ \"Vai al file…\",\n /* ja */ \"ファイルへ移動…\",\n /* ko */ \"파일로 이동…\",\n /* pt_br */ \"Ir para arquivo…\",\n /* ru */ \"Перейти к файлу…\",\n /* zh_hans */ \"转到文件…\",\n /* zh_hant */ \"跳至檔案…\",\n ],\n\n // Help (a menu bar item)\n [\n /* en */ \"Help\",\n /* de */ \"Hilfe\",\n /* es */ \"Ayuda\",\n /* fr */ \"Aide\",\n /* it */ \"Aiuto\",\n /* ja */ \"ヘルプ\",\n /* ko */ \"도움말\",\n /* pt_br */ \"Ajuda\",\n /* ru */ \"Помощь\",\n /* zh_hans */ \"帮助\",\n /* zh_hant */ \"幫助\",\n ],\n // HelpAbout\n [\n /* en */ \"About\",\n /* de */ \"Über\",\n /* es */ \"Acerca de\",\n /* fr */ \"À propos\",\n /* it */ \"Informazioni\",\n /* ja */ \"情報\",\n /* ko */ \"정보\",\n /* pt_br */ \"Sobre\",\n /* ru */ \"О программе\",\n /* zh_hans */ \"关于\",\n /* zh_hant */ \"關於\",\n ],\n\n // UnsavedChangesDialogTitle\n [\n /* en */ \"Unsaved Changes\",\n /* de */ \"Ungespeicherte Änderungen\",\n /* es */ \"Cambios sin guardar\",\n /* fr */ \"Modifications non enregistrées\",\n /* it */ \"Modifiche non salvate\",\n /* ja */ \"未保存の変更\",\n /* ko */ \"저장되지 않은 변경 사항\",\n /* pt_br */ \"Alterações não salvas\",\n /* ru */ \"Несохраненные изменения\",\n /* zh_hans */ \"未保存的更改\",\n /* zh_hant */ \"未儲存的變更\",\n ],\n // UnsavedChangesDialogDescription\n [\n /* en */ \"Do you want to save the changes you made?\",\n /* de */ \"Möchten Sie die vorgenommenen Änderungen speichern?\",\n /* es */ \"¿Desea guardar los cambios realizados?\",\n /* fr */ \"Voulez-vous enregistrer les modifications apportées ?\",\n /* it */ \"Vuoi salvare le modifiche apportate?\",\n /* ja */ \"変更内容を保存しますか?\",\n /* ko */ \"변경한 내용을 저장하시겠습니까?\",\n /* pt_br */ \"Deseja salvar as alterações feitas?\",\n /* ru */ \"Вы хотите сохранить внесённые изменения?\",\n /* zh_hans */ \"您要保存所做的更改吗?\",\n /* zh_hant */ \"您要保存所做的變更嗎?\",\n ],\n // UnsavedChangesDialogYes\n [\n /* en */ \"Save\",\n /* de */ \"Speichern\",\n /* es */ \"Guardar\",\n /* fr */ \"Enregistrer\",\n /* it */ \"Salva\",\n /* ja */ \"保存する\",\n /* ko */ \"저장\",\n /* pt_br */ \"Salvar\",\n /* ru */ \"Сохранить\",\n /* zh_hans */ \"保存\",\n /* zh_hant */ \"儲存\",\n ],\n // UnsavedChangesDialogNo\n [\n /* en */ \"Don't Save\",\n /* de */ \"Nicht speichern\",\n /* es */ \"No guardar\",\n /* fr */ \"Ne pas enregistrer\",\n /* it */ \"Non salvare\",\n /* ja */ \"保存しない\",\n /* ko */ \"저장 안 함\",\n /* pt_br */ \"Não salvar\",\n /* ru */ \"Не сохранять\",\n /* zh_hans */ \"不保存\",\n /* zh_hant */ \"不儲存\",\n ],\n\n // AboutDialogTitle\n [\n /* en */ \"About\",\n /* de */ \"Über\",\n /* es */ \"Acerca de\",\n /* fr */ \"À propos\",\n /* it */ \"Informazioni\",\n /* ja */ \"情報\",\n /* ko */ \"정보\",\n /* pt_br */ \"Sobre\",\n /* ru */ \"О программе\",\n /* zh_hans */ \"关于\",\n /* zh_hant */ \"關於\",\n ],\n // AboutDialogVersion\n [\n /* en */ \"Version: \",\n /* de */ \"Version: \",\n /* es */ \"Versión: \",\n /* fr */ \"Version : \",\n /* it */ \"Versione: \",\n /* ja */ \"バージョン: \",\n /* ko */ \"버전: \",\n /* pt_br */ \"Versão: \",\n /* ru */ \"Версия: \",\n /* zh_hans */ \"版本: \",\n /* zh_hant */ \"版本: \",\n ],\n\n // Shown when the clipboard size exceeds the limit for OSC 52\n // LargeClipboardWarningLine1\n [\n /* en */ \"Text you copy is shared with the terminal clipboard.\",\n /* de */ \"Der kopierte Text wird mit der Terminal-Zwischenablage geteilt.\",\n /* es */ \"El texto que copies se comparte con el portapapeles del terminal.\",\n /* fr */ \"Le texte que vous copiez est partagé avec le presse-papiers du terminal.\",\n /* it */ \"Il testo copiato viene condiviso con gli appunti del terminale.\",\n /* ja */ \"コピーしたテキストはターミナルのクリップボードと共有されます。\",\n /* ko */ \"복사한 텍스트가 터미널 클립보드와 공유됩니다.\",\n /* pt_br */ \"O texto copiado é compartilhado com a área de transferência do terminal.\",\n /* ru */ \"Скопированный текст передаётся в буфер обмена терминала.\",\n /* zh_hans */ \"你复制的文本将共享到终端剪贴板。\",\n /* zh_hant */ \"您複製的文字將會與終端機剪貼簿分享。\",\n ],\n // LargeClipboardWarningLine2\n [\n /* en */ \"You copied {size} which may take a long time to share.\",\n /* de */ \"Sie haben {size} kopiert. Das Weitergeben könnte länger dauern.\",\n /* es */ \"Copiaste {size}, lo que puede tardar en compartirse.\",\n /* fr */ \"Vous avez copié {size}, ce qui peut être long à partager.\",\n /* it */ \"Hai copiato {size}, potrebbe richiedere molto tempo per condividerlo.\",\n /* ja */ \"{size} をコピーしました。共有に時間がかかる可能性があります。\",\n /* ko */ \"{size}를 복사했습니다. 공유하는 데 시간이 오래 걸릴 수 있습니다.\",\n /* pt_br */ \"Você copiou {size}, o que pode demorar para compartilhar.\",\n /* ru */ \"Вы скопировали {size}; передача может занять много времени.\",\n /* zh_hans */ \"你复制了 {size},共享可能需要较长时间。\",\n /* zh_hant */ \"您已複製 {size},共享可能需要較長時間。\",\n ],\n // LargeClipboardWarningLine3\n [\n /* en */ \"Do you want to send it anyway?\",\n /* de */ \"Möchten Sie es trotzdem senden?\",\n /* es */ \"¿Desea enviarlo de todas formas?\",\n /* fr */ \"Voulez-vous quand même l’envoyer ?\",\n /* it */ \"Vuoi inviarlo comunque?\",\n /* ja */ \"それでも送信しますか?\",\n /* ko */ \"그래도 전송하시겠습니까?\",\n /* pt_br */ \"Deseja enviar mesmo assim?\",\n /* ru */ \"Отправить в любом случае?\",\n /* zh_hans */ \"仍要发送吗?\",\n /* zh_hant */ \"仍要傳送嗎?\",\n ],\n // SuperLargeClipboardWarning (as an alternative to LargeClipboardWarningLine2 and 3)\n [\n /* en */ \"The text you copied is too large to be shared.\",\n /* de */ \"Der kopierte Text ist zu groß, um geteilt zu werden.\",\n /* es */ \"El texto que copiaste es demasiado grande para compartirse.\",\n /* fr */ \"Le texte que vous avez copié est trop volumineux pour être partagé.\",\n /* it */ \"Il testo copiato è troppo grande per essere condiviso.\",\n /* ja */ \"コピーしたテキストは大きすぎて共有できません。\",\n /* ko */ \"복사한 텍스트가 너무 커서 공유할 수 없습니다.\",\n /* pt_br */ \"O texto copiado é grande demais para ser compartilhado.\",\n /* ru */ \"Скопированный текст слишком велик для передачи.\",\n /* zh_hans */ \"你复制的文本过大,无法共享。\",\n /* zh_hant */ \"您複製的文字過大,無法分享。\",\n ],\n\n // WarningDialogTitle\n [\n /* en */ \"Warning\",\n /* de */ \"Warnung\",\n /* es */ \"Advertencia\",\n /* fr */ \"Avertissement\",\n /* it */ \"Avviso\",\n /* ja */ \"警告\",\n /* ko */ \"경고\",\n /* pt_br */ \"Aviso\",\n /* ru */ \"Предупреждение\",\n /* zh_hans */ \"警告\",\n /* zh_hant */ \"警告\",\n ],\n\n // ErrorDialogTitle\n [\n /* en */ \"Error\",\n /* de */ \"Fehler\",\n /* es */ \"Error\",\n /* fr */ \"Erreur\",\n /* it */ \"Errore\",\n /* ja */ \"エラー\",\n /* ko */ \"오류\",\n /* pt_br */ \"Erro\",\n /* ru */ \"Ошибка\",\n /* zh_hans */ \"错误\",\n /* zh_hant */ \"錯誤\",\n ],\n // ErrorIcuMissing\n [\n /* en */ \"This operation requires the ICU library\",\n /* de */ \"Diese Operation erfordert die ICU-Bibliothek\",\n /* es */ \"Esta operación requiere la biblioteca ICU\",\n /* fr */ \"Cette opération nécessite la bibliothèque ICU\",\n /* it */ \"Questa operazione richiede la libreria ICU\",\n /* ja */ \"この操作にはICUライブラリが必要です\",\n /* ko */ \"이 작업에는 ICU 라이브러리가 필요합니다\",\n /* pt_br */ \"Esta operação requer a biblioteca ICU\",\n /* ru */ \"Эта операция требует наличия библиотеки ICU\",\n /* zh_hans */ \"此操作需要 ICU 库\",\n /* zh_hant */ \"此操作需要 ICU 庫\",\n ],\n\n // SearchNeedleLabel (for input field)\n [\n /* en */ \"Find:\",\n /* de */ \"Suchen:\",\n /* es */ \"Buscar:\",\n /* fr */ \"Rechercher :\",\n /* it */ \"Trova:\",\n /* ja */ \"検索:\",\n /* ko */ \"찾기:\",\n /* pt_br */ \"Encontrar:\",\n /* ru */ \"Найти:\",\n /* zh_hans */ \"查找:\",\n /* zh_hant */ \"尋找:\",\n ],\n // SearchReplacementLabel (for input field)\n [\n /* en */ \"Replace:\",\n /* de */ \"Ersetzen:\",\n /* es */ \"Reemplazar:\",\n /* fr */ \"Remplacer :\",\n /* it */ \"Sostituire:\",\n /* ja */ \"置換:\",\n /* ko */ \"바꾸기:\",\n /* pt_br */ \"Substituir:\",\n /* ru */ \"Замена:\",\n /* zh_hans */ \"替换:\",\n /* zh_hant */ \"替換:\",\n ],\n // SearchMatchCase (toggle)\n [\n /* en */ \"Match Case\",\n /* de */ \"Groß/Klein\",\n /* es */ \"May/Min\",\n /* fr */ \"Resp. la casse\",\n /* it */ \"Maius/minus\",\n /* ja */ \"大/小文字を区別\",\n /* ko */ \"대소문자\",\n /* pt_br */ \"Maius/minus\",\n /* ru */ \"Регистр\",\n /* zh_hans */ \"区分大小写\",\n /* zh_hant */ \"區分大小寫\",\n ],\n // SearchWholeWord (toggle)\n [\n /* en */ \"Whole Word\",\n /* de */ \"Ganzes Wort\",\n /* es */ \"Palabra\",\n /* fr */ \"Mot entier\",\n /* it */ \"Parola\",\n /* ja */ \"単語全体\",\n /* ko */ \"전체 단어\",\n /* pt_br */ \"Palavra\",\n /* ru */ \"Слово\",\n /* zh_hans */ \"全字匹配\",\n /* zh_hant */ \"全字匹配\",\n ],\n // SearchUseRegex (toggle)\n [\n /* en */ \"Use Regex\",\n /* de */ \"RegEx\",\n /* es */ \"RegEx\",\n /* fr */ \"RegEx\",\n /* it */ \"RegEx\",\n /* ja */ \"正規表現\",\n /* ko */ \"정규식\",\n /* pt_br */ \"RegEx\",\n /* ru */ \"RegEx\",\n /* zh_hans */ \"正则\",\n /* zh_hant */ \"正則\",\n ],\n // SearchReplaceAll (button)\n [\n /* en */ \"Replace All\",\n /* de */ \"Alle ersetzen\",\n /* es */ \"Reemplazar todo\",\n /* fr */ \"Remplacer tout\",\n /* it */ \"Sostituisci tutto\",\n /* ja */ \"すべて置換\",\n /* ko */ \"모두 바꾸기\",\n /* pt_br */ \"Substituir tudo\",\n /* ru */ \"Заменить все\",\n /* zh_hans */ \"全部替换\",\n /* zh_hant */ \"全部取代\",\n ],\n // SearchClose (button)\n [\n /* en */ \"Close\",\n /* de */ \"Schließen\",\n /* es */ \"Cerrar\",\n /* fr */ \"Fermer\",\n /* it */ \"Chiudi\",\n /* ja */ \"閉じる\",\n /* ko */ \"닫기\",\n /* pt_br */ \"Fechar\",\n /* ru */ \"Закрыть\",\n /* zh_hans */ \"关闭\",\n /* zh_hant */ \"關閉\",\n ],\n\n // EncodingReopen\n [\n /* en */ \"Reopen with encoding…\",\n /* de */ \"Mit Kodierung erneut öffnen…\",\n /* es */ \"Reabrir con codificación…\",\n /* fr */ \"Rouvrir avec un encodage différent…\",\n /* it */ \"Riapri con codifica…\",\n /* ja */ \"指定エンコーディングで再度開く…\",\n /* ko */ \"인코딩으로 다시 열기…\",\n /* pt_br */ \"Reabrir com codificação…\",\n /* ru */ \"Открыть снова с кодировкой…\",\n /* zh_hans */ \"使用编码重新打开…\",\n /* zh_hant */ \"使用編碼重新打開…\",\n ],\n // EncodingConvert\n [\n /* en */ \"Convert to encoding…\",\n /* de */ \"In Kodierung konvertieren…\",\n /* es */ \"Convertir a otra codificación…\",\n /* fr */ \"Convertir vers l’encodage…\",\n /* it */ \"Converti in codifica…\",\n /* ja */ \"エンコーディングを変換…\",\n /* ko */ \"인코딩으로 변환…\",\n /* pt_br */ \"Converter para codificação…\",\n /* ru */ \"Преобразовать в кодировку…\",\n /* zh_hans */ \"转换为编码…\",\n /* zh_hant */ \"轉換為編碼…\",\n ],\n\n // IndentationTabs\n [\n /* en */ \"Tabs\",\n /* de */ \"Tabs\",\n /* es */ \"Tabulaciones\",\n /* fr */ \"Tabulations\",\n /* it */ \"Tabulazioni\",\n /* ja */ \"タブ\",\n /* ko */ \"탭\",\n /* pt_br */ \"Tabulações\",\n /* ru */ \"Табы\",\n /* zh_hans */ \"制表符\",\n /* zh_hant */ \"製表符\",\n ],\n // IndentationSpaces\n [\n /* en */ \"Spaces\",\n /* de */ \"Leerzeichen\",\n /* es */ \"Espacios\",\n /* fr */ \"Espaces\",\n /* it */ \"Spazi\",\n /* ja */ \"スペース\",\n /* ko */ \"공백\",\n /* pt_br */ \"Espaços\",\n /* ru */ \"Пробелы\",\n /* zh_hans */ \"空格\",\n /* zh_hant */ \"空格\",\n ],\n\n // SaveAsDialogPathLabel\n [\n /* en */ \"Folder:\",\n /* de */ \"Ordner:\",\n /* es */ \"Carpeta:\",\n /* fr */ \"Dossier :\",\n /* it */ \"Cartella:\",\n /* ja */ \"フォルダ:\",\n /* ko */ \"폴더:\",\n /* pt_br */ \"Pasta:\",\n /* ru */ \"Папка:\",\n /* zh_hans */ \"文件夹:\",\n /* zh_hant */ \"資料夾:\",\n ],\n // SaveAsDialogNameLabel\n [\n /* en */ \"File name:\",\n /* de */ \"Dateiname:\",\n /* es */ \"Nombre de archivo:\",\n /* fr */ \"Nom du fichier :\",\n /* it */ \"Nome del file:\",\n /* ja */ \"ファイル名:\",\n /* ko */ \"파일 이름:\",\n /* pt_br */ \"Nome do arquivo:\",\n /* ru */ \"Имя файла:\",\n /* zh_hans */ \"文件名:\",\n /* zh_hant */ \"檔案名稱:\",\n ],\n\n // FileOverwriteWarning\n [\n /* en */ \"Confirm Save As\",\n /* de */ \"Speichern unter bestätigen\",\n /* es */ \"Confirmar Guardar como\",\n /* fr */ \"Confirmer Enregistrer sous\",\n /* it */ \"Conferma Salva con nome\",\n /* ja */ \"名前を付けて保存の確認\",\n /* ko */ \"다른 이름으로 저장 확인\",\n /* pt_br */ \"Confirmar Salvar como\",\n /* ru */ \"Подтвердите «Сохранить как…»\",\n /* zh_hans */ \"确认另存为\",\n /* zh_hant */ \"確認另存新檔\",\n ],\n // FileOverwriteWarningDescription\n [\n /* en */ \"File already exists. Do you want to overwrite it?\",\n /* de */ \"Datei existiert bereits. Möchten Sie sie überschreiben?\",\n /* es */ \"El archivo ya existe. ¿Desea sobrescribirlo?\",\n /* fr */ \"Le fichier existe déjà. Voulez-vous l’écraser ?\",\n /* it */ \"Il file esiste già. Vuoi sovrascriverlo?\",\n /* ja */ \"ファイルは既に存在します。上書きしますか?\",\n /* ko */ \"파일이 이미 존재합니다. 덮어쓰시겠습니까?\",\n /* pt_br */ \"O arquivo já existe. Deseja sobrescrevê-lo?\",\n /* ru */ \"Файл уже существует. Перезаписать?\",\n /* zh_hans */ \"文件已存在。要覆盖它吗?\",\n /* zh_hant */ \"檔案已存在。要覆蓋它嗎?\",\n ],\n];\n\nstatic mut S_LANG: LangId = LangId::en;\n\npub fn init() {\n // WARNING:\n // Generic language tags such as \"zh\" MUST be sorted after more specific tags such\n // as \"zh-hant\" to ensure that the prefix match finds the most specific one first.\n const LANG_MAP: &[(&str, LangId)] = &[\n (\"en\", LangId::en),\n // ----------------\n (\"de\", LangId::de),\n (\"es\", LangId::es),\n (\"fr\", LangId::fr),\n (\"it\", LangId::it),\n (\"ja\", LangId::ja),\n (\"ko\", LangId::ko),\n (\"pt-br\", LangId::pt_br),\n (\"ru\", LangId::ru),\n (\"zh-hant\", LangId::zh_hant),\n (\"zh-tw\", LangId::zh_hant),\n (\"zh\", LangId::zh_hans),\n ];\n\n let scratch = scratch_arena(None);\n let langs = sys::preferred_languages(&scratch);\n let mut lang = LangId::en;\n\n 'outer: for l in langs {\n for (prefix, id) in LANG_MAP {\n if l.starts_with_ignore_ascii_case(prefix) {\n lang = *id;\n break 'outer;\n }\n }\n }\n\n unsafe {\n S_LANG = lang;\n }\n}\n\npub fn loc(id: LocId) -> &'static str {\n S_LANG_LUT[id as usize][unsafe { S_LANG as usize }]\n}\n"], ["/edit/src/bin/edit/draw_menubar.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena_format;\nuse edit::helpers::*;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_menubar(ctx: &mut Context, state: &mut State) {\n ctx.menubar_begin();\n ctx.attr_background_rgba(state.menubar_color_bg);\n ctx.attr_foreground_rgba(state.menubar_color_fg);\n {\n let contains_focus = ctx.contains_focus();\n\n if ctx.menubar_menu_begin(loc(LocId::File), 'F') {\n draw_menu_file(ctx, state);\n }\n if !contains_focus && ctx.consume_shortcut(vk::F10) {\n ctx.steal_focus();\n }\n if state.documents.active().is_some() {\n if ctx.menubar_menu_begin(loc(LocId::Edit), 'E') {\n draw_menu_edit(ctx, state);\n }\n if ctx.menubar_menu_begin(loc(LocId::View), 'V') {\n draw_menu_view(ctx, state);\n }\n }\n if ctx.menubar_menu_begin(loc(LocId::Help), 'H') {\n draw_menu_help(ctx, state);\n }\n }\n ctx.menubar_end();\n}\n\nfn draw_menu_file(ctx: &mut Context, state: &mut State) {\n if ctx.menubar_menu_button(loc(LocId::FileNew), 'N', kbmod::CTRL | vk::N) {\n draw_add_untitled_document(ctx, state);\n }\n if ctx.menubar_menu_button(loc(LocId::FileOpen), 'O', kbmod::CTRL | vk::O) {\n state.wants_file_picker = StateFilePicker::Open;\n }\n if state.documents.active().is_some() {\n if ctx.menubar_menu_button(loc(LocId::FileSave), 'S', kbmod::CTRL | vk::S) {\n state.wants_save = true;\n }\n if ctx.menubar_menu_button(loc(LocId::FileSaveAs), 'A', vk::NULL) {\n state.wants_file_picker = StateFilePicker::SaveAs;\n }\n if ctx.menubar_menu_button(loc(LocId::FileClose), 'C', kbmod::CTRL | vk::W) {\n state.wants_close = true;\n }\n }\n if ctx.menubar_menu_button(loc(LocId::FileExit), 'X', kbmod::CTRL | vk::Q) {\n state.wants_exit = true;\n }\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_edit(ctx: &mut Context, state: &mut State) {\n let doc = state.documents.active().unwrap();\n let mut tb = doc.buffer.borrow_mut();\n\n if ctx.menubar_menu_button(loc(LocId::EditUndo), 'U', kbmod::CTRL | vk::Z) {\n tb.undo();\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditRedo), 'R', kbmod::CTRL | vk::Y) {\n tb.redo();\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditCut), 'T', kbmod::CTRL | vk::X) {\n tb.cut(ctx.clipboard_mut());\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditCopy), 'C', kbmod::CTRL | vk::C) {\n tb.copy(ctx.clipboard_mut());\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditPaste), 'P', kbmod::CTRL | vk::V) {\n tb.paste(ctx.clipboard_ref());\n ctx.needs_rerender();\n }\n if state.wants_search.kind != StateSearchKind::Disabled {\n if ctx.menubar_menu_button(loc(LocId::EditFind), 'F', kbmod::CTRL | vk::F) {\n state.wants_search.kind = StateSearchKind::Search;\n state.wants_search.focus = true;\n }\n if ctx.menubar_menu_button(loc(LocId::EditReplace), 'L', kbmod::CTRL | vk::R) {\n state.wants_search.kind = StateSearchKind::Replace;\n state.wants_search.focus = true;\n }\n }\n if ctx.menubar_menu_button(loc(LocId::EditSelectAll), 'A', kbmod::CTRL | vk::A) {\n tb.select_all();\n ctx.needs_rerender();\n }\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_view(ctx: &mut Context, state: &mut State) {\n if let Some(doc) = state.documents.active() {\n let mut tb = doc.buffer.borrow_mut();\n let word_wrap = tb.is_word_wrap_enabled();\n\n // All values on the statusbar are currently document specific.\n if ctx.menubar_menu_button(loc(LocId::ViewFocusStatusbar), 'S', vk::NULL) {\n state.wants_statusbar_focus = true;\n }\n if ctx.menubar_menu_button(loc(LocId::ViewGoToFile), 'F', kbmod::CTRL | vk::P) {\n state.wants_go_to_file = true;\n }\n if ctx.menubar_menu_button(loc(LocId::FileGoto), 'G', kbmod::CTRL | vk::G) {\n state.wants_goto = true;\n }\n if ctx.menubar_menu_checkbox(loc(LocId::ViewWordWrap), 'W', kbmod::ALT | vk::Z, word_wrap) {\n tb.set_word_wrap(!word_wrap);\n ctx.needs_rerender();\n }\n }\n\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_help(ctx: &mut Context, state: &mut State) {\n if ctx.menubar_menu_button(loc(LocId::HelpAbout), 'A', vk::NULL) {\n state.wants_about = true;\n }\n ctx.menubar_menu_end();\n}\n\npub fn draw_dialog_about(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"about\", loc(LocId::AboutDialogTitle));\n {\n ctx.block_begin(\"content\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(1, 2, 1));\n {\n ctx.label(\"description\", \"Microsoft Edit\");\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_position(Position::Center);\n\n ctx.label(\n \"version\",\n &arena_format!(\n ctx.arena(),\n \"{}{}\",\n loc(LocId::AboutDialogVersion),\n env!(\"CARGO_PKG_VERSION\")\n ),\n );\n ctx.attr_overflow(Overflow::TruncateHead);\n ctx.attr_position(Position::Center);\n\n ctx.label(\"copyright\", \"Copyright (c) Microsoft Corp 2025\");\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_position(Position::Center);\n\n ctx.block_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(1, 2, 0));\n ctx.attr_position(Position::Center);\n {\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n state.wants_about = false;\n }\n ctx.inherit_focus();\n }\n ctx.block_end();\n }\n ctx.block_end();\n }\n if ctx.modal_end() {\n state.wants_about = false;\n }\n}\n"], ["/edit/src/clipboard.rs", "//! Clipboard facilities for the editor.\n\n/// The builtin, internal clipboard of the editor.\n///\n/// This is useful particularly when the terminal doesn't support\n/// OSC 52 or when the clipboard contents are huge (e.g. 1GiB).\n#[derive(Default)]\npub struct Clipboard {\n data: Vec,\n line_copy: bool,\n wants_host_sync: bool,\n}\n\nimpl Clipboard {\n /// If true, we should emit a OSC 52 sequence to sync the clipboard\n /// with the hosting terminal.\n pub fn wants_host_sync(&self) -> bool {\n self.wants_host_sync\n }\n\n /// Call this once the clipboard has been synchronized with the host.\n pub fn mark_as_synchronized(&mut self) {\n self.wants_host_sync = false;\n }\n\n /// The editor has a special behavior when you have no selection and press\n /// Ctrl+C: It copies the current line to the clipboard. Then, when you\n /// paste it, it inserts the line at *the start* of the current line.\n /// This effectively prepends the current line with the copied line.\n /// `clipboard_line_start` is true in that case.\n pub fn is_line_copy(&self) -> bool {\n self.line_copy\n }\n\n /// Returns the current contents of the clipboard.\n pub fn read(&self) -> &[u8] {\n &self.data\n }\n\n /// Fill the clipboard with the given data.\n pub fn write(&mut self, data: Vec) {\n if !data.is_empty() {\n self.data = data;\n self.line_copy = false;\n self.wants_host_sync = true;\n }\n }\n\n /// See [`Clipboard::is_line_copy`].\n pub fn write_was_line_copy(&mut self, line_copy: bool) {\n self.line_copy = line_copy;\n }\n}\n"], ["/edit/src/simd/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides various high-throughput utilities.\n\npub mod lines_bwd;\npub mod lines_fwd;\nmod memchr2;\nmod memset;\n\npub use lines_bwd::*;\npub use lines_fwd::*;\npub use memchr2::*;\npub use memset::*;\n\n#[cfg(test)]\nmod test {\n // Knuth's MMIX LCG\n pub fn make_rng() -> impl FnMut() -> usize {\n let mut state = 1442695040888963407u64;\n move || {\n state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);\n state as usize\n }\n }\n\n pub fn generate_random_text(len: usize) -> String {\n const ALPHABET: &[u8; 20] = b\"0123456789abcdef\\n\\n\\n\\n\";\n\n let mut rng = make_rng();\n let mut res = String::new();\n\n for _ in 0..len {\n res.push(ALPHABET[rng() % ALPHABET.len()] as char);\n }\n\n res\n }\n\n pub fn count_lines(text: &str) -> usize {\n text.lines().count()\n }\n}\n"], ["/edit/src/lib.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![feature(\n allocator_api,\n breakpoint,\n cold_path,\n linked_list_cursors,\n maybe_uninit_fill,\n maybe_uninit_slice,\n maybe_uninit_uninit_array_transpose\n)]\n#![cfg_attr(\n target_arch = \"loongarch64\",\n feature(stdarch_loongarch, stdarch_loongarch_feature_detection, loongarch_target_feature),\n allow(clippy::incompatible_msrv)\n)]\n#![allow(clippy::missing_transmute_annotations, clippy::new_without_default, stable_features)]\n\n#[macro_use]\npub mod arena;\n\npub mod apperr;\npub mod base64;\npub mod buffer;\npub mod cell;\npub mod clipboard;\npub mod document;\npub mod framebuffer;\npub mod fuzzy;\npub mod hash;\npub mod helpers;\npub mod icu;\npub mod input;\npub mod oklab;\npub mod path;\npub mod simd;\npub mod sys;\npub mod tui;\npub mod unicode;\npub mod vt;\n"], ["/edit/src/unicode/tables.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n// BEGIN: Generated by grapheme-table-gen on 2025-06-03T13:50:48Z, from Unicode 16.0.0, with --lang=rust --extended --line-breaks, 17688 bytes\n#[rustfmt::skip]\nconst STAGE0: [u16; 544] = [\n 0x0000, 0x0040, 0x007f, 0x00bf, 0x00ff, 0x013f, 0x017f, 0x0194, 0x0194, 0x01a6, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x01e6, 0x0226, 0x024a, 0x024b, 0x024c, 0x0246, 0x0255, 0x0295, 0x02d5, 0x02d5, 0x02d5, 0x030d,\n 0x034d, 0x038d, 0x03cd, 0x040d, 0x044d, 0x0478, 0x04b8, 0x04db, 0x04fc, 0x0295, 0x0295, 0x0295, 0x0534, 0x0574, 0x0194, 0x0194,\n 0x05b4, 0x05f4, 0x0295, 0x0295, 0x0295, 0x061d, 0x065d, 0x067d, 0x0295, 0x06a3, 0x06e3, 0x0723, 0x0763, 0x07a3, 0x07e3, 0x0823,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0863,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0863,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x08a3, 0x08b3, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x08f3,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x08f3,\n];\n#[rustfmt::skip]\nconst STAGE1: [u16; 2355] = [\n 0x0000, 0x0008, 0x0010, 0x0018, 0x0020, 0x0028, 0x0030, 0x0038, 0x0040, 0x0047, 0x004f, 0x0056, 0x0059, 0x0059, 0x005e, 0x0059, 0x0059, 0x0059, 0x0066, 0x006a, 0x0059, 0x0059, 0x0071, 0x0059, 0x0079, 0x0079, 0x007e, 0x0086, 0x008e, 0x0096, 0x009e, 0x0059, 0x00a6, 0x00aa, 0x00ae, 0x0059, 0x00b6, 0x0059, 0x0059, 0x0059, 0x0059, 0x00ba, 0x00bf, 0x0059, 0x00c6, 0x00cb, 0x00d3, 0x00d9, 0x00e1, 0x0059, 0x00e9, 0x00f1, 0x0059, 0x0059, 0x00f6, 0x00fe, 0x0105, 0x010a, 0x0110, 0x0059, 0x0059, 0x0117, 0x011f, 0x0125,\n 0x012d, 0x0134, 0x013c, 0x0144, 0x0149, 0x0059, 0x0151, 0x0159, 0x0161, 0x0167, 0x016f, 0x0177, 0x017f, 0x0185, 0x018d, 0x0195, 0x019d, 0x01a3, 0x01ab, 0x01b3, 0x01bb, 0x01c1, 0x01c9, 0x01d1, 0x01d9, 0x01df, 0x01e7, 0x01ef, 0x01f7, 0x01ff, 0x0207, 0x020e, 0x0216, 0x021c, 0x0224, 0x022c, 0x0234, 0x023a, 0x0242, 0x024a, 0x0252, 0x0258, 0x0260, 0x0268, 0x0270, 0x0277, 0x027f, 0x0287, 0x028d, 0x0291, 0x0299, 0x028d, 0x028d, 0x02a0, 0x02a8, 0x028d, 0x02b0, 0x02b8, 0x00bc, 0x02c0, 0x02c8, 0x02cf, 0x02d7, 0x028d,\n 0x02de, 0x02e6, 0x02ee, 0x02f6, 0x0059, 0x02fe, 0x0059, 0x0306, 0x0306, 0x0306, 0x030e, 0x030e, 0x0314, 0x0316, 0x0316, 0x0059, 0x0059, 0x031e, 0x0059, 0x0326, 0x032a, 0x0332, 0x0059, 0x0338, 0x0059, 0x033e, 0x0346, 0x034e, 0x0059, 0x0059, 0x0356, 0x035e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0366, 0x0059, 0x0059, 0x036e, 0x0376, 0x037e, 0x0386, 0x038e, 0x028d, 0x0393, 0x039b, 0x03a3, 0x03ab,\n 0x0059, 0x0059, 0x03b3, 0x03bb, 0x03c1, 0x0059, 0x03c5, 0x03cd, 0x03d5, 0x03dd, 0x028d, 0x028d, 0x028d, 0x03e1, 0x0059, 0x03e9, 0x028d, 0x03f1, 0x03f9, 0x0401, 0x0408, 0x040d, 0x028d, 0x0415, 0x0418, 0x0420, 0x0428, 0x0430, 0x0438, 0x028d, 0x0440, 0x0059, 0x0447, 0x044f, 0x0456, 0x0144, 0x045e, 0x0466, 0x046e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0476, 0x047a, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0356, 0x0059, 0x0482, 0x048a, 0x0059, 0x0492, 0x0496, 0x049e, 0x04a6,\n 0x04ae, 0x04b6, 0x04be, 0x04c6, 0x04ce, 0x04d6, 0x04da, 0x04e2, 0x04ea, 0x04f1, 0x04f9, 0x0500, 0x0507, 0x050e, 0x0515, 0x051d, 0x0525, 0x052d, 0x0535, 0x053d, 0x0544, 0x0059, 0x054c, 0x0552, 0x0559, 0x0059, 0x0059, 0x055f, 0x0059, 0x0564, 0x056a, 0x0059, 0x0571, 0x0579, 0x0581, 0x0581, 0x0581, 0x0589, 0x058f, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0597, 0x059f, 0x05a7, 0x05af, 0x05b7, 0x05bf, 0x05c7, 0x05cf, 0x05d7, 0x05df, 0x05e7, 0x05ef, 0x05f6, 0x05fe, 0x0606, 0x060e, 0x0616, 0x061e, 0x0625, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0629, 0x0059, 0x0059, 0x0631, 0x0059, 0x0638, 0x063f, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0647, 0x0059, 0x064f, 0x0656, 0x065c, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0662, 0x0059, 0x02fe, 0x0059, 0x066a, 0x0672, 0x067a, 0x067a, 0x0079, 0x0682, 0x068a, 0x0692, 0x028d, 0x069a, 0x06a1, 0x06a1, 0x06a4, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06ac, 0x06b2, 0x06ba,\n 0x06c2, 0x06ca, 0x06d2, 0x06da, 0x06e2, 0x06d2, 0x06ea, 0x06f2, 0x06f6, 0x06a1, 0x06a1, 0x06fb, 0x06a1, 0x06a1, 0x0702, 0x070a, 0x06a1, 0x0712, 0x06a1, 0x0716, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x071e, 0x071e, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0726, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x072c, 0x06a1, 0x0733, 0x0456, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0738, 0x0740, 0x0059, 0x0748, 0x0750, 0x0059, 0x0059, 0x0758, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0760, 0x0768, 0x0770, 0x0778, 0x0059, 0x0780, 0x0788, 0x078b, 0x0792, 0x079a, 0x011f, 0x07a2, 0x07a9, 0x07b1, 0x07b9, 0x07bd, 0x07c5, 0x07cd, 0x028d, 0x07d4, 0x07dc, 0x07e4, 0x028d, 0x07ec, 0x07f4, 0x07fc, 0x0804, 0x080c,\n 0x0059, 0x0811, 0x0059, 0x0059, 0x0059, 0x0819, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822,\n 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x082e, 0x0835, 0x0838, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581,\n 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0840, 0x0848, 0x0850, 0x0059, 0x0059, 0x0059, 0x0858, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x085d, 0x0059, 0x0059, 0x0657, 0x0059, 0x0865, 0x0869, 0x0871, 0x0879, 0x0880,\n 0x0888, 0x0059, 0x0059, 0x0059, 0x088e, 0x0896, 0x089e, 0x08a6, 0x08ae, 0x08b3, 0x08bb, 0x08c3, 0x08cb, 0x00bb, 0x08d3, 0x08db, 0x028d, 0x0059, 0x0059, 0x0059, 0x0852, 0x08e3, 0x08e6, 0x0059, 0x0059, 0x08ec, 0x028c, 0x08f4, 0x08f8, 0x028d, 0x028d, 0x028d, 0x028d, 0x0900, 0x0059, 0x0903, 0x090b, 0x0059, 0x0911, 0x0144, 0x0915, 0x091d, 0x0059, 0x0925, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x048a, 0x03af, 0x092d, 0x0933, 0x0059, 0x0938, 0x0059, 0x093f, 0x0943, 0x0948, 0x0059, 0x0950, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0672, 0x03c5, 0x0953, 0x095b, 0x095f, 0x028d, 0x028d, 0x0967, 0x096a, 0x0972, 0x0059, 0x03cd, 0x097a, 0x028d, 0x0982, 0x0989, 0x0991, 0x028d, 0x028d, 0x0059, 0x0999, 0x0657, 0x0059, 0x09a1, 0x09a8, 0x09b0, 0x0059, 0x0059, 0x028d, 0x0059, 0x09b8, 0x0059, 0x09c0, 0x048c, 0x09c8, 0x09ce, 0x09d6, 0x028d, 0x028d, 0x0059, 0x0059, 0x09de, 0x028d, 0x0059, 0x0854, 0x0059, 0x09e6, 0x0059, 0x09ed, 0x011f, 0x09f5, 0x09fc, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x03cd, 0x0059, 0x0a04, 0x0a0c, 0x0a0e, 0x0059, 0x0938, 0x0a16, 0x08f4, 0x0a1e, 0x08f4, 0x0952, 0x0672, 0x0a26, 0x0a28, 0x0a2f, 0x0a36, 0x0430, 0x0a3e, 0x0a46, 0x0a4c, 0x0a54, 0x0a5b, 0x0a63, 0x0a67, 0x0430, 0x0a6f, 0x0a77, 0x0a7f, 0x065d, 0x0a87, 0x0a8f, 0x028d, 0x0a97, 0x0a9f, 0x0a55, 0x0aa7, 0x0aaf, 0x0ab1, 0x0ab9, 0x0ac1, 0x028d, 0x0ac7, 0x0acf, 0x0ad7, 0x0059, 0x0adf, 0x0ae7, 0x0aef, 0x0059, 0x0af7, 0x0aff, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0b07, 0x0b0f, 0x028d, 0x0059, 0x0b17, 0x0b1f,\n 0x0b27, 0x0059, 0x0b2f, 0x0b37, 0x0b3e, 0x0b3f, 0x0b47, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0b4f, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0b57, 0x028d, 0x0b5f, 0x0b67, 0x028d, 0x028d, 0x0659, 0x0b6f, 0x0b77, 0x0b7f, 0x0b83, 0x0b8b, 0x0059, 0x0b92, 0x0b9a, 0x0059, 0x03b3, 0x0ba2, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0baa, 0x0bb2, 0x0bb7, 0x0bbf, 0x0bc6, 0x0bcb, 0x0bd1, 0x028d, 0x028d, 0x0bd9, 0x0bdd, 0x0be5, 0x0bed, 0x0bf3, 0x0bfb, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x0bff, 0x0c07, 0x0c0a, 0x0c12, 0x028d, 0x028d, 0x0c19, 0x0c21, 0x0c29, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x034e, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0c31, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c39, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0059, 0x0059, 0x0854, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c41, 0x0059, 0x0c49, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c4c, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c53, 0x0c5b, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0852, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c63, 0x0059, 0x0059, 0x0059, 0x0c6a, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0c6c, 0x0c74, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x03b3, 0x03cd, 0x0c7c, 0x0059, 0x03cd, 0x03af, 0x0c81, 0x0059, 0x0c89, 0x0c90, 0x0c98, 0x0951, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0ca0, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0ca8, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0cb0, 0x0cb5, 0x0cbb, 0x028d, 0x028d, 0x0cc3, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a3, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x0ccb, 0x0cd1, 0x0cd9, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0cdd, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0ce5, 0x0cea, 0x0cf1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a2, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0cf9, 0x0cfe, 0x0d06, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d0e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0950, 0x028d, 0x028d, 0x0079, 0x0d16, 0x0d1d, 0x0059, 0x0059, 0x0059, 0x0c39, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x03c5, 0x0059, 0x0d24, 0x0059, 0x0d2b, 0x0d33, 0x0d39, 0x0059, 0x0579, 0x0059, 0x0059, 0x0d41, 0x028d, 0x028d, 0x028d, 0x0950, 0x0950, 0x071e, 0x071e, 0x0d49, 0x0d51, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0492, 0x0059, 0x0d59, 0x0d61, 0x0d69, 0x0059, 0x0d70, 0x0d6b, 0x0d78, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d7f, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d84, 0x0d88, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0079, 0x0d90, 0x0079, 0x0d97, 0x0d9e, 0x0da6, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x03cd, 0x0dad, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0db5, 0x0dbd, 0x0059, 0x0dc2, 0x0dc7, 0x028d, 0x028d, 0x028d, 0x0059, 0x0dcf, 0x0dd7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0ddf, 0x0059, 0x0de7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0def, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0df7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0dff, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0e07, 0x028d, 0x0059, 0x0059, 0x0e0f, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0e17, 0x0059, 0x0e1c, 0x028d, 0x028d, 0x0e24, 0x048a, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0d69, 0x0e2c, 0x0e34, 0x0e3c, 0x0e44, 0x0e4c, 0x028d, 0x0ba6, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0e54, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e5b, 0x0e56, 0x0e63, 0x0e68, 0x0581, 0x0e6e, 0x0e76, 0x0e7d, 0x0e56, 0x0e84, 0x0e8c, 0x0e93, 0x0e9b, 0x0ea3, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0eab, 0x0eb3, 0x0eab, 0x0eb9, 0x0ec1,\n 0x0ec9, 0x0ed1, 0x0ed9, 0x0eab, 0x0ee1, 0x0ee9, 0x0eab, 0x0eab, 0x0ef1, 0x0eab, 0x0ef6, 0x0efe, 0x0f05, 0x0f0d, 0x0f13, 0x0f1a, 0x0e54, 0x0f20, 0x0f27, 0x0eab, 0x0eab, 0x0f2e, 0x0f32, 0x0eab, 0x0eab, 0x0f3a, 0x0f42, 0x0059, 0x0059, 0x0059, 0x0f4a, 0x0059, 0x0059, 0x0f52, 0x0f5a, 0x0f62, 0x0059, 0x0f68, 0x0059, 0x0f70, 0x0f75, 0x0f7d, 0x0f7e, 0x0f86, 0x0f89, 0x0f90, 0x0eab, 0x0eab, 0x0eab, 0x0eab, 0x0eab, 0x0f98, 0x0f98, 0x0f9b, 0x0fa0, 0x0fa8, 0x0eab, 0x0faf, 0x0fb7, 0x0059, 0x0059, 0x0059, 0x0059, 0x0fbf,\n 0x0059, 0x0059, 0x0d0e, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0fc7, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0fcf, 0x0fd7, 0x0079, 0x0079, 0x0079, 0x0020, 0x0020, 0x0020, 0x0020, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0fdf, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,\n 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581,\n 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0fe7,\n];\n#[rustfmt::skip]\nconst STAGE2: [u16; 4079] = [\n 0x0000, 0x0004, 0x0008, 0x000c, 0x0010, 0x0014, 0x0018, 0x001c,\n 0x0020, 0x0024, 0x0028, 0x002c, 0x0030, 0x0034, 0x0038, 0x003c,\n 0x0040, 0x0044, 0x0048, 0x004c, 0x0050, 0x0054, 0x0058, 0x005c,\n 0x0060, 0x0064, 0x0068, 0x006c, 0x0070, 0x0074, 0x0078, 0x007c,\n 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,\n 0x0080, 0x0084, 0x0087, 0x008b, 0x008f, 0x0093, 0x0095, 0x0099,\n 0x0040, 0x009d, 0x0040, 0x0040, 0x009f, 0x00a0, 0x009f, 0x00a4,\n 0x00a6, 0x009d, 0x00aa, 0x00a6, 0x00ac, 0x00a0, 0x00aa, 0x00af,\n 0x009e, 0x0040, 0x0040, 0x0040, 0x00b0, 0x0040, 0x00b4, 0x0040,\n 0x00a4, 0x00b4, 0x0040, 0x00a9, 0x0040, 0x009f, 0x00b4, 0x00aa,\n 0x009f, 0x00b7, 0x009e, 0x00a4, 0x0040, 0x0040, 0x0040, 0x00a4,\n 0x00b4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x009d, 0x00af, 0x00af, 0x00af, 0x009f, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x009e, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ba, 0x00be, 0x00c2, 0x00c3, 0x0040, 0x00c7,\n 0x00cb, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x00d0, 0x00cf, 0x00cf, 0x00cf, 0x00d3, 0x00d4, 0x00cf,\n 0x00cf, 0x00cf, 0x0040, 0x0040, 0x00d8, 0x00da, 0x00de, 0x0040,\n 0x00e2, 0x00e4, 0x00a9, 0x00b7, 0x00b7, 0x00b7, 0x00e8, 0x00b7,\n 0x00a6, 0x0040, 0x00a9, 0x00b7, 0x00b7, 0x00b7, 0x00ab, 0x00b7,\n 0x00a6, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x009e, 0x0040,\n 0x0040, 0x0040, 0x00b7, 0x00b7, 0x00b7, 0x00b7, 0x00b7, 0x00b7,\n 0x00b7, 0x00b7, 0x009e, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00cf,\n 0x00ef, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e1, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040, 0x0040,\n 0x00f2, 0x00f5, 0x00f9, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x00cf, 0x00fb, 0x00ee, 0x00fe, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x00df, 0x0040, 0x00dd, 0x00de,\n 0x00de, 0x0102, 0x0104, 0x0107, 0x003a, 0x00cf, 0x00cf, 0x010b,\n 0x010d, 0x0040, 0x0040, 0x00ec, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x0030, 0x0030, 0x0111, 0x0114, 0x0118, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x011c, 0x00cf, 0x011f, 0x00cf, 0x0122,\n 0x0125, 0x00ef, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040, 0x0040,\n 0x012b, 0x0117, 0x0040, 0x0040, 0x0040, 0x0040, 0x00cf, 0x00cf,\n 0x00cf, 0x00cf, 0x012f, 0x00e1, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00ed, 0x00cf, 0x00cf, 0x0133, 0x00de, 0x00de, 0x00de, 0x0030,\n 0x0030, 0x0129, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec,\n 0x00cf, 0x00cf, 0x0040, 0x0137, 0x013a, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x013e, 0x00cf, 0x0140, 0x0140, 0x0142,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0140, 0x0144, 0x0040, 0x0040, 0x00e2, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0148, 0x014a, 0x00cf,\n 0x00cf, 0x0040, 0x0040, 0x00ed, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x014d, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x0150, 0x0040, 0x0040, 0x0040, 0x0040, 0x0154, 0x0155,\n 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0157, 0x015b, 0x015e,\n 0x00cf, 0x0161, 0x0164, 0x0140, 0x00cf, 0x0155, 0x0155, 0x00ed,\n 0x0168, 0x0030, 0x0030, 0x0040, 0x0040, 0x0155, 0x0155, 0x016c,\n 0x00e1, 0x0040, 0x0170, 0x0170, 0x0154, 0x0155, 0x0155, 0x0174,\n 0x0155, 0x0177, 0x017a, 0x017c, 0x015b, 0x015e, 0x0180, 0x0183,\n 0x0186, 0x00de, 0x0189, 0x00de, 0x0176, 0x00ed, 0x018d, 0x0030,\n 0x0030, 0x0191, 0x0040, 0x0195, 0x0199, 0x019c, 0x00e1, 0x00e2,\n 0x00df, 0x0170, 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x00e4,\n 0x01a0, 0x01a1, 0x01a5, 0x01a8, 0x014a, 0x01aa, 0x0142, 0x017f,\n 0x00de, 0x00e1, 0x01ae, 0x00de, 0x018d, 0x0030, 0x0030, 0x00ef,\n 0x01b2, 0x00de, 0x00de, 0x019c, 0x00e1, 0x0040, 0x00e3, 0x00e3,\n 0x0154, 0x0155, 0x0155, 0x0174, 0x0155, 0x0174, 0x01b5, 0x017c,\n 0x015b, 0x015e, 0x0130, 0x01b9, 0x01bc, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x00ed, 0x018d, 0x0030, 0x0030, 0x01c0, 0x00de, 0x01c3,\n 0x00cf, 0x01c7, 0x00e1, 0x0040, 0x0170, 0x0170, 0x0154, 0x0155,\n 0x0155, 0x0174, 0x0155, 0x0174, 0x01b5, 0x017c, 0x01cb, 0x015e,\n 0x0180, 0x0183, 0x01bc, 0x00de, 0x019c, 0x00de, 0x0176, 0x00ed,\n 0x018d, 0x0030, 0x0030, 0x01cf, 0x0040, 0x00de, 0x00de, 0x01ab,\n 0x00e1, 0x00e2, 0x00d8, 0x00e4, 0x01a1, 0x01a0, 0x00e4, 0x00df,\n 0x00dd, 0x00e2, 0x00d8, 0x0040, 0x0040, 0x01a1, 0x01d3, 0x01d7,\n 0x01d3, 0x01d9, 0x01dc, 0x00dd, 0x0189, 0x00de, 0x00de, 0x018d,\n 0x0030, 0x0030, 0x0040, 0x0040, 0x01e0, 0x00de, 0x0161, 0x0118,\n 0x0040, 0x00e4, 0x00e4, 0x0154, 0x0155, 0x0155, 0x0174, 0x0155,\n 0x0155, 0x0155, 0x017c, 0x0125, 0x0161, 0x01e4, 0x019b, 0x01e7,\n 0x00de, 0x01ea, 0x01ee, 0x01f1, 0x00ed, 0x018d, 0x0030, 0x0030,\n 0x00de, 0x01f3, 0x0040, 0x0040, 0x016c, 0x01f6, 0x0040, 0x00e4,\n 0x00e4, 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x0040, 0x00e1,\n 0x01a1, 0x01cb, 0x01fa, 0x01fd, 0x01d9, 0x0142, 0x00de, 0x0201,\n 0x00de, 0x01a0, 0x00ed, 0x018d, 0x0030, 0x0030, 0x0204, 0x00de,\n 0x00de, 0x00de, 0x0160, 0x0040, 0x0040, 0x00e4, 0x00e4, 0x0154,\n 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0156, 0x015b,\n 0x015e, 0x01a5, 0x01d9, 0x0207, 0x00de, 0x01f7, 0x0040, 0x0040,\n 0x00ed, 0x018d, 0x0030, 0x0030, 0x0040, 0x0040, 0x020a, 0x0040,\n 0x01c7, 0x00e1, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00d8, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040, 0x0040, 0x01f1, 0x0040,\n 0x00e2, 0x017e, 0x0189, 0x015d, 0x020e, 0x01fa, 0x01fa, 0x00de,\n 0x018d, 0x0030, 0x0030, 0x01d3, 0x00dd, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x01a4, 0x00cf, 0x012f,\n 0x0211, 0x00de, 0x014a, 0x00cf, 0x0215, 0x0030, 0x0030, 0x0219,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x01a4, 0x00cf, 0x00cf, 0x0210,\n 0x00de, 0x00de, 0x00cf, 0x012f, 0x0030, 0x0030, 0x021d, 0x00de,\n 0x0221, 0x0224, 0x0228, 0x022c, 0x022e, 0x003f, 0x00ef, 0x0040,\n 0x0030, 0x0030, 0x0129, 0x0040, 0x0040, 0x0232, 0x0234, 0x0236,\n 0x0040, 0x0040, 0x0040, 0x00dd, 0x00f9, 0x00cf, 0x00cf, 0x023a,\n 0x00cf, 0x00fc, 0x0040, 0x0140, 0x00cf, 0x00cf, 0x00f9, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x023e, 0x0040,\n 0x0116, 0x0040, 0x00e4, 0x0242, 0x0040, 0x0246, 0x00de, 0x00de,\n 0x00de, 0x00f9, 0x024a, 0x00cf, 0x019c, 0x01a8, 0x0030, 0x0030,\n 0x0219, 0x0040, 0x00de, 0x01d3, 0x0142, 0x014b, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x00f9, 0x0210, 0x00de, 0x00de, 0x017e, 0x01a8,\n 0x00de, 0x017f, 0x0030, 0x0030, 0x021d, 0x017f, 0x0040, 0x00e3,\n 0x00de, 0x01f1, 0x0040, 0x0040, 0x0040, 0x0040, 0x024e, 0x024e,\n 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x0252, 0x0252,\n 0x0252, 0x0252, 0x0252, 0x0252, 0x0252, 0x0252, 0x0256, 0x0256,\n 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0040, 0x0040,\n 0x00e4, 0x01a1, 0x0040, 0x00e2, 0x00e4, 0x01a1, 0x0040, 0x0040,\n 0x00e4, 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4, 0x01a1,\n 0x0040, 0x00e2, 0x00e4, 0x01a1, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4, 0x01a1, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00f9, 0x025a, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01a1, 0x0040, 0x01a1, 0x025b, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x025b, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0058, 0x025f, 0x0040, 0x0040,\n 0x0263, 0x0266, 0x0040, 0x0040, 0x00dd, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x026a, 0x00de, 0x00df, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x026e, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x00e4, 0x0272, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0274, 0x00cf, 0x0160, 0x01fa, 0x01d5, 0x015e, 0x00cf, 0x00cf,\n 0x0278, 0x027c, 0x017f, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x01a1, 0x00de, 0x0280, 0x0284, 0x0288, 0x028b, 0x0030,\n 0x0030, 0x021d, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00dd, 0x00de, 0x0040, 0x00ee, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01b2, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0150, 0x028f, 0x0161,\n 0x00de, 0x01d5, 0x01fa, 0x015e, 0x00de, 0x00dd, 0x010f, 0x0030,\n 0x0030, 0x00de, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030, 0x0293,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec, 0x01c8,\n 0x00d8, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0296, 0x00cf,\n 0x012f, 0x020e, 0x00f9, 0x00cf, 0x0161, 0x028f, 0x00cf, 0x00cf,\n 0x01aa, 0x0030, 0x0030, 0x021d, 0x00de, 0x0030, 0x0030, 0x021d,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x012f, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x0299, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x024a, 0x0150, 0x0161,\n 0x01d5, 0x0299, 0x00de, 0x029b, 0x00de, 0x00de, 0x029b, 0x029f,\n 0x02a2, 0x02a3, 0x02a4, 0x00cf, 0x00cf, 0x02a3, 0x02a3, 0x029f,\n 0x0151, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x02a8, 0x0160, 0x0274, 0x00ef, 0x0030, 0x0030, 0x0129, 0x0040,\n 0x00de, 0x02ac, 0x0160, 0x02af, 0x0160, 0x00de, 0x00de, 0x0040,\n 0x01fa, 0x01fa, 0x00cf, 0x00cf, 0x015d, 0x029a, 0x02b3, 0x0030,\n 0x0030, 0x021d, 0x00e1, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0264, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040, 0x0040,\n 0x00de, 0x00de, 0x0215, 0x00cf, 0x00cf, 0x00cf, 0x024a, 0x00cf,\n 0x0118, 0x0117, 0x0040, 0x02b7, 0x02bb, 0x00de, 0x00cf, 0x00cf,\n 0x00cf, 0x02bf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x02c0, 0x0040, 0x01a1, 0x0040, 0x01a1, 0x0040, 0x0040,\n 0x01af, 0x01af, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4,\n 0x0040, 0x0040, 0x0040, 0x00d8, 0x0040, 0x00e1, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00d8, 0x00e4, 0x0040, 0x02c4, 0x02b3, 0x02c8,\n 0x02cc, 0x02d0, 0x02d4, 0x00c8, 0x02d8, 0x02d8, 0x02dc, 0x02e0,\n 0x02e4, 0x02e6, 0x02ea, 0x02ee, 0x02f2, 0x02f6, 0x0040, 0x02fa,\n 0x02fd, 0x0040, 0x0040, 0x02ff, 0x02b3, 0x0303, 0x0307, 0x030a,\n 0x00cf, 0x00cf, 0x01a1, 0x00c3, 0x0040, 0x030e, 0x0094, 0x00c3,\n 0x0040, 0x0312, 0x0040, 0x0040, 0x0040, 0x00dd, 0x0316, 0x0317,\n 0x0316, 0x031b, 0x0316, 0x031d, 0x0317, 0x031d, 0x031f, 0x0316,\n 0x0316, 0x0316, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x0323, 0x00a2, 0x0325, 0x0040, 0x00a0, 0x0327,\n 0x0040, 0x0040, 0x032a, 0x009d, 0x00a0, 0x0040, 0x0040, 0x0040,\n 0x032d, 0x0040, 0x0040, 0x0040, 0x0040, 0x0331, 0x0334, 0x0331,\n 0x00c8, 0x00c7, 0x00c7, 0x00c7, 0x0040, 0x00c7, 0x00c7, 0x0338,\n 0x0040, 0x0040, 0x00a2, 0x00de, 0x00c7, 0x033c, 0x033e, 0x0040,\n 0x0040, 0x0341, 0x0040, 0x0040, 0x0040, 0x00a6, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00a1, 0x00c3, 0x0040, 0x0040, 0x00b4, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0345, 0x00a0, 0x0348,\n 0x00a0, 0x034a, 0x00a2, 0x00a1, 0x0094, 0x0348, 0x0344, 0x00c7,\n 0x00ca, 0x0040, 0x00c7, 0x0040, 0x0338, 0x0040, 0x0040, 0x00c3,\n 0x00c3, 0x00a1, 0x0040, 0x0040, 0x0040, 0x0338, 0x00c7, 0x00c5,\n 0x00c5, 0x0040, 0x0040, 0x0040, 0x0040, 0x00c5, 0x00c5, 0x0040,\n 0x0040, 0x0040, 0x00a2, 0x00a2, 0x0040, 0x00a2, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00a0, 0x0040, 0x0040, 0x0040, 0x034e,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0352, 0x0040, 0x00a1, 0x0040,\n 0x0356, 0x0040, 0x0040, 0x035a, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x035e, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x035f,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0363, 0x0366, 0x036a, 0x0040,\n 0x036e, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x00c7, 0x0372, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x00c7, 0x0375, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x0378, 0x00c9,\n 0x00c7, 0x037c, 0x0040, 0x00c5, 0x0380, 0x0040, 0x0338, 0x0382,\n 0x00c5, 0x0348, 0x00c5, 0x0338, 0x0040, 0x0040, 0x0040, 0x00c5,\n 0x0338, 0x0040, 0x00a0, 0x0040, 0x0040, 0x035f, 0x0386, 0x038a,\n 0x038e, 0x0391, 0x0393, 0x036e, 0x0397, 0x039b, 0x039f, 0x03a3,\n 0x03a3, 0x03a3, 0x03a3, 0x03a7, 0x03a7, 0x03ab, 0x03a3, 0x03af,\n 0x03a3, 0x03a7, 0x03a7, 0x03a7, 0x03a3, 0x03a3, 0x03a3, 0x03b3,\n 0x03b3, 0x03b7, 0x03b3, 0x03a3, 0x03a3, 0x03a3, 0x0367, 0x03a3,\n 0x037e, 0x03bb, 0x03bd, 0x03a4, 0x03a3, 0x03a3, 0x0393, 0x03c1,\n 0x03a3, 0x03a5, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03c4, 0x038a,\n 0x03c5, 0x03c8, 0x03cb, 0x03ce, 0x03d2, 0x03c7, 0x03d6, 0x03d9,\n 0x03a3, 0x03dc, 0x033c, 0x03df, 0x03e3, 0x03e6, 0x03e9, 0x038a,\n 0x03ed, 0x03f1, 0x03f5, 0x036e, 0x03f8, 0x0040, 0x032d, 0x0040,\n 0x03fc, 0x0040, 0x035f, 0x035e, 0x0040, 0x009e, 0x0040, 0x0400,\n 0x0040, 0x0404, 0x0407, 0x040a, 0x040e, 0x0411, 0x0414, 0x03a2,\n 0x0352, 0x0352, 0x0352, 0x0418, 0x00c7, 0x00c7, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0363, 0x0040, 0x0040, 0x032d, 0x0040,\n 0x0040, 0x0040, 0x03fc, 0x0040, 0x0040, 0x0407, 0x0040, 0x041c,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x041f, 0x0352,\n 0x0352, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x037e, 0x0040,\n 0x0040, 0x0058, 0x0422, 0x0422, 0x0422, 0x0422, 0x0422, 0x0426,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0352, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0354, 0x0040,\n 0x0429, 0x0040, 0x0040, 0x0040, 0x0040, 0x0407, 0x03fc, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x03fc, 0x042d, 0x0338, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00d8, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e3, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00ef, 0x00de,\n 0x0431, 0x0434, 0x0040, 0x0040, 0x00de, 0x00df, 0x0437, 0x00de,\n 0x00de, 0x014a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x00de, 0x00de, 0x0040, 0x00e2, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x0040, 0x00e2, 0x0411, 0x0411, 0x0411, 0x043b, 0x02b3, 0x043d,\n 0x0441, 0x0445, 0x0449, 0x0352, 0x044b, 0x044d, 0x043d, 0x025b,\n 0x01a1, 0x0451, 0x0455, 0x02b3, 0x0451, 0x0453, 0x003c, 0x0459,\n 0x045b, 0x045f, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0465, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x00de, 0x00de, 0x00de, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0468, 0x00de, 0x00de, 0x00de, 0x00de, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x046c, 0x046f, 0x0473, 0x0473, 0x0475, 0x0473,\n 0x0473, 0x0479, 0x0463, 0x0463, 0x047d, 0x047f, 0x0483, 0x0486,\n 0x0488, 0x048b, 0x048f, 0x0491, 0x0486, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0491, 0x0463, 0x0485, 0x0463, 0x0493,\n 0x0496, 0x0499, 0x049d, 0x0491, 0x0486, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0491, 0x0463, 0x0485, 0x0463, 0x049f,\n 0x0488, 0x04a3, 0x00de, 0x0462, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0462, 0x0463, 0x0463, 0x0463, 0x0464, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0468, 0x00de, 0x04a7, 0x04ab, 0x04ab,\n 0x04ab, 0x04ab, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0464, 0x0463, 0x0463, 0x00c7, 0x00c7, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x04af, 0x04b1, 0x0463, 0x03bd, 0x03bd,\n 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x046f, 0x0463, 0x0463, 0x0463, 0x04a6,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0464, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x04b5, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0030, 0x0030, 0x0129, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x00ec, 0x0215, 0x00cf, 0x00cf, 0x00ef,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ed,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x04b9, 0x02b3, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x01a1, 0x00e3, 0x00e1, 0x0040, 0x00dd,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00d8, 0x0040, 0x0040, 0x0040,\n 0x0116, 0x0116, 0x00ec, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x01f7, 0x04bd, 0x0040, 0x0210, 0x0040, 0x0040, 0x04c1, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x04c5, 0x00de, 0x00de,\n 0x04c9, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x01fa, 0x01fa, 0x01fa, 0x0142, 0x00de, 0x029b, 0x0030, 0x0030,\n 0x021d, 0x00de, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00ef, 0x0040,\n 0x0040, 0x04cd, 0x0040, 0x00ed, 0x00cf, 0x04d0, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ec, 0x00cf, 0x00cf, 0x0160, 0x00de, 0x00de,\n 0x00df, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e,\n 0x04d4, 0x0150, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x014a, 0x015d, 0x0160, 0x0160, 0x04d8, 0x04d9, 0x02a1,\n 0x04dd, 0x00de, 0x00de, 0x00de, 0x04e1, 0x00de, 0x017f, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x00de, 0x00f9, 0x0150,\n 0x04bd, 0x01a8, 0x00de, 0x00de, 0x02b4, 0x02b3, 0x02b3, 0x026a,\n 0x00de, 0x00de, 0x00de, 0x029f, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0210, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x019b, 0x01aa, 0x0210, 0x014b, 0x017f, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x01f7, 0x0160,\n 0x0266, 0x04e5, 0x00de, 0x00de, 0x00e1, 0x00e2, 0x00e1, 0x00e2,\n 0x00e1, 0x00e2, 0x00de, 0x00de, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x01f7, 0x01d6, 0x04e9, 0x01dc, 0x0030, 0x0030, 0x021d,\n 0x00de, 0x04ed, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee,\n 0x04ed, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x00de,\n 0x00de, 0x00de, 0x0252, 0x0252, 0x0252, 0x0252, 0x04f2, 0x04f5,\n 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x00de,\n 0x0040, 0x00e2, 0x00de, 0x00de, 0x00df, 0x0040, 0x00de, 0x01b1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x01ae,\n 0x00e3, 0x00e4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00e2, 0x00de, 0x00de, 0x00de, 0x00df, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x04f9, 0x0040, 0x0040, 0x00de,\n 0x00df, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x04fd, 0x00cf, 0x00cf, 0x00cf, 0x0501, 0x0505, 0x0508, 0x050c,\n 0x00de, 0x0510, 0x0512, 0x0511, 0x0513, 0x0463, 0x0472, 0x0517,\n 0x0517, 0x051b, 0x051f, 0x0463, 0x0523, 0x0527, 0x0472, 0x0474,\n 0x0463, 0x0464, 0x052b, 0x00de, 0x0040, 0x00e4, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x052f, 0x0533, 0x0537,\n 0x0475, 0x053b, 0x0463, 0x0463, 0x053e, 0x0542, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0546, 0x053c, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0546, 0x054a, 0x054e, 0x0551,\n 0x00de, 0x00de, 0x0554, 0x02a3, 0x02a3, 0x02a3, 0x02a3, 0x02a3,\n 0x02a3, 0x02a3, 0x0556, 0x02a3, 0x02a3, 0x02a3, 0x02a3, 0x02a3,\n 0x02a3, 0x02a3, 0x055a, 0x04e1, 0x02a3, 0x04e1, 0x02a3, 0x04e1,\n 0x02a3, 0x04e1, 0x055c, 0x0560, 0x0563, 0x0040, 0x00e2, 0x0000,\n 0x0000, 0x02e5, 0x0333, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e2, 0x00e3, 0x0040, 0x0040, 0x0040, 0x01a1, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x0567, 0x00df, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00df, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x056b,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd,\n 0x00de, 0x00de, 0x00de, 0x0118, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x012f, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x056f, 0x0040, 0x00de, 0x0040,\n 0x0040, 0x025b, 0x01a1, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00de, 0x00de, 0x00df, 0x0040, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x00e3, 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040, 0x00e3, 0x00dd,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0040, 0x00e3, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x00e2, 0x00de, 0x0040,\n 0x01a1, 0x00e4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e3,\n 0x00dd, 0x0170, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x056f,\n 0x0040, 0x0040, 0x00de, 0x00df, 0x0040, 0x0040, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x01a1,\n 0x00df, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x029a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1,\n 0x00df, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de,\n 0x0040, 0x0140, 0x01ea, 0x00de, 0x00cf, 0x0040, 0x00e1, 0x00e1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x012f, 0x014a,\n 0x0040, 0x0040, 0x00dd, 0x00de, 0x02b3, 0x02b3, 0x00dd, 0x00de,\n 0x0040, 0x0573, 0x00df, 0x0040, 0x02b3, 0x0577, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x02c7, 0x02b3,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x00de, 0x00e1, 0x00dd, 0x00de, 0x00de,\n 0x00e1, 0x0040, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x00dd, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00e2, 0x00de, 0x00d8, 0x0040, 0x00cf, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040, 0x01a1, 0x00f9,\n 0x057b, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00d8,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x057e, 0x0581,\n 0x01a1, 0x00de, 0x00de, 0x00de, 0x00d8, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x0040, 0x00ed,\n 0x00cf, 0x00cf, 0x0118, 0x0040, 0x01a1, 0x00de, 0x00ed, 0x00ef,\n 0x01a1, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0297, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x00cf,\n 0x00fa, 0x02a2, 0x055b, 0x04e1, 0x02a3, 0x02a3, 0x02a3, 0x055b,\n 0x00de, 0x00de, 0x01aa, 0x0210, 0x00de, 0x0583, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x0150, 0x02ba, 0x0587, 0x0589, 0x00de,\n 0x00de, 0x058c, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de,\n 0x0030, 0x0030, 0x021d, 0x00de, 0x0215, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00cf, 0x015e, 0x00cf,\n 0x0590, 0x0030, 0x0030, 0x02b3, 0x0594, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00ec, 0x02c4, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01f7, 0x015d, 0x00cf, 0x0150, 0x0596,\n 0x0265, 0x059a, 0x01cb, 0x0030, 0x0030, 0x059e, 0x0303, 0x00e1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x0160, 0x024a, 0x043d, 0x05a2, 0x056b,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x00e2, 0x00e4, 0x00e3, 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040,\n 0x0040, 0x05a5, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x028f,\n 0x00cf, 0x012f, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0160,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x014a,\n 0x05a9, 0x0161, 0x0183, 0x0183, 0x05ab, 0x00de, 0x0189, 0x00de,\n 0x04df, 0x01d3, 0x014b, 0x00cf, 0x0210, 0x00cf, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x05ad, 0x028f, 0x00cf, 0x05b1,\n 0x05b2, 0x01fb, 0x01d5, 0x05b6, 0x05b9, 0x055c, 0x00de, 0x01ea,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01f9, 0x00cf, 0x00cf, 0x015d,\n 0x0159, 0x0263, 0x0451, 0x0030, 0x0030, 0x0219, 0x01b1, 0x01a1,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x028f, 0x00cf, 0x02ae, 0x028f, 0x024a,\n 0x0040, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x01f7, 0x015d, 0x0142, 0x01fa, 0x0274, 0x05bd,\n 0x05c1, 0x0303, 0x02b3, 0x02b3, 0x02b3, 0x0040, 0x0142, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x028f, 0x00cf, 0x0150, 0x02af, 0x05c5,\n 0x00dd, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x05c9,\n 0x05c9, 0x05c9, 0x05cc, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x00ec, 0x01d6, 0x00cf, 0x0274, 0x01a1, 0x00de, 0x0030,\n 0x0030, 0x021d, 0x00de, 0x0030, 0x0030, 0x0030, 0x0030, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0249, 0x014b,\n 0x0274, 0x00cf, 0x00de, 0x0030, 0x0030, 0x021d, 0x0567, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x00cf, 0x00cf, 0x02ba, 0x00de, 0x0030,\n 0x0030, 0x0129, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00df, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x01fa, 0x01d8, 0x05d0, 0x05d3, 0x05d7,\n 0x0567, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01f9, 0x00cf, 0x014b, 0x01fa, 0x02c3,\n 0x0299, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0140,\n 0x00cf, 0x0215, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec,\n 0x00cf, 0x05da, 0x05dd, 0x0303, 0x05e1, 0x00de, 0x00de, 0x0140,\n 0x0150, 0x015e, 0x0040, 0x05e5, 0x05e7, 0x00cf, 0x00cf, 0x0150,\n 0x04d0, 0x05c7, 0x05eb, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x05c9, 0x05c9, 0x05cb, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x01a1, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030,\n 0x021d, 0x00de, 0x0040, 0x0040, 0x00e4, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01f7, 0x00cf, 0x012f, 0x00cf, 0x0274, 0x0303,\n 0x05ec, 0x00de, 0x00de, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040,\n 0x0040, 0x00dd, 0x05f0, 0x0040, 0x0040, 0x0040, 0x0040, 0x014b,\n 0x00cf, 0x00cf, 0x00cf, 0x05f4, 0x00cf, 0x024a, 0x01a8, 0x00de,\n 0x00de, 0x0040, 0x00e2, 0x00e3, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0140, 0x012f, 0x017e, 0x0130, 0x00cf, 0x05f6, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040, 0x00e3, 0x00e4,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01f8, 0x01fb, 0x05f9,\n 0x02af, 0x00dd, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x05fd, 0x04e9, 0x0437, 0x00de, 0x0600,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x015d,\n 0x012f, 0x01d3, 0x0275, 0x02a2, 0x02a3, 0x02a3, 0x00de, 0x00de,\n 0x017e, 0x00de, 0x00de, 0x00de, 0x00de, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0107, 0x04fd, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de,\n 0x029a, 0x0040, 0x0040, 0x0040, 0x00e2, 0x02b3, 0x0437, 0x00de,\n 0x00de, 0x0040, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0604,\n 0x0607, 0x0609, 0x041f, 0x0354, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x060c, 0x0040, 0x0040, 0x0040, 0x0058, 0x00d3,\n 0x0610, 0x0614, 0x0618, 0x0118, 0x00ec, 0x00cf, 0x00cf, 0x00cf,\n 0x0142, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x041f, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x014b, 0x00cf, 0x00cf, 0x0160, 0x015e,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x029b,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00cf, 0x0581, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00cf, 0x00fa, 0x0266,\n 0x0040, 0x061c, 0x00de, 0x00de, 0x0030, 0x0030, 0x0620, 0x0040,\n 0x00e3, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x00e1,\n 0x0623, 0x0623, 0x0626, 0x0264, 0x0030, 0x0030, 0x021d, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0263, 0x057d, 0x00de,\n 0x0040, 0x0040, 0x00e2, 0x014a, 0x01f9, 0x01fa, 0x01fa, 0x01fa,\n 0x01fa, 0x01fa, 0x01fa, 0x01fa, 0x01fa, 0x00de, 0x014a, 0x0215,\n 0x0040, 0x0040, 0x0040, 0x062a, 0x062e, 0x00de, 0x00de, 0x0632,\n 0x00de, 0x00de, 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd,\n 0x0636, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0638, 0x0463, 0x0463, 0x04a6, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x03bd, 0x063a, 0x03bd, 0x0635, 0x0464, 0x00de, 0x00de,\n 0x00de, 0x063e, 0x00de, 0x00de, 0x00de, 0x00de, 0x0642, 0x0645,\n 0x00de, 0x00de, 0x04ab, 0x00de, 0x00de, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0040, 0x0040, 0x00e2, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x00dd, 0x00de, 0x0040, 0x0040, 0x01a1, 0x04cf, 0x00cf, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0030, 0x0030, 0x021d, 0x00de, 0x00cf, 0x00cf,\n 0x00cf, 0x0142, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x012f, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x015c, 0x00ef, 0x01f9, 0x028f,\n 0x00cf, 0x00cf, 0x00cf, 0x0215, 0x0140, 0x00cf, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00ed, 0x00ef, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00ed, 0x0133, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x063b, 0x00de,\n 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x0649, 0x00dd,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00e4, 0x0144, 0x01a0, 0x00e1, 0x00e4, 0x0040, 0x0040, 0x00e3,\n 0x00e1, 0x0040, 0x00e1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e3, 0x00e2, 0x00e1, 0x0040, 0x00e4, 0x0040, 0x00e4,\n 0x0040, 0x01ae, 0x00d8, 0x0040, 0x00e4, 0x0040, 0x0040, 0x0040,\n 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x018d,\n 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,\n 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x0215, 0x00ec, 0x00cf,\n 0x00cf, 0x00cf, 0x0118, 0x0040, 0x0117, 0x0040, 0x0040, 0x064d,\n 0x0451, 0x00de, 0x00de, 0x00de, 0x014a, 0x00cf, 0x00f9, 0x00cf,\n 0x00cf, 0x00cf, 0x00de, 0x00de, 0x00de, 0x00de, 0x00e1, 0x00e2,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x012f, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x01aa, 0x00cf, 0x0130, 0x019b, 0x012f,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x014a, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00dd, 0x00cf, 0x0215, 0x0040, 0x01a1, 0x0030,\n 0x0030, 0x021d, 0x00d8, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0199, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00cf, 0x0030, 0x0030, 0x021d, 0x0211, 0x0040,\n 0x0040, 0x0040, 0x00cf, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x0651, 0x0030, 0x0293, 0x00df, 0x0040,\n 0x00e2, 0x0040, 0x01a0, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040,\n 0x0170, 0x0040, 0x0040, 0x00cf, 0x012f, 0x00de, 0x00de, 0x0040,\n 0x00cf, 0x0215, 0x00de, 0x0030, 0x0030, 0x021d, 0x0655, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040, 0x04fd,\n 0x04fd, 0x00dd, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a0, 0x0170, 0x00e1, 0x0040,\n 0x00e2, 0x0040, 0x01af, 0x00de, 0x0144, 0x00df, 0x01af, 0x00e1,\n 0x01a0, 0x0170, 0x01af, 0x01af, 0x01a0, 0x0170, 0x00e2, 0x0040,\n 0x00e2, 0x0040, 0x00e1, 0x01ae, 0x0040, 0x0040, 0x00e3, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00de, 0x00e1, 0x00e1, 0x00e3, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00de, 0x038a, 0x0659, 0x038a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x065a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x00c7, 0x00c7, 0x065e, 0x0661, 0x00c7,\n 0x00c7, 0x00c7, 0x00c7, 0x0665, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x0338, 0x03a3, 0x0669, 0x00c7, 0x00c7, 0x066b, 0x00c7, 0x00c7,\n 0x00c7, 0x066f, 0x0672, 0x0673, 0x0674, 0x00c7, 0x00c7, 0x00c7,\n 0x0677, 0x038a, 0x038a, 0x038a, 0x038a, 0x0679, 0x067b, 0x067b,\n 0x067b, 0x067b, 0x067b, 0x067b, 0x067f, 0x038a, 0x038a, 0x038a,\n 0x0463, 0x0463, 0x04b0, 0x0463, 0x0463, 0x0463, 0x04af, 0x0683,\n 0x0685, 0x0686, 0x038a, 0x0463, 0x0463, 0x0689, 0x038a, 0x03f3,\n 0x038a, 0x038a, 0x038a, 0x0685, 0x03f3, 0x038a, 0x038a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0685, 0x0659, 0x038a, 0x038a, 0x068c, 0x0685,\n 0x068e, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068f, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x038a, 0x038a,\n 0x0693, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0697, 0x0685,\n 0x0699, 0x0685, 0x0685, 0x068d, 0x065a, 0x0685, 0x038a, 0x038a,\n 0x038a, 0x0685, 0x0685, 0x0685, 0x0685, 0x0659, 0x0659, 0x069a,\n 0x069d, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068d, 0x068f, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x0685, 0x06a1, 0x0699, 0x0685, 0x06a4, 0x0697, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x036a, 0x03a7, 0x06a7,\n 0x0685, 0x0685, 0x0685, 0x06a4, 0x03a7, 0x03a7, 0x0699, 0x0685,\n 0x0685, 0x06a5, 0x03a7, 0x03a7, 0x06ab, 0x0040, 0x0340, 0x06af,\n 0x068d, 0x0685, 0x0685, 0x0685, 0x0685, 0x038a, 0x038a, 0x038a,\n 0x038a, 0x06b3, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x03f2,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x03a3, 0x03a3, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x03a3, 0x06af, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x040f,\n 0x06b7, 0x0040, 0x0685, 0x03f3, 0x038a, 0x0659, 0x068d, 0x068c,\n 0x038a, 0x0685, 0x038a, 0x038a, 0x065a, 0x0659, 0x038a, 0x0685,\n 0x0685, 0x0659, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x038a,\n 0x038a, 0x038a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0389,\n 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x038a, 0x0659, 0x038a,\n 0x038a, 0x038a, 0x0040, 0x0040, 0x0040, 0x06bb, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x06bb, 0x06bb, 0x0040, 0x0040, 0x06bf, 0x06bb,\n 0x0040, 0x0040, 0x06bb, 0x06bb, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x06bf, 0x03a3, 0x03a3, 0x03a3, 0x06bb, 0x06c3, 0x06bb, 0x06bb,\n 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x0040, 0x0040,\n 0x0040, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x06c7,\n 0x0685, 0x06c8, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x0659,\n 0x0685, 0x0685, 0x03f3, 0x065a, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068d, 0x038a, 0x03f1, 0x0685, 0x0685, 0x0685, 0x036a, 0x0685,\n 0x0685, 0x03f3, 0x038a, 0x0685, 0x0685, 0x0659, 0x038a, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x06cc, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0468, 0x06d0,\n 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x0000, 0x0000, 0x0000, 0x0000, 0x00c7,\n 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x06d4,\n];\n#[rustfmt::skip]\nconst STAGE3: [u16; 1752] = [\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0963, 0x0802, 0x0803,\n 0x0803, 0x0801, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0900, 0x0ac0, 0x0c00, 0x0d80,\n 0x0d00, 0x0cc0, 0x0d80, 0x0c00,\n 0x0bc0, 0x0a80, 0x0d80, 0x0d00,\n 0x0c40, 0x09c0, 0x0c40, 0x0d40,\n 0x0c80, 0x0c80, 0x0c80, 0x0c80,\n 0x0c80, 0x0c80, 0x0c80, 0x0c80,\n 0x0c80, 0x0c80, 0x0c40, 0x0c40,\n 0x0d80, 0x0d80, 0x0d80, 0x0ac0,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0bc0,\n 0x0d00, 0x0a80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0bc0,\n 0x0940, 0x0a00, 0x0d80, 0x0803,\n 0x08c0, 0x1bc0, 0x0cc0, 0x0d00,\n 0x1d00, 0x0d00, 0x0d80, 0x1800,\n 0x0d8e, 0x1800, 0x0c00, 0x0d80,\n 0x0944, 0x1d8e, 0x0d80, 0x1cc0,\n 0x1d00, 0x1800, 0x1800, 0x1980,\n 0x0d80, 0x1800, 0x1800, 0x1800,\n 0x0c00, 0x1800, 0x1800, 0x1800,\n 0x1bc0, 0x0d80, 0x0d80, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x1800,\n 0x0d80, 0x0d80, 0x1d80, 0x1d80,\n 0x0d80, 0x0d80, 0x1d80, 0x1d80,\n 0x1d80, 0x0d80, 0x1d80, 0x1d80,\n 0x0d80, 0x1d80, 0x0d80, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x1d80,\n 0x1d80, 0x1d80, 0x1d80, 0x0d80,\n 0x0d80, 0x1800, 0x0980, 0x1800,\n 0x1800, 0x1800, 0x0980, 0x1800,\n 0x0d80, 0x0d80, 0x0d80, 0x1800,\n 0x1800, 0x1800, 0x1800, 0x0d80,\n 0x1800, 0x0d80, 0x1980, 0x0004,\n 0x0004, 0x0004, 0x0004, 0x00c4,\n 0x00c4, 0x00c4, 0x00c4, 0x0004,\n 0x0800, 0x0800, 0x0d80, 0x0d80,\n 0x0c40, 0x0d80, 0x0800, 0x0800,\n 0x0800, 0x0800, 0x0d80, 0x0d80,\n 0x0d80, 0x0800, 0x0d80, 0x0d80,\n 0x1d80, 0x1d80, 0x0800, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0004,\n 0x0004, 0x0d80, 0x0d80, 0x0c40,\n 0x0940, 0x0800, 0x0d80, 0x0d80,\n 0x0d00, 0x0800, 0x0004, 0x0004,\n 0x0004, 0x0940, 0x0004, 0x0004,\n 0x0ac0, 0x0004, 0x0486, 0x0486,\n 0x0486, 0x0486, 0x0d80, 0x0d80,\n 0x0cc0, 0x0cc0, 0x0cc0, 0x0004,\n 0x0004, 0x0004, 0x0ac0, 0x0ac0,\n 0x0ac0, 0x0c80, 0x0c80, 0x0cc0,\n 0x0c80, 0x0d80, 0x0d80, 0x0d80,\n 0x0004, 0x0d80, 0x0d80, 0x0d80,\n 0x0ac0, 0x0d80, 0x0004, 0x0004,\n 0x0486, 0x0d80, 0x0004, 0x0d80,\n 0x0d80, 0x0004, 0x0d80, 0x0004,\n 0x0004, 0x0c80, 0x0c80, 0x0d80,\n 0x0d80, 0x0800, 0x0586, 0x0004,\n 0x0004, 0x0004, 0x0800, 0x0004,\n 0x0d80, 0x0800, 0x0800, 0x0c40,\n 0x0ac0, 0x0d80, 0x0800, 0x0004,\n 0x0d00, 0x0d00, 0x0004, 0x0004,\n 0x0d80, 0x0004, 0x0004, 0x0004,\n 0x0800, 0x0800, 0x0d80, 0x0800,\n 0x0486, 0x0486, 0x0800, 0x0800,\n 0x0800, 0x0004, 0x0004, 0x0486,\n 0x0004, 0x0004, 0x0004, 0x0804,\n 0x0d80, 0x0d8d, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0004, 0x0804, 0x0004,\n 0x0d80, 0x0804, 0x0804, 0x0004,\n 0x0004, 0x0004, 0x0804, 0x0804,\n 0x0804, 0x000c, 0x0804, 0x0804,\n 0x0940, 0x0940, 0x0c80, 0x0c80,\n 0x0d80, 0x0004, 0x0804, 0x0804,\n 0x0d80, 0x0800, 0x0800, 0x0d80,\n 0x0d8d, 0x0800, 0x0d8d, 0x0d8d,\n 0x0800, 0x0d8d, 0x0800, 0x0800,\n 0x0d8d, 0x0d8d, 0x0800, 0x0800,\n 0x0004, 0x0800, 0x0800, 0x0804,\n 0x0800, 0x0800, 0x0804, 0x000c,\n 0x0d80, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0c80,\n 0x0c80, 0x0d8d, 0x0d8d, 0x0cc0,\n 0x0cc0, 0x0d80, 0x0cc0, 0x0d80,\n 0x0d00, 0x0d80, 0x0d80, 0x0004,\n 0x0800, 0x0004, 0x0004, 0x0804,\n 0x0800, 0x0d80, 0x0d80, 0x0800,\n 0x0800, 0x0004, 0x0800, 0x0804,\n 0x0804, 0x0004, 0x0004, 0x0800,\n 0x0800, 0x0004, 0x0d80, 0x0800,\n 0x0d80, 0x0800, 0x0d80, 0x0004,\n 0x0d80, 0x0800, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0004, 0x0804, 0x0800,\n 0x0804, 0x000c, 0x0800, 0x0800,\n 0x0d80, 0x0d00, 0x0800, 0x0800,\n 0x0d8d, 0x0004, 0x0004, 0x0800,\n 0x0004, 0x0804, 0x0804, 0x0004,\n 0x0d80, 0x0804, 0x0004, 0x0d80,\n 0x0d8d, 0x0d80, 0x0d80, 0x0800,\n 0x0800, 0x0804, 0x0804, 0x0004,\n 0x0804, 0x0804, 0x0800, 0x0804,\n 0x0804, 0x0004, 0x0800, 0x0800,\n 0x0d80, 0x0d00, 0x0d80, 0x0800,\n 0x0804, 0x0800, 0x0004, 0x0004,\n 0x000c, 0x0800, 0x0800, 0x0004,\n 0x0004, 0x0800, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0800, 0x0d80, 0x0800,\n 0x0800, 0x0800, 0x0980, 0x0d80,\n 0x0d80, 0x0d80, 0x0804, 0x0804,\n 0x0804, 0x0804, 0x0800, 0x0004,\n 0x0804, 0x0800, 0x0804, 0x0804,\n 0x0800, 0x0d80, 0x0d80, 0x0804,\n 0x000c, 0x0d86, 0x0d80, 0x0cc0,\n 0x0d80, 0x0d80, 0x0004, 0x0800,\n 0x0004, 0x0800, 0x0800, 0x0800,\n 0x0d00, 0x0004, 0x0004, 0x0004,\n 0x0d80, 0x0c80, 0x0c80, 0x0940,\n 0x0940, 0x0c80, 0x0c80, 0x0800,\n 0x0800, 0x0d80, 0x0980, 0x0980,\n 0x0980, 0x0d80, 0x0980, 0x0980,\n 0x08c0, 0x0980, 0x0980, 0x0940,\n 0x08c0, 0x0ac0, 0x0ac0, 0x0ac0,\n 0x08c0, 0x0d80, 0x0940, 0x0004,\n 0x0d80, 0x0004, 0x0bc0, 0x0a00,\n 0x0804, 0x0804, 0x0004, 0x0004,\n 0x0004, 0x0944, 0x0004, 0x0800,\n 0x0940, 0x0940, 0x0980, 0x0980,\n 0x0940, 0x0980, 0x0d80, 0x08c0,\n 0x08c0, 0x0800, 0x0004, 0x0804,\n 0x0004, 0x0004, 0x1007, 0x1007,\n 0x1007, 0x1007, 0x0808, 0x0808,\n 0x0808, 0x0808, 0x0809, 0x0809,\n 0x0809, 0x0809, 0x0d80, 0x0940,\n 0x0d80, 0x0d80, 0x0d80, 0x0a00,\n 0x0800, 0x0800, 0x0800, 0x0d80,\n 0x0d80, 0x0d80, 0x0940, 0x0940,\n 0x0d80, 0x0d80, 0x0004, 0x0804,\n 0x0800, 0x0800, 0x0804, 0x0940,\n 0x0940, 0x0800, 0x0d80, 0x0800,\n 0x0004, 0x0004, 0x0804, 0x0004,\n 0x0940, 0x0940, 0x0b40, 0x0800,\n 0x0940, 0x0d80, 0x0940, 0x0d00,\n 0x0d80, 0x0d80, 0x0ac0, 0x0ac0,\n 0x0940, 0x0940, 0x0980, 0x0d80,\n 0x0ac0, 0x0ac0, 0x0d80, 0x0004,\n 0x0004, 0x00c4, 0x0004, 0x0804,\n 0x0804, 0x0804, 0x0004, 0x0c80,\n 0x0c80, 0x0c80, 0x0800, 0x0804,\n 0x0004, 0x0804, 0x0800, 0x0800,\n 0x0800, 0x0940, 0x0940, 0x0dc0,\n 0x0940, 0x0940, 0x0940, 0x0dc0,\n 0x0dc0, 0x0dc0, 0x0dc0, 0x0004,\n 0x0d80, 0x0804, 0x0004, 0x0004,\n 0x0800, 0x0800, 0x0004, 0x0804,\n 0x0004, 0x0804, 0x0004, 0x0940,\n 0x0940, 0x0940, 0x0940, 0x0004,\n 0x0d80, 0x0d80, 0x0804, 0x0004,\n 0x0004, 0x0d80, 0x0800, 0x0004,\n 0x00c4, 0x0004, 0x0004, 0x0004,\n 0x0d80, 0x0980, 0x0d80, 0x0800,\n 0x0940, 0x0940, 0x0940, 0x08c0,\n 0x0940, 0x0940, 0x0940, 0x0084,\n 0x0004, 0x000f, 0x0004, 0x0004,\n 0x1940, 0x08c0, 0x0940, 0x1940,\n 0x1c00, 0x1c00, 0x0bc0, 0x0c00,\n 0x1800, 0x1800, 0x1d80, 0x0d80,\n 0x1b00, 0x1b00, 0x1b00, 0x1940,\n 0x0803, 0x0803, 0x0004, 0x0004,\n 0x0004, 0x08c0, 0x1cc0, 0x0cc0,\n 0x1cc0, 0x1cc0, 0x0cc0, 0x1cc0,\n 0x0cc0, 0x0cc0, 0x0d80, 0x0c00,\n 0x0c00, 0x1800, 0x0b4e, 0x0b40,\n 0x1d80, 0x0d80, 0x0c40, 0x0bc0,\n 0x0a00, 0x0b40, 0x0b4e, 0x0d80,\n 0x0d80, 0x0940, 0x0cc0, 0x0d80,\n 0x0940, 0x0940, 0x0940, 0x0044,\n 0x0584, 0x0584, 0x0584, 0x0803,\n 0x0004, 0x0004, 0x0d80, 0x0bc0,\n 0x0a00, 0x1800, 0x0d80, 0x0bc0,\n 0x0a00, 0x0800, 0x0d00, 0x0d00,\n 0x0d00, 0x0d00, 0x0cc0, 0x1d00,\n 0x0d00, 0x0d00, 0x0d00, 0x0cc0,\n 0x0d00, 0x0d00, 0x0d00, 0x0d80,\n 0x0d80, 0x0d80, 0x1cc0, 0x0d80,\n 0x0d80, 0x1d00, 0x0d80, 0x1800,\n 0x180e, 0x0d80, 0x0d8e, 0x0d80,\n 0x0d80, 0x0800, 0x0800, 0x0800,\n 0x1800, 0x0800, 0x0800, 0x0800,\n 0x1800, 0x1800, 0x0d80, 0x0d80,\n 0x180e, 0x180e, 0x180e, 0x180e,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d8e,\n 0x0d80, 0x1800, 0x0d80, 0x1800,\n 0x1800, 0x0d80, 0x0d80, 0x1800,\n 0x0d00, 0x0d00, 0x0d80, 0x0d80,\n 0x0d80, 0x0b00, 0x0bc0, 0x0a00,\n 0x0bc0, 0x0a00, 0x0d80, 0x0d80,\n 0x15ce, 0x15ce, 0x0d8e, 0x1380,\n 0x1200, 0x0d80, 0x0d8e, 0x0d80,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d80,\n 0x158e, 0x158e, 0x158e, 0x0d8e,\n 0x0d8e, 0x0d8e, 0x15ce, 0x0dce,\n 0x0dce, 0x15ce, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x0d80, 0x1800, 0x1800,\n 0x180e, 0x1800, 0x1800, 0x0800,\n 0x1800, 0x1800, 0x1800, 0x1d80,\n 0x1800, 0x1800, 0x0d8e, 0x0d8e,\n 0x0d80, 0x0d80, 0x180e, 0x1800,\n 0x0d80, 0x0d80, 0x0d8e, 0x158e,\n 0x158e, 0x0d80, 0x0dce, 0x0dce,\n 0x0dce, 0x0dce, 0x0d8e, 0x180e,\n 0x1800, 0x0d8e, 0x180e, 0x0d8e,\n 0x0d8e, 0x180e, 0x180e, 0x15ce,\n 0x15ce, 0x080e, 0x080e, 0x0dce,\n 0x0d8e, 0x0dce, 0x0dce, 0x1dce,\n 0x0dce, 0x1dce, 0x0dce, 0x0d8e,\n 0x0d8e, 0x0d8e, 0x0d8e, 0x158e,\n 0x158e, 0x158e, 0x158e, 0x0d8e,\n 0x0dce, 0x0dce, 0x0dce, 0x180e,\n 0x0d8e, 0x180e, 0x0d8e, 0x180e,\n 0x180e, 0x0d8e, 0x180e, 0x1dce,\n 0x180e, 0x180e, 0x0d8e, 0x0d80,\n 0x0d80, 0x1580, 0x1580, 0x1580,\n 0x1580, 0x0d8e, 0x158e, 0x0d8e,\n 0x0d8e, 0x15ce, 0x15ce, 0x1dce,\n 0x1dce, 0x180e, 0x180e, 0x180e,\n 0x1dce, 0x158e, 0x1dce, 0x1dce,\n 0x180e, 0x1dce, 0x15ce, 0x180e,\n 0x180e, 0x180e, 0x1dce, 0x180e,\n 0x180e, 0x1dce, 0x1dce, 0x0d8e,\n 0x180e, 0x180e, 0x15ce, 0x180e,\n 0x1dce, 0x15ce, 0x15ce, 0x1dce,\n 0x15ce, 0x180e, 0x1dce, 0x1dce,\n 0x15ce, 0x180e, 0x15ce, 0x1dce,\n 0x1dce, 0x0dce, 0x158e, 0x0d80,\n 0x0d80, 0x0dce, 0x0dce, 0x15ce,\n 0x15ce, 0x0dce, 0x0dce, 0x0d8e,\n 0x0d8e, 0x0d80, 0x0d8e, 0x0d80,\n 0x158e, 0x0d80, 0x0d80, 0x0d80,\n 0x0d8e, 0x0d80, 0x0d80, 0x0d8e,\n 0x158e, 0x0d80, 0x158e, 0x0d80,\n 0x0d80, 0x0d80, 0x158e, 0x158e,\n 0x0d80, 0x100e, 0x0d80, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0c00,\n 0x0c00, 0x0d80, 0x0ac0, 0x0ace,\n 0x0bc0, 0x0a00, 0x1800, 0x1800,\n 0x0d80, 0x0bc0, 0x0a00, 0x0d80,\n 0x0d80, 0x0bc0, 0x0a00, 0x0bc0,\n 0x0a00, 0x0bc0, 0x0a00, 0x0d80,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x0d80, 0x100e, 0x1800,\n 0x1800, 0x0800, 0x0ac0, 0x0940,\n 0x0940, 0x0d80, 0x0ac0, 0x0940,\n 0x0800, 0x0800, 0x0800, 0x0c00,\n 0x0c00, 0x0940, 0x0940, 0x0d80,\n 0x0940, 0x0bc0, 0x0940, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0bc0,\n 0x0a00, 0x0940, 0x0940, 0x0ac0,\n 0x0d80, 0x0940, 0x0940, 0x0940,\n 0x0d80, 0x0940, 0x0940, 0x0bc0,\n 0x0940, 0x0ac0, 0x0bc0, 0x0a80,\n 0x0bc0, 0x0a80, 0x0bc0, 0x0a80,\n 0x0940, 0x0800, 0x0800, 0x15c0,\n 0x15c0, 0x15c0, 0x15c0, 0x0800,\n 0x15c0, 0x15c0, 0x0800, 0x0800,\n 0x1140, 0x1200, 0x1200, 0x15c0,\n 0x1340, 0x15c0, 0x15c0, 0x1380,\n 0x1200, 0x1380, 0x1200, 0x15c0,\n 0x15c0, 0x1340, 0x1380, 0x1200,\n 0x1200, 0x15c0, 0x15c0, 0x0004,\n 0x0004, 0x1004, 0x1004, 0x15ce,\n 0x15c0, 0x15c0, 0x15c0, 0x1000,\n 0x15c0, 0x15c0, 0x15c0, 0x1340,\n 0x15ce, 0x15c0, 0x0dc0, 0x0800,\n 0x1000, 0x15c0, 0x1000, 0x15c0,\n 0x1000, 0x1000, 0x0800, 0x0004,\n 0x0004, 0x1340, 0x1340, 0x1340,\n 0x15c0, 0x1340, 0x1000, 0x15c0,\n 0x1000, 0x1000, 0x15c0, 0x1000,\n 0x1340, 0x1340, 0x15c0, 0x0800,\n 0x0800, 0x0800, 0x15c0, 0x1000,\n 0x1000, 0x1000, 0x1000, 0x15c0,\n 0x15c0, 0x15c0, 0x15ce, 0x15c0,\n 0x15c0, 0x0d80, 0x0940, 0x0ac0,\n 0x0940, 0x0004, 0x0004, 0x0d80,\n 0x0940, 0x0804, 0x0004, 0x0004,\n 0x0804, 0x0cc0, 0x0d80, 0x0800,\n 0x0800, 0x0980, 0x0980, 0x0ac0,\n 0x0ac0, 0x0804, 0x0804, 0x0d80,\n 0x0d80, 0x0980, 0x0d80, 0x0d80,\n 0x0004, 0x0004, 0x0940, 0x0940,\n 0x1007, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0dc0, 0x0dc0, 0x0dc0,\n 0x0940, 0x0dc0, 0x0dc0, 0x0800,\n 0x0940, 0x0800, 0x0800, 0x0dc0,\n 0x0dc0, 0x0d80, 0x0804, 0x0004,\n 0x0800, 0x0004, 0x0804, 0x0804,\n 0x0940, 0x100a, 0x100b, 0x100b,\n 0x100b, 0x100b, 0x0808, 0x0808,\n 0x0808, 0x0800, 0x0800, 0x0800,\n 0x0809, 0x0d80, 0x0d80, 0x0a00,\n 0x0bc0, 0x0cc0, 0x0d80, 0x0d80,\n 0x0d80, 0x0004, 0x0004, 0x0004,\n 0x1004, 0x1200, 0x1200, 0x1200,\n 0x1340, 0x12c0, 0x12c0, 0x1380,\n 0x1200, 0x1300, 0x0800, 0x0800,\n 0x00c4, 0x0004, 0x00c4, 0x0004,\n 0x00c4, 0x00c4, 0x0004, 0x1200,\n 0x1380, 0x1200, 0x1380, 0x1200,\n 0x15c0, 0x15c0, 0x1380, 0x1200,\n 0x15c0, 0x15c0, 0x15c0, 0x1200,\n 0x15c0, 0x1200, 0x0800, 0x1340,\n 0x1340, 0x12c0, 0x12c0, 0x15c0,\n 0x1500, 0x14c0, 0x15c0, 0x0d80,\n 0x0800, 0x0800, 0x0044, 0x0800,\n 0x12c0, 0x15c0, 0x15c0, 0x1500,\n 0x14c0, 0x15c0, 0x15c0, 0x1200,\n 0x15c0, 0x1200, 0x15c0, 0x15c0,\n 0x1340, 0x1340, 0x15c0, 0x15c0,\n 0x15c0, 0x12c0, 0x15c0, 0x15c0,\n 0x15c0, 0x1380, 0x15c0, 0x1200,\n 0x15c0, 0x1380, 0x1200, 0x0a00,\n 0x0b80, 0x0a00, 0x0b40, 0x0dc0,\n 0x0800, 0x0dc0, 0x0dc0, 0x0dc0,\n 0x0b44, 0x0b44, 0x0dc0, 0x0dc0,\n 0x0dc0, 0x0800, 0x0800, 0x0800,\n 0x14c0, 0x1500, 0x15c0, 0x15c0,\n 0x1500, 0x1500, 0x0800, 0x0940,\n 0x0940, 0x0940, 0x0800, 0x0d80,\n 0x0004, 0x0800, 0x0800, 0x0d80,\n 0x0d80, 0x0800, 0x0940, 0x0d80,\n 0x0004, 0x0004, 0x0800, 0x0940,\n 0x0940, 0x0b00, 0x0800, 0x0004,\n 0x0004, 0x0940, 0x0d80, 0x0d80,\n 0x0800, 0x0004, 0x0940, 0x0800,\n 0x0800, 0x0800, 0x00c4, 0x0d80,\n 0x0486, 0x0940, 0x0940, 0x0004,\n 0x0800, 0x0486, 0x0800, 0x0800,\n 0x0004, 0x0800, 0x0c80, 0x0c80,\n 0x0d80, 0x0804, 0x0804, 0x0d80,\n 0x0d86, 0x0d86, 0x0940, 0x0004,\n 0x0004, 0x0004, 0x0c80, 0x0c80,\n 0x0d80, 0x0980, 0x0940, 0x0d80,\n 0x0004, 0x0d80, 0x0940, 0x0800,\n 0x0800, 0x0004, 0x0940, 0x0804,\n 0x0804, 0x0800, 0x0800, 0x0800,\n 0x0dc0, 0x0004, 0x0800, 0x0804,\n 0x0800, 0x0804, 0x0004, 0x0806,\n 0x0004, 0x0dc0, 0x0dc0, 0x0800,\n 0x0dc0, 0x0004, 0x0980, 0x0940,\n 0x0940, 0x0ac0, 0x0ac0, 0x0d80,\n 0x0d80, 0x0004, 0x0940, 0x0940,\n 0x0d80, 0x0980, 0x0980, 0x0980,\n 0x0980, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0004,\n 0x0804, 0x0004, 0x0806, 0x0804,\n 0x0806, 0x0804, 0x0004, 0x0804,\n 0x0d86, 0x0004, 0x0004, 0x0004,\n 0x0980, 0x0940, 0x0980, 0x0d80,\n 0x0004, 0x0d86, 0x0d86, 0x0d86,\n 0x0d86, 0x0004, 0x0004, 0x0980,\n 0x0940, 0x0940, 0x0800, 0x0800,\n 0x0980, 0x0ac0, 0x0d80, 0x0d80,\n 0x0800, 0x0804, 0x0004, 0x0004,\n 0x0d86, 0x0004, 0x0004, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0940,\n 0x0004, 0x0004, 0x0806, 0x0804,\n 0x0bc0, 0x0bc0, 0x0bc0, 0x0a00,\n 0x0a00, 0x0d80, 0x0d80, 0x0a00,\n 0x0d80, 0x0bc0, 0x0a00, 0x0a00,\n 0x00c4, 0x00c4, 0x00c4, 0x03c4,\n 0x0204, 0x00c4, 0x00c4, 0x00c4,\n 0x03c4, 0x0204, 0x03c4, 0x0204,\n 0x0940, 0x0d80, 0x0800, 0x0800,\n 0x0c80, 0x0c80, 0x0800, 0x0d80,\n 0x0d80, 0x0d80, 0x0d88, 0x0d88,\n 0x0d88, 0x0d80, 0x1340, 0x1340,\n 0x1340, 0x1340, 0x00c4, 0x0800,\n 0x0800, 0x0800, 0x1004, 0x1004,\n 0x0800, 0x0800, 0x1580, 0x1580,\n 0x0800, 0x0800, 0x0800, 0x1580,\n 0x1580, 0x1580, 0x0800, 0x0800,\n 0x1000, 0x0800, 0x1000, 0x1000,\n 0x1000, 0x0800, 0x1000, 0x0800,\n 0x0800, 0x1580, 0x1580, 0x1580,\n 0x0d80, 0x0004, 0x0d80, 0x0d80,\n 0x0940, 0x0d80, 0x0c80, 0x0c80,\n 0x0c80, 0x0800, 0x0800, 0x0bc0,\n 0x0bc0, 0x15ce, 0x0dce, 0x0dce,\n 0x0dce, 0x15ce, 0x1800, 0x1800,\n 0x1800, 0x0800, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x1800, 0x1800, 0x0d80,\n 0x0d8e, 0x180e, 0x180e, 0x1800,\n 0x1800, 0x180e, 0x180e, 0x1800,\n 0x1800, 0x100e, 0x1800, 0x100e,\n 0x100e, 0x100e, 0x100e, 0x1800,\n 0x0d8e, 0x0dce, 0x0dce, 0x0805,\n 0x0805, 0x0805, 0x0805, 0x15c0,\n 0x15ce, 0x15ce, 0x0dce, 0x15c0,\n 0x15c0, 0x15ce, 0x15ce, 0x15ce,\n 0x15ce, 0x15c0, 0x0dce, 0x0dce,\n 0x0dce, 0x15ce, 0x15ce, 0x15ce,\n 0x0dce, 0x15ce, 0x15ce, 0x0d8e,\n 0x0d8e, 0x0dce, 0x0dce, 0x15ce,\n 0x158e, 0x158e, 0x15ce, 0x15ce,\n 0x15ce, 0x15c4, 0x15c4, 0x15c4,\n 0x15c4, 0x158e, 0x15ce, 0x158e,\n 0x15ce, 0x15ce, 0x15ce, 0x158e,\n 0x158e, 0x158e, 0x15ce, 0x158e,\n 0x158e, 0x0d80, 0x0d80, 0x0d8e,\n 0x0d8e, 0x0dce, 0x15ce, 0x0dce,\n 0x0dce, 0x15ce, 0x0dce, 0x0c00,\n 0x0b40, 0x0b40, 0x0b40, 0x080e,\n 0x080e, 0x080e, 0x080e, 0x0d80,\n 0x0d80, 0x080e, 0x080e, 0x0d8e,\n 0x0d8e, 0x080e, 0x080e, 0x15ce,\n 0x15ce, 0x15ce, 0x0dc0, 0x15ce,\n 0x0dce, 0x0dce, 0x0800, 0x0800,\n 0x0803, 0x0004, 0x0803, 0x0803,\n 0x1800, 0x1800, 0x0800, 0x0800,\n];\n#[rustfmt::skip]\nconst GRAPHEME_JOIN_RULES: [[u32; 16]; 2] = [\n [\n 0b00111100111111111111110011111111,\n 0b11111111111111111111111111001111,\n 0b11111111111111111111111111111111,\n 0b11111111111111111111111111111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111010011111111,\n 0b00000000000000000000000011111100,\n 0b00111100000011000011110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00110000111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00001100111111111111110011111111,\n ],\n [\n 0b00111100111111111111110011111111,\n 0b11111111111111111111111111001111,\n 0b11111111111111111111111111111111,\n 0b11111111111111111111111111111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00000000000000000000000011111100,\n 0b00111100000011000011110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00110000111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00001100111111111111110011111111,\n ],\n];\n#[rustfmt::skip]\nconst LINE_BREAK_JOIN_RULES: [u32; 25] = [\n 0b00000000001000110011111110111010,\n 0b00000000111111111111111111111111,\n 0b00000000000000000000000000010000,\n 0b00000000111111111111111111111111,\n 0b00000000001000110000111100010010,\n 0b00000000001000110011111110110010,\n 0b00000000111111111111111111111111,\n 0b00000000001001110011111100110010,\n 0b00000000001110110011111110111010,\n 0b00000000001110110011111110111010,\n 0b00000000011111110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000111111111111111111111111,\n 0b00000000111111111111111111111111,\n 0b00000000111111111111111111111111,\n 0b00000000011111110011111110111010,\n 0b00000000011111111011111110111010,\n 0b00000000011001111111111110111010,\n 0b00000000111001111111111110111010,\n 0b00000000001111110011111110111010,\n 0b00000000011111111011111110111010,\n 0b00000000001010110011111110111010,\n 0b00000000000000000000000000000000,\n];\n#[inline(always)]\npub fn ucd_grapheme_cluster_lookup(cp: char) -> usize {\n unsafe {\n let cp = cp as usize;\n if cp < 0x80 {\n return STAGE3[cp] as usize;\n }\n let s = *STAGE0.get_unchecked(cp >> 11) as usize;\n let s = *STAGE1.get_unchecked(s + ((cp >> 5) & 63)) as usize;\n let s = *STAGE2.get_unchecked(s + ((cp >> 2) & 7)) as usize;\n *STAGE3.get_unchecked(s + (cp & 3)) as usize\n }\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_joins(state: u32, lead: usize, trail: usize) -> u32 {\n unsafe {\n let l = lead & 31;\n let t = trail & 31;\n let s = GRAPHEME_JOIN_RULES.get_unchecked(state as usize);\n (s[l] >> (t * 2)) & 3\n }\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_joins_done(state: u32) -> bool {\n state == 3\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_character_width(val: usize, ambiguous_width: usize) -> usize {\n let mut w = val >> 11;\n if w > 2 {\n cold_path();\n w = ambiguous_width;\n }\n w\n}\n#[inline(always)]\npub fn ucd_line_break_joins(lead: usize, trail: usize) -> bool {\n unsafe {\n let l = (lead >> 6) & 31;\n let t = (trail >> 6) & 31;\n let s = *LINE_BREAK_JOIN_RULES.get_unchecked(l);\n ((s >> t) & 1) != 0\n }\n}\n#[inline(always)]\npub fn ucd_start_of_text_properties() -> usize {\n 0x603\n}\n#[inline(always)]\npub fn ucd_tab_properties() -> usize {\n 0x963\n}\n#[inline(always)]\npub fn ucd_linefeed_properties() -> usize {\n 0x802\n}\n#[cold]\n#[inline(always)]\nfn cold_path() {}\n// END: Generated by grapheme-table-gen\n"], ["/edit/src/cell.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! [`std::cell::RefCell`], but without runtime checks in release builds.\n\n#[cfg(debug_assertions)]\npub use debug::*;\n#[cfg(not(debug_assertions))]\npub use release::*;\n\n#[allow(unused)]\n#[cfg(debug_assertions)]\nmod debug {\n pub type SemiRefCell = std::cell::RefCell;\n pub type Ref<'b, T> = std::cell::Ref<'b, T>;\n pub type RefMut<'b, T> = std::cell::RefMut<'b, T>;\n}\n\n#[cfg(not(debug_assertions))]\nmod release {\n #[derive(Default)]\n #[repr(transparent)]\n pub struct SemiRefCell(std::cell::UnsafeCell);\n\n impl SemiRefCell {\n #[inline(always)]\n pub const fn new(value: T) -> Self {\n Self(std::cell::UnsafeCell::new(value))\n }\n\n #[inline(always)]\n pub const fn as_ptr(&self) -> *mut T {\n self.0.get()\n }\n\n #[inline(always)]\n pub const fn borrow(&self) -> Ref<'_, T> {\n Ref(unsafe { &*self.0.get() })\n }\n\n #[inline(always)]\n pub const fn borrow_mut(&self) -> RefMut<'_, T> {\n RefMut(unsafe { &mut *self.0.get() })\n }\n }\n\n #[repr(transparent)]\n pub struct Ref<'b, T>(&'b T);\n\n impl<'b, T> Ref<'b, T> {\n #[inline(always)]\n pub fn clone(orig: &Self) -> Self {\n Ref(orig.0)\n }\n }\n\n impl<'b, T> std::ops::Deref for Ref<'b, T> {\n type Target = T;\n\n #[inline(always)]\n fn deref(&self) -> &Self::Target {\n self.0\n }\n }\n\n #[repr(transparent)]\n pub struct RefMut<'b, T>(&'b mut T);\n\n impl<'b, T> std::ops::Deref for RefMut<'b, T> {\n type Target = T;\n\n #[inline(always)]\n fn deref(&self) -> &Self::Target {\n self.0\n }\n }\n\n impl<'b, T> std::ops::DerefMut for RefMut<'b, T> {\n #[inline(always)]\n fn deref_mut(&mut self) -> &mut Self::Target {\n self.0\n }\n }\n}\n"], ["/edit/src/apperr.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides a transparent error type for edit.\n\nuse std::{io, result};\n\nuse crate::sys;\n\npub const APP_ICU_MISSING: Error = Error::new_app(0);\n\n/// Edit's transparent `Result` type.\npub type Result = result::Result;\n\n/// Edit's transparent `Error` type.\n/// Abstracts over system and application errors.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum Error {\n App(u32),\n Icu(u32),\n Sys(u32),\n}\n\nimpl Error {\n pub const fn new_app(code: u32) -> Self {\n Self::App(code)\n }\n\n pub const fn new_icu(code: u32) -> Self {\n Self::Icu(code)\n }\n\n pub const fn new_sys(code: u32) -> Self {\n Self::Sys(code)\n }\n}\n\nimpl From for Error {\n fn from(err: io::Error) -> Self {\n sys::io_error_to_apperr(err)\n }\n}\n"], ["/edit/src/arena/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Arena allocators. Small and fast.\n\n#[cfg(debug_assertions)]\nmod debug;\nmod release;\nmod scratch;\nmod string;\n\n#[cfg(all(not(doc), debug_assertions))]\npub use self::debug::Arena;\n#[cfg(any(doc, not(debug_assertions)))]\npub use self::release::Arena;\npub use self::scratch::{ScratchArena, init, scratch_arena};\npub use self::string::ArenaString;\n"], ["/edit/src/unicode/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Everything related to Unicode lives here.\n\nmod measurement;\nmod tables;\nmod utf8;\n\npub use measurement::*;\npub use utf8::*;\n"], ["/edit/src/sys/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Platform abstractions.\n\n#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n\n#[cfg(not(windows))]\npub use std::fs::canonicalize;\n\n#[cfg(unix)]\npub use unix::*;\n#[cfg(windows)]\npub use windows::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:51:55", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Trace back through the scoring matrix to identify optimal character match positions and reverse their order to produce sequential alignment indices."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n if scores[area - 1] == NO_MATCH {\n return (NO_MATCH, positions); // No matches found\n }\n\n let mut query_index = query.len() as isize - 1;\n let mut target_index = target.len() as isize - 1;\n\n while query_index >= 0 && target_index >= 0 && (positions.len() < query.len()) {\n let current_index = (query_index as usize) * target.len() + (target_index as usize);\n let left_score = if target_index > 0 {\n scores[current_index - 1]\n } else {\n 0\n };\n\n if scores[current_index] > left_score {\n positions.push(target_index as usize);\n query_index -= 1;\n target_index -= 1;\n } else {\n target_index -= 1;\n }\n }\n\n positions.reverse();\n[TASK_END]\n```", "inference_time": "2025-08-21 01-53-09"}, "editdistance_info": {"edit_distance": 37.9888, "calculate_time": "2025-08-21 01:53:09", "true_code_clean": "if !query.is_empty() && !target.is_empty() {\n let mut query_index = query.len() - 1;\n let mut target_index = target.len() - 1;\n loop {\n let current_index = query_index * target.len() + target_index;\n if matches[current_index] == NO_MATCH {\n if target_index == 0 {\n break;\n }\n target_index -= 1; \n } else {\n positions.push(target_index);\n if query_index == 0 || target_index == 0 {\n break;\n }\n query_index -= 1;\n target_index -= 1;\n }\n }\n positions.reverse();\n }", "predict_code_clean": "if scores[area - 1] == NO_MATCH {\n return (NO_MATCH, positions); \n }\n let mut query_index = query.len() as isize - 1;\n let mut target_index = target.len() as isize - 1;\n while query_index >= 0 && target_index >= 0 && (positions.len() < query.len()) {\n let current_index = (query_index as usize) * target.len() + (target_index as usize);\n let left_score = if target_index > 0 {\n scores[current_index - 1]\n } else {\n 0\n };\n if scores[current_index] > left_score {\n positions.push(target_index as usize);\n query_index -= 1;\n target_index -= 1;\n } else {\n target_index -= 1;\n }\n }\n positions.reverse();"}} {"repo_name": "edit", "file_name": "/edit/src/icu.rs", "inference_info": {"prefix_code": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Bindings to the ICU library.\n\nuse std::cmp::Ordering;\nuse std::ffi::{CStr, c_char};\nuse std::mem;\nuse std::mem::MaybeUninit;\nuse std::ops::Range;\nuse std::ptr::{null, null_mut};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::buffer::TextBuffer;\nuse crate::unicode::Utf8Chars;\nuse crate::{apperr, arena_format, sys};\n\n#[derive(Clone, Copy)]\npub struct Encoding {\n pub label: &'static str,\n pub canonical: &'static str,\n}\n\npub struct Encodings {\n pub preferred: &'static [Encoding],\n pub all: &'static [Encoding],\n}\n\nstatic mut ENCODINGS: Encodings = Encodings { preferred: &[], all: &[] };\n\n/// Returns a list of encodings ICU supports.\npub fn get_available_encodings() -> &'static Encodings {\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n unsafe {\n if ENCODINGS.all.is_empty() {\n let scratch = scratch_arena(None);\n let mut preferred = Vec::new_in(&*scratch);\n let mut alternative = Vec::new_in(&*scratch);\n\n // These encodings are always available.\n preferred.push(Encoding { label: \"UTF-8\", canonical: \"UTF-8\" });\n preferred.push(Encoding { label: \"UTF-8 BOM\", canonical: \"UTF-8 BOM\" });\n\n if let Ok(f) = init_if_needed() {\n let mut n = 0;\n loop {\n let name = (f.ucnv_getAvailableName)(n);\n if name.is_null() {\n break;\n }\n\n n += 1;\n\n let name = CStr::from_ptr(name).to_str().unwrap_unchecked();\n // We have already pushed UTF-8 above and can skip it.\n // There is no need to filter UTF-8 BOM here,\n // since ICU does not distinguish it from UTF-8.\n if name.is_empty() || name == \"UTF-8\" {\n continue;\n }\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let mime = (f.ucnv_getStandardName)(\n name.as_ptr(),\n c\"MIME\".as_ptr() as *const _,\n &mut status,\n );\n if !mime.is_null() && status.is_success() {\n let mime = CStr::from_ptr(mime).to_str().unwrap_unchecked();\n preferred.push(Encoding { label: mime, canonical: name });\n } else {\n alternative.push(Encoding { label: name, canonical: name });\n }\n }\n }\n\n let preferred_len = preferred.len();\n\n // Combine the preferred and alternative encodings into a single list.\n let mut all = Vec::with_capacity(preferred.len() + alternative.len());\n all.extend(preferred);\n all.extend(alternative);\n\n let all = all.leak();\n ENCODINGS.preferred = &all[..preferred_len];\n ENCODINGS.all = &all[..];\n }\n\n &ENCODINGS\n }\n}\n\n/// Formats the given ICU error code into a human-readable string.\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n fn format(code: u32) -> &'static str {\n let Ok(f) = init_if_needed() else {\n return \"\";\n };\n\n let status = icu_ffi::UErrorCode::new(code);\n let ptr = unsafe { (f.u_errorName)(status) };\n if ptr.is_null() {\n return \"\";\n }\n\n let str = unsafe { CStr::from_ptr(ptr) };\n str.to_str().unwrap_or(\"\")\n }\n\n let msg = format(code);\n if !msg.is_empty() {\n write!(f, \"ICU Error: {msg}\")\n } else {\n write!(f, \"ICU Error: {code:#08x}\")\n }\n}\n\n/// Converts between two encodings using ICU.\npub struct Converter<'pivot> {\n source: *mut icu_ffi::UConverter,\n target: *mut icu_ffi::UConverter,\n pivot_buffer: &'pivot mut [MaybeUninit],\n pivot_source: *mut u16,\n pivot_target: *mut u16,\n reset: bool,\n}\n\nimpl Drop for Converter<'_> {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.ucnv_close)(self.source) };\n unsafe { (f.ucnv_close)(self.target) };\n }\n}\n\nimpl<'pivot> Converter<'pivot> {\n /// Constructs a new `Converter` instance.\n ///\n /// # Parameters\n ///\n /// * `pivot_buffer`: A buffer used to cache partial conversions.\n /// Don't make it too small.\n /// * `source_encoding`: The source encoding name (e.g., \"UTF-8\").\n /// * `target_encoding`: The target encoding name (e.g., \"UTF-16\").\n pub fn new(\n pivot_buffer: &'pivot mut [MaybeUninit],\n source_encoding: &str,\n target_encoding: &str,\n ) -> apperr::Result {\n let f = init_if_needed()?;\n\n let arena = scratch_arena(None);\n let source_encoding = Self::append_nul(&arena, source_encoding);\n let target_encoding = Self::append_nul(&arena, target_encoding);\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let source = unsafe { (f.ucnv_open)(source_encoding.as_ptr(), &mut status) };\n let target = unsafe { (f.ucnv_open)(target_encoding.as_ptr(), &mut status) };\n if status.is_failure() {\n if !source.is_null() {\n unsafe { (f.ucnv_close)(source) };\n }\n if !target.is_null() {\n unsafe { (f.ucnv_close)(target) };\n }\n return Err(status.as_error());\n }\n\n let pivot_source = pivot_buffer.as_mut_ptr() as *mut u16;\n let pivot_target = unsafe { pivot_source.add(pivot_buffer.len()) };\n\n Ok(Self { source, target, pivot_buffer, pivot_source, pivot_target, reset: true })\n }\n\n fn append_nul<'a>(arena: &'a Arena, input: &str) -> ArenaString<'a> {\n arena_format!(arena, \"{}\\0\", input)\n }\n\n /// Performs one step of the encoding conversion.\n ///\n /// # Parameters\n ///\n /// * `input`: The input buffer to convert from.\n /// It should be in the `source_encoding` that was previously specified.\n /// * `output`: The output buffer to convert to.\n /// It should be in the `target_encoding` that was previously specified.\n ///\n /// # Returns\n ///\n /// A tuple containing:\n /// 1. The number of bytes read from the input buffer.\n /// 2. The number of bytes written to the output buffer.\n pub fn convert(\n &mut self,\n input: &[u8],\n output: &mut [MaybeUninit],\n ) -> apperr::Result<(usize, usize)> {\n let f = assume_loaded();\n\n let input_beg = input.as_ptr();\n let input_end = unsafe { input_beg.add(input.len()) };\n let mut input_ptr = input_beg;\n\n let output_beg = output.as_mut_ptr() as *mut u8;\n let output_end = unsafe { output_beg.add(output.len()) };\n let mut output_ptr = output_beg;\n\n let pivot_beg = self.pivot_buffer.as_mut_ptr() as *mut u16;\n let pivot_end = unsafe { pivot_beg.add(self.pivot_buffer.len()) };\n\n let flush = input.is_empty();\n let mut status = icu_ffi::U_ZERO_ERROR;\n\n unsafe {\n (f.ucnv_convertEx)(\n /* target_cnv */ self.target,\n /* source_cnv */ self.source,\n /* target */ &mut output_ptr,\n /* target_limit */ output_end,\n /* source */ &mut input_ptr,\n /* source_limit */ input_end,\n /* pivot_start */ pivot_beg,\n /* pivot_source */ &mut self.pivot_source,\n /* pivot_target */ &mut self.pivot_target,\n /* pivot_limit */ pivot_end,\n /* reset */ self.reset,\n /* flush */ flush,\n /* status */ &mut status,\n );\n }\n\n self.reset = false;\n if status.is_failure() && status != icu_ffi::U_BUFFER_OVERFLOW_ERROR {\n return Err(status.as_error());\n }\n\n let input_advance = unsafe { input_ptr.offset_from(input_beg) as usize };\n let output_advance = unsafe { output_ptr.offset_from(output_beg) as usize };\n Ok((input_advance, output_advance))\n }\n}\n\n// In benchmarking, I found that the performance does not really change much by changing this value.\n// I picked 64 because it seemed like a reasonable lower bound.\nconst CACHE_SIZE: usize = 64;\n\n/// Caches a chunk of TextBuffer contents (UTF-8) in UTF-16 format.\n#[repr(C)]\nstruct Cache {\n /// The translated text. Contains [`Cache::utf16_len`]-many valid items.\n utf16: [u16; CACHE_SIZE],\n /// For each character in [`Cache::utf16`] this stores the offset in the [`TextBuffer`],\n /// relative to the start offset stored in `native_beg`.\n /// This has the same length as [`Cache::utf16`].\n utf16_to_utf8_offsets: [u16; CACHE_SIZE],\n /// `utf8_to_utf16_offsets[native_offset - native_beg]` will tell you which character in\n /// [`Cache::utf16`] maps to the given `native_offset` in the underlying [`TextBuffer`].\n /// Contains `native_end - native_beg`-many valid items.\n utf8_to_utf16_offsets: [u16; CACHE_SIZE],\n\n /// The number of valid items in [`Cache::utf16`].\n utf16_len: usize,\n /// Offset of the first non-ASCII character.\n /// Less than or equal to [`Cache::utf16_len`].\n native_indexing_limit: usize,\n\n /// The range of UTF-8 text in the [`TextBuffer`] that this chunk covers.\n utf8_range: Range,\n}\n\n#[repr(C)]\nstruct DoubleCache {\n cache: [Cache; 2],\n /// You can consider this a 1 bit index into `cache`.\n mru: bool,\n}\n\n/// A wrapper around ICU's `UText` struct.\n///\n/// In our case its only purpose is to adapt a [`TextBuffer`] for ICU.\n///\n/// # Safety\n///\n/// Warning! No lifetime tracking is done here.\n/// I initially did it properly with a PhantomData marker for the TextBuffer\n/// lifetime, but it was a pain so now I don't. Not a big deal in our case.\npub struct Text(&'static mut icu_ffi::UText);\n\nimpl Drop for Text {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.utext_close)(self.0) };\n }\n}\n\nimpl Text {\n /// Constructs an ICU `UText` instance from a [`TextBuffer`].\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given [`TextBuffer`]\n /// outlives the returned `Text` instance.\n pub unsafe fn new(tb: &TextBuffer) -> apperr::Result {\n let f = init_if_needed()?;\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let ptr =\n unsafe { (f.utext_setup)(null_mut(), size_of::() as i32, &mut status) };\n if status.is_failure() {\n return Err(status.as_error());\n }\n\n const FUNCS: icu_ffi::UTextFuncs = icu_ffi::UTextFuncs {\n table_size: size_of::() as i32,\n reserved1: 0,\n reserved2: 0,\n reserved3: 0,\n clone: Some(utext_clone),\n native_length: Some(utext_native_length),\n access: Some(utext_access),\n extract: None,\n replace: None,\n copy: None,\n map_offset_to_native: Some(utext_map_offset_to_native),\n map_native_index_to_utf16: Some(utext_map_native_index_to_utf16),\n close: None,\n spare1: None,\n spare2: None,\n spare3: None,\n };\n\n let ut = unsafe { &mut *ptr };\n ut.p_funcs = &FUNCS;\n ut.context = tb as *const TextBuffer as *mut _;\n ut.a = -1;\n\n Ok(Self(ut))\n }\n}\n\nfn text_buffer_from_utext<'a>(ut: &icu_ffi::UText) -> &'a TextBuffer {\n unsafe { &*(ut.context as *const TextBuffer) }\n}\n\nfn double_cache_from_utext<'a>(ut: &icu_ffi::UText) -> &'a mut DoubleCache {\n unsafe { &mut *(ut.p_extra as *mut DoubleCache) }\n}\n\nextern \"C\" fn utext_clone(\n dest: *mut icu_ffi::UText,\n src: &icu_ffi::UText,\n deep: bool,\n status: &mut icu_ffi::UErrorCode,\n) -> *mut icu_ffi::UText {\n if status.is_failure() {\n return null_mut();\n }\n\n if deep {\n *status = icu_ffi::U_UNSUPPORTED_ERROR;\n return null_mut();\n }\n\n let f = assume_loaded();\n let ut_ptr = unsafe { (f.utext_setup)(dest, size_of::() as i32, status) };\n if status.is_failure() {\n return null_mut();\n }\n\n // TODO: I'm somewhat unsure whether we have to preserve the `chunk_offset`.\n // We can't blindly copy chunk contents and the `Cache` in `ut.p_extra`,\n // because they may contain dirty contents (different `TextBuffer` generation).\n unsafe {\n let ut = &mut *ut_ptr;\n ut.p_funcs = src.p_funcs;\n ut.context = src.context;\n ut.a = -1;\n }\n\n ut_ptr\n}\n\nextern \"C\" fn utext_native_length(ut: &mut icu_ffi::UText) -> i64 {\n let tb = text_buffer_from_utext(ut);\n tb.text_length() as i64\n}\n\nextern \"C\" fn utext_access(ut: &mut icu_ffi::UText, native_index: i64, forward: bool) -> bool {\n if let Some(cache) = utext_access_impl(ut, native_index, forward) {\n let native_off = native_index as usize - cache.utf8_range.start;\n ut.chunk_contents = cache.utf16.as_ptr();\n ut.chunk_length = cache.utf16_len as i32;\n ut.chunk_offset = cache.utf8_to_utf16_offsets[native_off] as i32;\n ut.chunk_native_start = cache.utf8_range.start as i64;\n ut.chunk_native_limit = cache.utf8_range.end as i64;\n ut.native_indexing_limit = cache.native_indexing_limit as i32;\n true\n } else {\n false\n }\n}\n\nfn utext_access_impl<'a>(\n ut: &mut icu_ffi::UText,\n native_index: i64,\n forward: bool,\n) -> Option<&'a mut Cache> {\n let tb = text_buffer_from_utext(ut);\n let mut index_contained = native_index;\n\n if !forward {\n index_contained -= 1;\n }\n if index_contained < 0 || index_contained as usize >= tb.text_length() {\n return None;\n }\n\n let index_contained = index_contained as usize;\n let native_index = native_index as usize;\n let double_cache = double_cache_from_utext(ut);\n let dirty = ut.a != tb.generation() as i64;\n\n if dirty {\n // The text buffer contents have changed.\n // Invalidate both caches so that future calls don't mistakenly use them\n // when they enter the for loop in the else branch below (`dirty == false`).\n double_cache.cache[0].utf16_len = 0;\n double_cache.cache[1].utf16_len = 0;\n double_cache.cache[0].utf8_range = 0..0;\n double_cache.cache[1].utf8_range = 0..0;\n ut.a = tb.generation() as i64;\n } else {\n // Check if one of the caches already contains the requested range.\n for (i, cache) in double_cache.cache.iter_mut().enumerate() {\n if cache.utf8_range.contains(&index_contained) {\n double_cache.mru = i != 0;\n return Some(cache);\n }\n }\n }\n\n // Turn the least recently used cache into the most recently used one.\n let double_cache = double_cache_from_utext(ut);\n double_cache.mru = !double_cache.mru;\n let cache = &mut double_cache.cache[double_cache.mru as usize];\n\n // In order to safely fit any UTF-8 character into our cache,\n // we must assume the worst case of a 4-byte long encoding.\n const UTF16_LEN_LIMIT: usize = CACHE_SIZE - 4;\n let utf8_len_limit;\n let native_start;\n\n if forward {\n utf8_len_limit = (tb.text_length() - native_index).min(UTF16_LEN_LIMIT);\n native_start = native_index;\n } else {\n // The worst case ratio for UTF-8 to UTF-16 is 1:1, when the text is ASCII.\n // This allows us to safely subtract the UTF-16 buffer size\n // and assume that whatever we read as UTF-8 will fit.\n // TODO: Test what happens if you have lots of invalid UTF-8 text blow up to U+FFFD.\n utf8_len_limit = native_index.min(UTF16_LEN_LIMIT);\n\n // Since simply subtracting an offset may end up in the middle of a codepoint sequence,\n // we must align the offset to the next codepoint boundary.\n // Here we skip trail bytes until we find a lead.\n let mut beg = native_index - utf8_len_limit;\n let chunk = tb.read_forward(beg);\n for &c in chunk {\n if c & 0b1100_0000 != 0b1000_0000 {\n break;\n }\n beg += 1;\n }\n\n native_start = beg;\n }\n\n // Translate the given range from UTF-8 to UTF-16.\n // NOTE: This code makes the assumption that the `native_index` is always\n // at UTF-8 codepoint boundaries which technically isn't guaranteed.\n let mut utf16_len = 0;\n let mut utf8_len = 0;\n let mut ascii_len = 0;\n 'outer: loop {\n let initial_utf8_len = utf8_len;\n let chunk = tb.read_forward(native_start + utf8_len);\n if chunk.is_empty() {\n break;\n }\n\n let mut it = Utf8Chars::new(chunk, 0);\n\n // If we've only seen ASCII so far we can fast-pass the UTF-16 translation,\n // because we can just widen from u8 -> u16.\n if utf16_len == ascii_len {\n let haystack = &chunk[..chunk.len().min(utf8_len_limit - ascii_len)];\n\n // When it comes to performance, and the search space is small (which it is here),\n // it's always a good idea to keep the loops small and tight...\n let len = haystack.iter().position(|&c| c >= 0x80).unwrap_or(haystack.len());\n\n // ...In this case it allows the compiler to vectorize this loop and double\n // the performance. Luckily, llvm doesn't unroll the loop, which is great,\n // because `len` will always be a relatively small number.\n for &c in &chunk[..len] {\n unsafe {\n *cache.utf16.get_unchecked_mut(ascii_len) = c as u16;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(ascii_len) = ascii_len as u16;\n *cache.utf8_to_utf16_offsets.get_unchecked_mut(ascii_len) = ascii_len as u16;\n }\n ascii_len += 1;\n }\n\n utf16_len += len;\n utf8_len += len;\n it.seek(len);\n if ascii_len >= UTF16_LEN_LIMIT {\n break;\n }\n }\n\n loop {\n let Some(c) = it.next() else {\n break;\n };\n\n // Thanks to our `if utf16_len >= UTF16_LEN_LIMIT` check,\n // we can safely assume that this will fit.\n unsafe {\n let utf8_len_beg = utf8_len;\n let utf8_len_end = initial_utf8_len + it.offset();\n\n while utf8_len < utf8_len_end {\n *cache.utf8_to_utf16_offsets.get_unchecked_mut(utf8_len) = utf16_len as u16;\n utf8_len += 1;\n }\n\n if c <= '\\u{FFFF}' {\n *cache.utf16.get_unchecked_mut(utf16_len) = c as u16;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len) = utf8_len_beg as u16;\n utf16_len += 1;\n } else {\n let c = c as u32 - 0x10000;\n let b = utf8_len_beg as u16;\n *cache.utf16.get_unchecked_mut(utf16_len) = (c >> 10) as u16 | 0xD800;\n *cache.utf16.get_unchecked_mut(utf16_len + 1) = (c & 0x3FF) as u16 | 0xDC00;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len) = b;\n *cache.utf16_to_utf8_offsets.get_unchecked_mut(utf16_len + 1) = b;\n utf16_len += 2;\n }\n }\n\n if utf16_len >= UTF16_LEN_LIMIT || utf8_len >= utf8_len_limit {\n break 'outer;\n }\n }\n }\n\n // Allow for looking up past-the-end indices via\n // `utext_map_offset_to_native` and `utext_map_native_index_to_utf16`.\n cache.utf16_to_utf8_offsets[utf16_len] = utf8_len as u16;\n cache.utf8_to_utf16_offsets[utf8_len] = utf16_len as u16;\n\n let native_limit = native_start + utf8_len;\n cache.utf16_len = utf16_len;\n // If parts of the UTF-8 chunk are ASCII, we can tell ICU that it doesn't need to call\n // utext_map_offset_to_native. For some reason, uregex calls that function *a lot*,\n // literally half the CPU time is spent on it.\n cache.native_indexing_limit = ascii_len;\n cache.utf8_range = native_start..native_limit;\n Some(cache)\n}\n\nextern \"C\" fn utext_map_offset_to_native(ut: &icu_ffi::UText) -> i64 {\n debug_assert!((0..=ut.chunk_length).contains(&ut.chunk_offset));\n\n let double_cache = double_cache_from_utext(ut);\n let cache = &double_cache.cache[double_cache.mru as usize];\n let off_rel = cache.utf16_to_utf8_offsets[ut.chunk_offset as usize];\n let off_abs = cache.utf8_range.start + off_rel as usize;\n off_abs as i64\n}\n\nextern \"C\" fn utext_map_native_index_to_utf16(ut: &icu_ffi::UText, native_index: i64) -> i32 {\n debug_assert!((ut.chunk_native_start..=ut.chunk_native_limit).contains(&native_index));\n\n let double_cache = double_cache_from_utext(ut);\n let cache = &double_cache.cache[double_cache.mru as usize];\n let off_rel = cache.utf8_to_utf16_offsets[(native_index - ut.chunk_native_start) as usize];\n off_rel as i32\n}\n\n/// A wrapper around ICU's `URegularExpression` struct.\n///\n/// # Safety\n///\n/// Warning! No lifetime tracking is done here.\npub struct Regex(&'static mut icu_ffi::URegularExpression);\n\nimpl Drop for Regex {\n fn drop(&mut self) {\n let f = assume_loaded();\n unsafe { (f.uregex_close)(self.0) };\n }\n}\n\nimpl Regex {\n /// Enable case-insensitive matching.\n pub const CASE_INSENSITIVE: i32 = icu_ffi::UREGEX_CASE_INSENSITIVE;\n\n /// If set, ^ and $ match the start and end of each line.\n /// Otherwise, they match the start and end of the entire string.\n pub const MULTILINE: i32 = icu_ffi::UREGEX_MULTILINE;\n\n /// Treat the given pattern as a literal string.\n pub const LITERAL: i32 = icu_ffi::UREGEX_LITERAL;\n\n /// Constructs a regex, plain and simple. Read `uregex_open` docs.\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given `Text` outlives the returned `Regex` instance.\n pub unsafe fn new(pattern: &str, flags: i32, text: &Text) -> apperr::Result {\n let f = init_if_needed()?;\n unsafe {\n let scratch = scratch_arena(None);\n let mut utf16 = Vec::new_in(&*scratch);\n let mut status = icu_ffi::U_ZERO_ERROR;\n\n utf16.extend(pattern.encode_utf16());\n\n let ptr = (f.uregex_open)(\n utf16.as_ptr(),\n utf16.len() as i32,\n icu_ffi::UREGEX_MULTILINE | icu_ffi::UREGEX_ERROR_ON_UNKNOWN_ESCAPES | flags,\n None,\n &mut status,\n );\n // ICU describes the time unit as being dependent on CPU performance\n // and \"typically [in] the order of milliseconds\", but this claim seems\n // highly outdated. On my CPU from 2021, a limit of 4096 equals roughly 600ms.\n (f.uregex_setTimeLimit)(ptr, 4096, &mut status);\n (f.uregex_setUText)(ptr, text.0 as *const _ as *mut _, &mut status);\n if status.is_failure() {\n return Err(status.as_error());\n }\n\n Ok(Self(&mut *ptr))\n }\n }\n\n /// Updates the regex pattern with the given text.\n /// If the text contents have changed, you can pass the same text as you used\n /// initially and it'll trigger ICU to reload the text and invalidate its caches.\n ///\n /// # Safety\n ///\n /// The caller must ensure that the given `Text` outlives the `Regex` instance.\n pub unsafe fn set_text(&mut self, text: &mut Text, offset: usize) {\n // Get `utext_access_impl` to detect the `TextBuffer::generation` change,\n // and refresh its contents. This ensures that ICU doesn't reuse\n // stale `UText::chunk_contents`, as it has no way tell that it's stale.\n utext_access(text.0, offset as i64, true);\n\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n unsafe { (f.uregex_setUText)(self.0, text.0 as *const _ as *mut _, &mut status) };\n // `uregex_setUText` resets the regex to the start of the text.\n // Because of this, we must also call `uregex_reset64`.\n unsafe { (f.uregex_reset64)(self.0, offset as i64, &mut status) };\n }\n\n /// Sets the regex to the absolute offset in the underlying text.\n pub fn reset(&mut self, offset: usize) {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n unsafe { (f.uregex_reset64)(self.0, offset as i64, &mut status) };\n }\n\n /// Gets captured group count.\n pub fn group_count(&mut self) -> i32 {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let count = unsafe { (f.uregex_groupCount)(self.0, &mut status) };\n if status.is_failure() { 0 } else { count }\n }\n\n /// Gets the text range of a captured group by index.\n pub fn group(&mut self, group: i32) -> Option> {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let start = unsafe { (f.uregex_start64)(self.0, group, &mut status) };\n let end = unsafe { (f.uregex_end64)(self.0, group, &mut status) };\n if status.is_failure() {\n None\n } else {\n let start = start.max(0);\n let end = end.max(start);\n Some(start as usize..end as usize)\n }\n }\n}\n\nimpl Iterator for Regex {\n type Item = Range;\n\n fn next(&mut self) -> Option {\n let f = assume_loaded();\n\n let mut status = icu_ffi::U_ZERO_ERROR;\n let ok = unsafe { (f.uregex_findNext)(self.0, &mut status) };\n if !ok {\n return None;\n }\n\n self.group(0)\n }\n}\n\nstatic mut ROOT_COLLATOR: Option<*mut icu_ffi::UCollator> = None;\n\n/// Compares two UTF-8 strings for sorting using ICU's collation algorithm.\npub fn compare_strings(a: &[u8], b: &[u8]) -> Ordering {\n #[cold]\n fn init() {\n unsafe {\n let mut coll = null_mut();\n\n if let Ok(f) = init_if_needed() {\n let mut status = icu_ffi::U_ZERO_ERROR;\n coll = (f.ucol_open)(c\"\".as_ptr(), &mut status);\n }\n\n ROOT_COLLATOR = Some(coll);\n }\n }\n\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n let coll = unsafe {\n if ROOT_COLLATOR.is_none() {\n init();\n }\n ROOT_COLLATOR.unwrap_unchecked()\n };\n\n if coll.is_null() {\n compare_strings_ascii(a, b)\n } else {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n let res = unsafe {\n (f.ucol_strcollUTF8)(\n coll,\n a.as_ptr(),\n a.len() as i32,\n b.as_ptr(),\n b.len() as i32,\n &mut status,\n )\n };\n\n match res {\n icu_ffi::UCollationResult::UCOL_EQUAL => Ordering::Equal,\n icu_ffi::UCollationResult::UCOL_GREATER => Ordering::Greater,\n icu_ffi::UCollationResult::UCOL_LESS => Ordering::Less,\n }\n }\n}\n\n/// Unicode collation via `ucol_strcollUTF8`, now for ASCII!\nfn compare_strings_ascii(a: &[u8], b: &[u8]) -> Ordering {\n let mut iter = a.iter().zip(b.iter());\n\n // Low weight: Find the first character which differs.\n //\n // Remember that result in case all remaining characters are\n // case-insensitive equal, because then we use that as a fallback.\n ", "suffix_code": "\n\n // Fallback: The shorter string wins.\n a.len().cmp(&b.len())\n}\n\nstatic mut ROOT_CASEMAP: Option<*mut icu_ffi::UCaseMap> = None;\n\n/// Converts the given UTF-8 string to lower case.\n///\n/// Case folding differs from lower case in that the output is primarily useful\n/// to machines for comparisons. It's like applying Unicode normalization.\npub fn fold_case<'a>(arena: &'a Arena, input: &str) -> ArenaString<'a> {\n // OnceCell for people that want to put it into a static.\n #[allow(static_mut_refs)]\n let casemap = unsafe {\n if ROOT_CASEMAP.is_none() {\n ROOT_CASEMAP = Some(if let Ok(f) = init_if_needed() {\n let mut status = icu_ffi::U_ZERO_ERROR;\n (f.ucasemap_open)(null(), 0, &mut status)\n } else {\n null_mut()\n })\n }\n ROOT_CASEMAP.unwrap_unchecked()\n };\n\n if !casemap.is_null() {\n let f = assume_loaded();\n let mut status = icu_ffi::U_ZERO_ERROR;\n let mut output = Vec::new_in(arena);\n let mut output_len;\n\n // First, guess the output length:\n // TODO: What's a good heuristic here?\n {\n output.reserve_exact(input.len() + 16);\n let output = output.spare_capacity_mut();\n output_len = unsafe {\n (f.ucasemap_utf8FoldCase)(\n casemap,\n output.as_mut_ptr() as *mut _,\n output.len() as i32,\n input.as_ptr() as *const _,\n input.len() as i32,\n &mut status,\n )\n };\n }\n\n // If that failed to fit, retry with the correct length.\n if status == icu_ffi::U_BUFFER_OVERFLOW_ERROR && output_len > 0 {\n output.reserve_exact(output_len as usize);\n let output = output.spare_capacity_mut();\n output_len = unsafe {\n (f.ucasemap_utf8FoldCase)(\n casemap,\n output.as_mut_ptr() as *mut _,\n output.len() as i32,\n input.as_ptr() as *const _,\n input.len() as i32,\n &mut status,\n )\n };\n }\n\n if status.is_success() && output_len > 0 {\n unsafe {\n output.set_len(output_len as usize);\n }\n return unsafe { ArenaString::from_utf8_unchecked(output) };\n }\n }\n\n let mut result = ArenaString::from_str(arena, input);\n for b in unsafe { result.as_bytes_mut() } {\n b.make_ascii_lowercase();\n }\n result\n}\n\n// NOTE:\n// To keep this neat, fields are ordered by prefix (= `ucol_` before `uregex_`),\n// followed by functions in this order:\n// * Static methods (e.g. `ucnv_getAvailableName`)\n// * Constructors (e.g. `ucnv_open`)\n// * Destructors (e.g. `ucnv_close`)\n// * Methods, grouped by relationship\n// (e.g. `uregex_start64` and `uregex_end64` are near each other)\n//\n// WARNING:\n// The order of the fields MUST match the order of strings in the following two arrays.\n#[allow(non_snake_case)]\n#[repr(C)]\nstruct LibraryFunctions {\n // LIBICUUC_PROC_NAMES\n u_errorName: icu_ffi::u_errorName,\n ucasemap_open: icu_ffi::ucasemap_open,\n ucasemap_utf8FoldCase: icu_ffi::ucasemap_utf8FoldCase,\n ucnv_getAvailableName: icu_ffi::ucnv_getAvailableName,\n ucnv_getStandardName: icu_ffi::ucnv_getStandardName,\n ucnv_open: icu_ffi::ucnv_open,\n ucnv_close: icu_ffi::ucnv_close,\n ucnv_convertEx: icu_ffi::ucnv_convertEx,\n utext_setup: icu_ffi::utext_setup,\n utext_close: icu_ffi::utext_close,\n\n // LIBICUI18N_PROC_NAMES\n ucol_open: icu_ffi::ucol_open,\n ucol_strcollUTF8: icu_ffi::ucol_strcollUTF8,\n uregex_open: icu_ffi::uregex_open,\n uregex_close: icu_ffi::uregex_close,\n uregex_setTimeLimit: icu_ffi::uregex_setTimeLimit,\n uregex_setUText: icu_ffi::uregex_setUText,\n uregex_reset64: icu_ffi::uregex_reset64,\n uregex_findNext: icu_ffi::uregex_findNext,\n uregex_groupCount: icu_ffi::uregex_groupCount,\n uregex_start64: icu_ffi::uregex_start64,\n uregex_end64: icu_ffi::uregex_end64,\n}\n\nmacro_rules! proc_name {\n ($s:literal) => {\n concat!(env!(\"EDIT_CFG_ICU_EXPORT_PREFIX\"), $s, env!(\"EDIT_CFG_ICU_EXPORT_SUFFIX\"), \"\\0\")\n .as_ptr() as *const c_char\n };\n}\n\n// Found in libicuuc.so on UNIX, icuuc.dll/icu.dll on Windows.\nconst LIBICUUC_PROC_NAMES: [*const c_char; 10] = [\n proc_name!(\"u_errorName\"),\n proc_name!(\"ucasemap_open\"),\n proc_name!(\"ucasemap_utf8FoldCase\"),\n proc_name!(\"ucnv_getAvailableName\"),\n proc_name!(\"ucnv_getStandardName\"),\n proc_name!(\"ucnv_open\"),\n proc_name!(\"ucnv_close\"),\n proc_name!(\"ucnv_convertEx\"),\n proc_name!(\"utext_setup\"),\n proc_name!(\"utext_close\"),\n];\n\n// Found in libicui18n.so on UNIX, icuin.dll/icu.dll on Windows.\nconst LIBICUI18N_PROC_NAMES: [*const c_char; 11] = [\n proc_name!(\"ucol_open\"),\n proc_name!(\"ucol_strcollUTF8\"),\n proc_name!(\"uregex_open\"),\n proc_name!(\"uregex_close\"),\n proc_name!(\"uregex_setTimeLimit\"),\n proc_name!(\"uregex_setUText\"),\n proc_name!(\"uregex_reset64\"),\n proc_name!(\"uregex_findNext\"),\n proc_name!(\"uregex_groupCount\"),\n proc_name!(\"uregex_start64\"),\n proc_name!(\"uregex_end64\"),\n];\n\nenum LibraryFunctionsState {\n Uninitialized,\n Failed,\n Loaded(LibraryFunctions),\n}\n\nstatic mut LIBRARY_FUNCTIONS: LibraryFunctionsState = LibraryFunctionsState::Uninitialized;\n\npub fn init() -> apperr::Result<()> {\n init_if_needed()?;\n Ok(())\n}\n\n#[allow(static_mut_refs)]\nfn init_if_needed() -> apperr::Result<&'static LibraryFunctions> {\n #[cold]\n fn load() {\n unsafe {\n LIBRARY_FUNCTIONS = LibraryFunctionsState::Failed;\n\n let Ok(icu) = sys::load_icu() else {\n return;\n };\n\n type TransparentFunction = unsafe extern \"C\" fn() -> *const ();\n\n // OH NO I'M DOING A BAD THING\n //\n // If this assertion hits, you either forgot to update `LIBRARY_PROC_NAMES`\n // or you're on a platform where `dlsym` behaves different from classic UNIX and Windows.\n //\n // This code assumes that we can treat the `LibraryFunctions` struct containing various different function\n // pointers as an array of `TransparentFunction` pointers. In C, this works on any platform that supports\n // POSIX `dlsym` or equivalent, but I suspect Rust is once again being extra about it. In any case, that's\n // still better than loading every function one by one, just to blow up our binary size for no reason.\n const _: () = assert!(\n mem::size_of::()\n == mem::size_of::()\n * (LIBICUUC_PROC_NAMES.len() + LIBICUI18N_PROC_NAMES.len())\n );\n\n let mut funcs = MaybeUninit::::uninit();\n let mut ptr = funcs.as_mut_ptr() as *mut TransparentFunction;\n\n #[cfg(edit_icu_renaming_auto_detect)]\n let scratch_outer = scratch_arena(None);\n #[cfg(edit_icu_renaming_auto_detect)]\n let suffix = sys::icu_detect_renaming_suffix(&scratch_outer, icu.libicuuc);\n\n for (handle, names) in [\n (icu.libicuuc, &LIBICUUC_PROC_NAMES[..]),\n (icu.libicui18n, &LIBICUI18N_PROC_NAMES[..]),\n ] {\n for &name in names {\n #[cfg(edit_icu_renaming_auto_detect)]\n let scratch = scratch_arena(Some(&scratch_outer));\n #[cfg(edit_icu_renaming_auto_detect)]\n let name = sys::icu_add_renaming_suffix(&scratch, name, &suffix);\n\n let Ok(func) = sys::get_proc_address(handle, name) else {\n debug_assert!(\n false,\n \"Failed to load ICU function: {:?}\",\n CStr::from_ptr(name)\n );\n return;\n };\n\n ptr.write(func);\n ptr = ptr.add(1);\n }\n }\n\n LIBRARY_FUNCTIONS = LibraryFunctionsState::Loaded(funcs.assume_init());\n }\n }\n\n unsafe {\n if matches!(&LIBRARY_FUNCTIONS, LibraryFunctionsState::Uninitialized) {\n load();\n }\n }\n\n match unsafe { &LIBRARY_FUNCTIONS } {\n LibraryFunctionsState::Loaded(f) => Ok(f),\n _ => Err(apperr::APP_ICU_MISSING),\n }\n}\n\n#[allow(static_mut_refs)]\nfn assume_loaded() -> &'static LibraryFunctions {\n match unsafe { &LIBRARY_FUNCTIONS } {\n LibraryFunctionsState::Loaded(f) => f,\n _ => unreachable!(),\n }\n}\n\nmod icu_ffi {\n #![allow(dead_code, non_camel_case_types)]\n\n use std::ffi::{c_char, c_int, c_void};\n\n use crate::apperr;\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct UErrorCode(c_int);\n\n impl UErrorCode {\n pub const fn new(code: u32) -> Self {\n Self(code as c_int)\n }\n\n pub fn is_success(&self) -> bool {\n self.0 <= 0\n }\n\n pub fn is_failure(&self) -> bool {\n self.0 > 0\n }\n\n pub fn as_error(&self) -> apperr::Error {\n debug_assert!(self.0 > 0);\n apperr::Error::new_icu(self.0 as u32)\n }\n }\n\n pub const U_ZERO_ERROR: UErrorCode = UErrorCode(0);\n pub const U_BUFFER_OVERFLOW_ERROR: UErrorCode = UErrorCode(15);\n pub const U_UNSUPPORTED_ERROR: UErrorCode = UErrorCode(16);\n\n pub type u_errorName = unsafe extern \"C\" fn(code: UErrorCode) -> *const c_char;\n\n pub struct UConverter;\n\n pub type ucnv_getAvailableName = unsafe extern \"C\" fn(n: i32) -> *const c_char;\n\n pub type ucnv_getStandardName = unsafe extern \"C\" fn(\n name: *const u8,\n standard: *const u8,\n status: &mut UErrorCode,\n ) -> *const c_char;\n\n pub type ucnv_open =\n unsafe extern \"C\" fn(converter_name: *const u8, status: &mut UErrorCode) -> *mut UConverter;\n\n pub type ucnv_close = unsafe extern \"C\" fn(converter: *mut UConverter);\n\n pub type ucnv_convertEx = unsafe extern \"C\" fn(\n target_cnv: *mut UConverter,\n source_cnv: *mut UConverter,\n target: *mut *mut u8,\n target_limit: *const u8,\n source: *mut *const u8,\n source_limit: *const u8,\n pivot_start: *mut u16,\n pivot_source: *mut *mut u16,\n pivot_target: *mut *mut u16,\n pivot_limit: *const u16,\n reset: bool,\n flush: bool,\n status: &mut UErrorCode,\n );\n\n pub struct UCaseMap;\n\n pub type ucasemap_open = unsafe extern \"C\" fn(\n locale: *const c_char,\n options: u32,\n status: &mut UErrorCode,\n ) -> *mut UCaseMap;\n\n pub type ucasemap_utf8FoldCase = unsafe extern \"C\" fn(\n csm: *const UCaseMap,\n dest: *mut c_char,\n dest_capacity: i32,\n src: *const c_char,\n src_length: i32,\n status: &mut UErrorCode,\n ) -> i32;\n\n #[repr(C)]\n pub enum UCollationResult {\n UCOL_EQUAL = 0,\n UCOL_GREATER = 1,\n UCOL_LESS = -1,\n }\n\n #[repr(C)]\n pub struct UCollator;\n\n pub type ucol_open =\n unsafe extern \"C\" fn(loc: *const c_char, status: &mut UErrorCode) -> *mut UCollator;\n\n pub type ucol_strcollUTF8 = unsafe extern \"C\" fn(\n coll: *mut UCollator,\n source: *const u8,\n source_length: i32,\n target: *const u8,\n target_length: i32,\n status: &mut UErrorCode,\n ) -> UCollationResult;\n\n // UText callback functions\n pub type UTextClone = unsafe extern \"C\" fn(\n dest: *mut UText,\n src: &UText,\n deep: bool,\n status: &mut UErrorCode,\n ) -> *mut UText;\n pub type UTextNativeLength = unsafe extern \"C\" fn(ut: &mut UText) -> i64;\n pub type UTextAccess =\n unsafe extern \"C\" fn(ut: &mut UText, native_index: i64, forward: bool) -> bool;\n pub type UTextExtract = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n dest: *mut u16,\n dest_capacity: i32,\n status: &mut UErrorCode,\n ) -> i32;\n pub type UTextReplace = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n replacement_text: *const u16,\n replacement_length: i32,\n status: &mut UErrorCode,\n ) -> i32;\n pub type UTextCopy = unsafe extern \"C\" fn(\n ut: &mut UText,\n native_start: i64,\n native_limit: i64,\n native_dest: i64,\n move_text: bool,\n status: &mut UErrorCode,\n );\n pub type UTextMapOffsetToNative = unsafe extern \"C\" fn(ut: &UText) -> i64;\n pub type UTextMapNativeIndexToUTF16 =\n unsafe extern \"C\" fn(ut: &UText, native_index: i64) -> i32;\n pub type UTextClose = unsafe extern \"C\" fn(ut: &mut UText);\n\n #[repr(C)]\n pub struct UTextFuncs {\n pub table_size: i32,\n pub reserved1: i32,\n pub reserved2: i32,\n pub reserved3: i32,\n pub clone: Option,\n pub native_length: Option,\n pub access: Option,\n pub extract: Option,\n pub replace: Option,\n pub copy: Option,\n pub map_offset_to_native: Option,\n pub map_native_index_to_utf16: Option,\n pub close: Option,\n pub spare1: Option,\n pub spare2: Option,\n pub spare3: Option,\n }\n\n #[repr(C)]\n pub struct UText {\n pub magic: u32,\n pub flags: i32,\n pub provider_properties: i32,\n pub size_of_struct: i32,\n pub chunk_native_limit: i64,\n pub extra_size: i32,\n pub native_indexing_limit: i32,\n pub chunk_native_start: i64,\n pub chunk_offset: i32,\n pub chunk_length: i32,\n pub chunk_contents: *const u16,\n pub p_funcs: &'static UTextFuncs,\n pub p_extra: *mut c_void,\n pub context: *mut c_void,\n pub p: *mut c_void,\n pub q: *mut c_void,\n pub r: *mut c_void,\n pub priv_p: *mut c_void,\n pub a: i64,\n pub b: i32,\n pub c: i32,\n pub priv_a: i64,\n pub priv_b: i32,\n pub priv_c: i32,\n }\n\n pub const UTEXT_MAGIC: u32 = 0x345ad82c;\n pub const UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE: i32 = 1;\n pub const UTEXT_PROVIDER_STABLE_CHUNKS: i32 = 2;\n pub const UTEXT_PROVIDER_WRITABLE: i32 = 3;\n pub const UTEXT_PROVIDER_HAS_META_DATA: i32 = 4;\n pub const UTEXT_PROVIDER_OWNS_TEXT: i32 = 5;\n\n pub type utext_setup = unsafe extern \"C\" fn(\n ut: *mut UText,\n extra_space: i32,\n status: &mut UErrorCode,\n ) -> *mut UText;\n pub type utext_close = unsafe extern \"C\" fn(ut: *mut UText) -> *mut UText;\n\n #[repr(C)]\n pub struct UParseError {\n pub line: i32,\n pub offset: i32,\n pub pre_context: [u16; 16],\n pub post_context: [u16; 16],\n }\n\n #[repr(C)]\n pub struct URegularExpression;\n\n pub const UREGEX_UNIX_LINES: i32 = 1;\n pub const UREGEX_CASE_INSENSITIVE: i32 = 2;\n pub const UREGEX_COMMENTS: i32 = 4;\n pub const UREGEX_MULTILINE: i32 = 8;\n pub const UREGEX_LITERAL: i32 = 16;\n pub const UREGEX_DOTALL: i32 = 32;\n pub const UREGEX_UWORD: i32 = 256;\n pub const UREGEX_ERROR_ON_UNKNOWN_ESCAPES: i32 = 512;\n\n pub type uregex_open = unsafe extern \"C\" fn(\n pattern: *const u16,\n pattern_length: i32,\n flags: i32,\n pe: Option<&mut UParseError>,\n status: &mut UErrorCode,\n ) -> *mut URegularExpression;\n pub type uregex_close = unsafe extern \"C\" fn(regexp: *mut URegularExpression);\n pub type uregex_setTimeLimit =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, limit: i32, status: &mut UErrorCode);\n pub type uregex_setUText = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n text: *mut UText,\n status: &mut UErrorCode,\n );\n pub type uregex_reset64 =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, index: i64, status: &mut UErrorCode);\n pub type uregex_findNext =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, status: &mut UErrorCode) -> bool;\n pub type uregex_groupCount =\n unsafe extern \"C\" fn(regexp: *mut URegularExpression, status: &mut UErrorCode) -> i32;\n pub type uregex_start64 = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n group_num: i32,\n status: &mut UErrorCode,\n ) -> i64;\n pub type uregex_end64 = unsafe extern \"C\" fn(\n regexp: *mut URegularExpression,\n group_num: i32,\n status: &mut UErrorCode,\n ) -> i64;\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[ignore]\n #[test]\n fn init() {\n assert!(init_if_needed().is_ok());\n }\n\n #[test]\n fn test_compare_strings_ascii() {\n // Empty strings\n assert_eq!(compare_strings_ascii(b\"\", b\"\"), Ordering::Equal);\n // Equal strings\n assert_eq!(compare_strings_ascii(b\"hello\", b\"hello\"), Ordering::Equal);\n // Different lengths\n assert_eq!(compare_strings_ascii(b\"abc\", b\"abcd\"), Ordering::Less);\n assert_eq!(compare_strings_ascii(b\"abcd\", b\"abc\"), Ordering::Greater);\n // Same chars, different cases - 1st char wins\n assert_eq!(compare_strings_ascii(b\"AbC\", b\"aBc\"), Ordering::Less);\n // Different chars, different cases - 2nd char wins, because it differs\n assert_eq!(compare_strings_ascii(b\"hallo\", b\"Hello\"), Ordering::Less);\n assert_eq!(compare_strings_ascii(b\"Hello\", b\"hallo\"), Ordering::Greater);\n }\n}\n", "middle_code": "while let Some((&a, &b)) = iter.next() {\n if a != b {\n let mut order = a.cmp(&b);\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n if la == lb {\n for (a, b) in iter {\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n if la != lb {\n order = la.cmp(&lb);\n break;\n }\n }\n }\n return order;\n }\n }", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "rust", "sub_task_type": "while_statement"}, "context_code": [["/edit/src/sys/unix.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Unix-specific platform code.\n//!\n//! Read the `windows` module for reference.\n//! TODO: This reminds me that the sys API should probably be a trait.\n\nuse std::ffi::{CStr, c_char, c_int, c_void};\nuse std::fs::File;\nuse std::mem::{self, ManuallyDrop, MaybeUninit};\nuse std::os::fd::{AsRawFd as _, FromRawFd as _};\nuse std::path::Path;\nuse std::ptr::{self, NonNull, null_mut};\nuse std::{thread, time};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::helpers::*;\nuse crate::{apperr, arena_format};\n\n#[cfg(target_os = \"netbsd\")]\nconst fn desired_mprotect(flags: c_int) -> c_int {\n // NetBSD allows an mmap(2) caller to specify what protection flags they\n // will use later via mprotect. It does not allow a caller to move from\n // PROT_NONE to PROT_READ | PROT_WRITE.\n //\n // see PROT_MPROTECT in man 2 mmap\n flags << 3\n}\n\n#[cfg(not(target_os = \"netbsd\"))]\nconst fn desired_mprotect(_: c_int) -> c_int {\n libc::PROT_NONE\n}\n\nstruct State {\n stdin: libc::c_int,\n stdin_flags: libc::c_int,\n stdout: libc::c_int,\n stdout_initial_termios: Option,\n inject_resize: bool,\n // Buffer for incomplete UTF-8 sequences (max 4 bytes needed)\n utf8_buf: [u8; 4],\n utf8_len: usize,\n}\n\nstatic mut STATE: State = State {\n stdin: libc::STDIN_FILENO,\n stdin_flags: 0,\n stdout: libc::STDOUT_FILENO,\n stdout_initial_termios: None,\n inject_resize: false,\n utf8_buf: [0; 4],\n utf8_len: 0,\n};\n\nextern \"C\" fn sigwinch_handler(_: libc::c_int) {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\npub fn init() -> Deinit {\n Deinit\n}\n\npub fn switch_modes() -> apperr::Result<()> {\n unsafe {\n // Reopen stdin if it's redirected (= piped input).\n if libc::isatty(STATE.stdin) == 0 {\n STATE.stdin = check_int_return(libc::open(c\"/dev/tty\".as_ptr(), libc::O_RDONLY))?;\n }\n\n // Store the stdin flags so we can more easily toggle `O_NONBLOCK` later on.\n STATE.stdin_flags = check_int_return(libc::fcntl(STATE.stdin, libc::F_GETFL))?;\n\n // Set STATE.inject_resize to true whenever we get a SIGWINCH.\n let mut sigwinch_action: libc::sigaction = mem::zeroed();\n sigwinch_action.sa_sigaction = sigwinch_handler as libc::sighandler_t;\n check_int_return(libc::sigaction(libc::SIGWINCH, &sigwinch_action, null_mut()))?;\n\n // Get the original terminal modes so we can disable raw mode on exit.\n let mut termios = MaybeUninit::::uninit();\n check_int_return(libc::tcgetattr(STATE.stdout, termios.as_mut_ptr()))?;\n let mut termios = termios.assume_init();\n STATE.stdout_initial_termios = Some(termios);\n\n termios.c_iflag &= !(\n // When neither IGNBRK...\n libc::IGNBRK\n // ...nor BRKINT are set, a BREAK reads as a null byte ('\\0'), ...\n | libc::BRKINT\n // ...except when PARMRK is set, in which case it reads as the sequence \\377 \\0 \\0.\n | libc::PARMRK\n // Disable input parity checking.\n | libc::INPCK\n // Disable stripping of eighth bit.\n | libc::ISTRIP\n // Disable mapping of NL to CR on input.\n | libc::INLCR\n // Disable ignoring CR on input.\n | libc::IGNCR\n // Disable mapping of CR to NL on input.\n | libc::ICRNL\n // Disable software flow control.\n | libc::IXON\n );\n // Disable output processing.\n termios.c_oflag &= !libc::OPOST;\n termios.c_cflag &= !(\n // Reset character size mask.\n libc::CSIZE\n // Disable parity generation.\n | libc::PARENB\n );\n // Set character size back to 8 bits.\n termios.c_cflag |= libc::CS8;\n termios.c_lflag &= !(\n // Disable signal generation (SIGINT, SIGTSTP, SIGQUIT).\n libc::ISIG\n // Disable canonical mode (line buffering).\n | libc::ICANON\n // Disable echoing of input characters.\n | libc::ECHO\n // Disable echoing of NL.\n | libc::ECHONL\n // Disable extended input processing (e.g. Ctrl-V).\n | libc::IEXTEN\n );\n\n // Set the terminal to raw mode.\n termios.c_lflag &= !(libc::ICANON | libc::ECHO);\n check_int_return(libc::tcsetattr(STATE.stdout, libc::TCSANOW, &termios))?;\n\n Ok(())\n }\n}\n\npub struct Deinit;\n\nimpl Drop for Deinit {\n fn drop(&mut self) {\n unsafe {\n #[allow(static_mut_refs)]\n if let Some(termios) = STATE.stdout_initial_termios.take() {\n // Restore the original terminal modes.\n libc::tcsetattr(STATE.stdout, libc::TCSANOW, &termios);\n }\n }\n }\n}\n\npub fn inject_window_size_into_stdin() {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\nfn get_window_size() -> (u16, u16) {\n let mut winsz: libc::winsize = unsafe { mem::zeroed() };\n\n for attempt in 1.. {\n let ret = unsafe { libc::ioctl(STATE.stdout, libc::TIOCGWINSZ, &raw mut winsz) };\n if ret == -1 || (winsz.ws_col != 0 && winsz.ws_row != 0) {\n break;\n }\n\n if attempt == 10 {\n winsz.ws_col = 80;\n winsz.ws_row = 24;\n break;\n }\n\n // Some terminals are bad emulators and don't report TIOCGWINSZ immediately.\n thread::sleep(time::Duration::from_millis(10 * attempt));\n }\n\n (winsz.ws_col, winsz.ws_row)\n}\n\n/// Reads from stdin.\n///\n/// Returns `None` if there was an error reading from stdin.\n/// Returns `Some(\"\")` if the given timeout was reached.\n/// Otherwise, it returns the read, non-empty string.\npub fn read_stdin(arena: &Arena, mut timeout: time::Duration) -> Option> {\n unsafe {\n if STATE.inject_resize {\n timeout = time::Duration::ZERO;\n }\n\n let read_poll = timeout != time::Duration::MAX;\n let mut buf = Vec::new_in(arena);\n\n // We don't know if the input is valid UTF8, so we first use a Vec and then\n // later turn it into UTF8 using `from_utf8_lossy_owned`.\n // It is important that we allocate the buffer with an explicit capacity,\n // because we later use `spare_capacity_mut` to access it.\n buf.reserve(4 * KIBI);\n\n // We got some leftover broken UTF8 from a previous read? Prepend it.\n if STATE.utf8_len != 0 {\n buf.extend_from_slice(&STATE.utf8_buf[..STATE.utf8_len]);\n STATE.utf8_len = 0;\n }\n\n loop {\n if timeout != time::Duration::MAX {\n let beg = time::Instant::now();\n\n let mut pollfd = libc::pollfd { fd: STATE.stdin, events: libc::POLLIN, revents: 0 };\n let ret;\n #[cfg(target_os = \"linux\")]\n {\n let ts = libc::timespec {\n tv_sec: timeout.as_secs() as libc::time_t,\n tv_nsec: timeout.subsec_nanos() as libc::c_long,\n };\n ret = libc::ppoll(&mut pollfd, 1, &ts, ptr::null());\n }\n #[cfg(not(target_os = \"linux\"))]\n {\n ret = libc::poll(&mut pollfd, 1, timeout.as_millis() as libc::c_int);\n }\n if ret < 0 {\n return None; // Error? Let's assume it's an EOF.\n }\n if ret == 0 {\n break; // Timeout? We can stop reading.\n }\n\n timeout = timeout.saturating_sub(beg.elapsed());\n };\n\n // If we're asked for a non-blocking read we need\n // to manipulate `O_NONBLOCK` and vice versa.\n set_tty_nonblocking(read_poll);\n\n // Read from stdin.\n let spare = buf.spare_capacity_mut();\n let ret = libc::read(STATE.stdin, spare.as_mut_ptr() as *mut _, spare.len());\n if ret > 0 {\n buf.set_len(buf.len() + ret as usize);\n break;\n }\n if ret == 0 {\n return None; // EOF\n }\n if ret < 0 {\n match errno() {\n libc::EINTR if STATE.inject_resize => break,\n libc::EAGAIN if timeout == time::Duration::ZERO => break,\n libc::EINTR | libc::EAGAIN => {}\n _ => return None,\n }\n }\n }\n\n if !buf.is_empty() {\n // We only need to check the last 3 bytes for UTF-8 continuation bytes,\n // because we should be able to assume that any 4 byte sequence is complete.\n let lim = buf.len().saturating_sub(3);\n let mut off = buf.len() - 1;\n\n // Find the start of the last potentially incomplete UTF-8 sequence.\n while off > lim && buf[off] & 0b1100_0000 == 0b1000_0000 {\n off -= 1;\n }\n\n let seq_len = match buf[off] {\n b if b & 0b1000_0000 == 0 => 1,\n b if b & 0b1110_0000 == 0b1100_0000 => 2,\n b if b & 0b1111_0000 == 0b1110_0000 => 3,\n b if b & 0b1111_1000 == 0b1111_0000 => 4,\n // If the lead byte we found isn't actually one, we don't cache it.\n // `from_utf8_lossy_owned` will replace it with U+FFFD.\n _ => 0,\n };\n\n // Cache incomplete sequence if any.\n if off + seq_len > buf.len() {\n STATE.utf8_len = buf.len() - off;\n STATE.utf8_buf[..STATE.utf8_len].copy_from_slice(&buf[off..]);\n buf.truncate(off);\n }\n }\n\n let mut result = ArenaString::from_utf8_lossy_owned(buf);\n\n // We received a SIGWINCH? Add a fake window size sequence for our input parser.\n // I prepend it so that on startup, the TUI system gets first initialized with a size.\n if STATE.inject_resize {\n STATE.inject_resize = false;\n let (w, h) = get_window_size();\n if w > 0 && h > 0 {\n let scratch = scratch_arena(Some(arena));\n let seq = arena_format!(&scratch, \"\\x1b[8;{h};{w}t\");\n result.replace_range(0..0, &seq);\n }\n }\n\n result.shrink_to_fit();\n Some(result)\n }\n}\n\npub fn write_stdout(text: &str) {\n if text.is_empty() {\n return;\n }\n\n // If we don't set the TTY to blocking mode,\n // the write will potentially fail with EAGAIN.\n set_tty_nonblocking(false);\n\n let buf = text.as_bytes();\n let mut written = 0;\n\n while written < buf.len() {\n let w = &buf[written..];\n let w = &buf[..w.len().min(GIBI)];\n let n = unsafe { libc::write(STATE.stdout, w.as_ptr() as *const _, w.len()) };\n\n if n >= 0 {\n written += n as usize;\n continue;\n }\n\n let err = errno();\n if err != libc::EINTR {\n return;\n }\n }\n}\n\n/// Sets/Resets `O_NONBLOCK` on the TTY handle.\n///\n/// Note that setting this flag applies to both stdin and stdout, because the\n/// TTY is a bidirectional device and both handles refer to the same thing.\nfn set_tty_nonblocking(nonblock: bool) {\n unsafe {\n let is_nonblock = (STATE.stdin_flags & libc::O_NONBLOCK) != 0;\n if is_nonblock != nonblock {\n STATE.stdin_flags ^= libc::O_NONBLOCK;\n let _ = libc::fcntl(STATE.stdin, libc::F_SETFL, STATE.stdin_flags);\n }\n }\n}\n\npub fn open_stdin_if_redirected() -> Option {\n unsafe {\n // Did we reopen stdin during `init()`?\n if STATE.stdin != libc::STDIN_FILENO {\n Some(File::from_raw_fd(libc::STDIN_FILENO))\n } else {\n None\n }\n }\n}\n\n#[derive(Clone, PartialEq, Eq)]\npub struct FileId {\n st_dev: libc::dev_t,\n st_ino: libc::ino_t,\n}\n\n/// Returns a unique identifier for the given file by handle or path.\npub fn file_id(file: Option<&File>, path: &Path) -> apperr::Result {\n let file = match file {\n Some(f) => f,\n None => &File::open(path)?,\n };\n\n unsafe {\n let mut stat = MaybeUninit::::uninit();\n check_int_return(libc::fstat(file.as_raw_fd(), stat.as_mut_ptr()))?;\n let stat = stat.assume_init();\n Ok(FileId { st_dev: stat.st_dev, st_ino: stat.st_ino })\n }\n}\n\n/// Reserves a virtual memory region of the given size.\n/// To commit the memory, use `virtual_commit`.\n/// To release the memory, use `virtual_release`.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Don't forget to release the memory when you're done with it or you'll leak it.\npub unsafe fn virtual_reserve(size: usize) -> apperr::Result> {\n unsafe {\n let ptr = libc::mmap(\n null_mut(),\n size,\n desired_mprotect(libc::PROT_READ | libc::PROT_WRITE),\n libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,\n -1,\n 0,\n );\n if ptr.is_null() || ptr::eq(ptr, libc::MAP_FAILED) {\n Err(errno_to_apperr(libc::ENOMEM))\n } else {\n Ok(NonNull::new_unchecked(ptr as *mut u8))\n }\n }\n}\n\n/// Releases a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from `virtual_reserve`.\npub unsafe fn virtual_release(base: NonNull, size: usize) {\n unsafe {\n libc::munmap(base.cast().as_ptr(), size);\n }\n}\n\n/// Commits a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from `virtual_reserve`\n/// and to pass a size less than or equal to the size passed to `virtual_reserve`.\npub unsafe fn virtual_commit(base: NonNull, size: usize) -> apperr::Result<()> {\n unsafe {\n let status = libc::mprotect(base.cast().as_ptr(), size, libc::PROT_READ | libc::PROT_WRITE);\n if status != 0 { Err(errno_to_apperr(libc::ENOMEM)) } else { Ok(()) }\n }\n}\n\nunsafe fn load_library(name: *const c_char) -> apperr::Result> {\n unsafe {\n NonNull::new(libc::dlopen(name, libc::RTLD_LAZY))\n .ok_or_else(|| errno_to_apperr(libc::ENOENT))\n }\n}\n\n/// Loads a function from a dynamic library.\n///\n/// # Safety\n///\n/// This function is highly unsafe as it requires you to know the exact type\n/// of the function you're loading. No type checks whatsoever are performed.\n//\n// It'd be nice to constrain T to std::marker::FnPtr, but that's unstable.\npub unsafe fn get_proc_address(\n handle: NonNull,\n name: *const c_char,\n) -> apperr::Result {\n unsafe {\n let sym = libc::dlsym(handle.as_ptr(), name);\n if sym.is_null() {\n Err(errno_to_apperr(libc::ENOENT))\n } else {\n Ok(mem::transmute_copy(&sym))\n }\n }\n}\n\npub struct LibIcu {\n pub libicuuc: NonNull,\n pub libicui18n: NonNull,\n}\n\npub fn load_icu() -> apperr::Result {\n const fn const_str_eq(a: &str, b: &str) -> bool {\n let a = a.as_bytes();\n let b = b.as_bytes();\n let mut i = 0;\n\n loop {\n if i >= a.len() || i >= b.len() {\n return a.len() == b.len();\n }\n if a[i] != b[i] {\n return false;\n }\n i += 1;\n }\n }\n\n const LIBICUUC: &str = concat!(env!(\"EDIT_CFG_ICUUC_SONAME\"), \"\\0\");\n const LIBICUI18N: &str = concat!(env!(\"EDIT_CFG_ICUI18N_SONAME\"), \"\\0\");\n\n if const { const_str_eq(LIBICUUC, LIBICUI18N) } {\n let icu = unsafe { load_library(LIBICUUC.as_ptr() as *const _)? };\n Ok(LibIcu { libicuuc: icu, libicui18n: icu })\n } else {\n let libicuuc = unsafe { load_library(LIBICUUC.as_ptr() as *const _)? };\n let libicui18n = unsafe { load_library(LIBICUI18N.as_ptr() as *const _)? };\n Ok(LibIcu { libicuuc, libicui18n })\n }\n}\n/// ICU, by default, adds the major version as a suffix to each exported symbol.\n/// They also recommend to disable this for system-level installations (`runConfigureICU Linux --disable-renaming`),\n/// but I found that many (most?) Linux distributions don't do this for some reason.\n/// This function returns the suffix, if any.\n#[cfg(edit_icu_renaming_auto_detect)]\npub fn icu_detect_renaming_suffix(arena: &Arena, handle: NonNull) -> ArenaString<'_> {\n unsafe {\n type T = *const c_void;\n\n let mut res = ArenaString::new_in(arena);\n\n // Check if the ICU library is using unversioned symbols.\n // Return an empty suffix in that case.\n if get_proc_address::(handle, c\"u_errorName\".as_ptr()).is_ok() {\n return res;\n }\n\n // In the versions (63-76) and distributions (Arch/Debian) I tested,\n // this symbol seems to be always present. This allows us to call `dladdr`.\n // It's the `UCaseMap::~UCaseMap()` destructor which for some reason isn't\n // in a namespace. Thank you ICU maintainers for this oversight.\n let proc = match get_proc_address::(handle, c\"_ZN8UCaseMapD1Ev\".as_ptr()) {\n Ok(proc) => proc,\n Err(_) => return res,\n };\n\n // `dladdr` is specific to GNU's libc unfortunately.\n let mut info: libc::Dl_info = mem::zeroed();\n let ret = libc::dladdr(proc, &mut info);\n if ret == 0 {\n return res;\n }\n\n // The library path is in `info.dli_fname`.\n let path = match CStr::from_ptr(info.dli_fname).to_str() {\n Ok(name) => name,\n Err(_) => return res,\n };\n\n let path = match std::fs::read_link(path) {\n Ok(path) => path,\n Err(_) => path.into(),\n };\n\n // I'm going to assume it's something like \"libicuuc.so.76.1\".\n let path = path.into_os_string();\n let path = path.to_string_lossy();\n let suffix_start = match path.rfind(\".so.\") {\n Some(pos) => pos + 4,\n None => return res,\n };\n let version = &path[suffix_start..];\n let version_end = version.find('.').unwrap_or(version.len());\n let version = &version[..version_end];\n\n res.push('_');\n res.push_str(version);\n res\n }\n}\n\n#[cfg(edit_icu_renaming_auto_detect)]\n#[allow(clippy::not_unsafe_ptr_arg_deref)]\npub fn icu_add_renaming_suffix<'a, 'b, 'r>(\n arena: &'a Arena,\n name: *const c_char,\n suffix: &str,\n) -> *const c_char\nwhere\n 'a: 'r,\n 'b: 'r,\n{\n if suffix.is_empty() {\n name\n } else {\n // SAFETY: In this particular case we know that the string\n // is valid UTF-8, because it comes from icu.rs.\n let name = unsafe { CStr::from_ptr(name) };\n let name = unsafe { name.to_str().unwrap_unchecked() };\n\n let mut res = ManuallyDrop::new(ArenaString::new_in(arena));\n res.reserve(name.len() + suffix.len() + 1);\n res.push_str(name);\n res.push_str(suffix);\n res.push('\\0');\n res.as_ptr() as *const c_char\n }\n}\n\npub fn preferred_languages(arena: &Arena) -> Vec, &Arena> {\n let mut locales = Vec::new_in(arena);\n\n for key in [\"LANGUAGE\", \"LC_ALL\", \"LANG\"] {\n if let Ok(val) = std::env::var(key)\n && !val.is_empty()\n {\n locales.extend(val.split(':').filter(|s| !s.is_empty()).map(|s| {\n // Replace all underscores with dashes,\n // because the localization code expects pt-br, not pt_BR.\n let mut res = Vec::new_in(arena);\n res.extend(s.as_bytes().iter().map(|&b| if b == b'_' { b'-' } else { b }));\n unsafe { ArenaString::from_utf8_unchecked(res) }\n }));\n break;\n }\n }\n\n locales\n}\n\n#[inline]\nfn errno() -> i32 {\n // Under `-O -Copt-level=s` the 1.87 compiler fails to fully inline and\n // remove the raw_os_error() call. This leaves us with the drop() call.\n // ManuallyDrop fixes that and results in a direct `std::sys::os::errno` call.\n ManuallyDrop::new(std::io::Error::last_os_error()).raw_os_error().unwrap_or(0)\n}\n\n#[inline]\npub(crate) fn io_error_to_apperr(err: std::io::Error) -> apperr::Error {\n errno_to_apperr(err.raw_os_error().unwrap_or(0))\n}\n\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n write!(f, \"Error {code}\")?;\n\n unsafe {\n let ptr = libc::strerror(code as i32);\n if !ptr.is_null() {\n let msg = CStr::from_ptr(ptr).to_string_lossy();\n write!(f, \": {msg}\")?;\n }\n }\n\n Ok(())\n}\n\npub fn apperr_is_not_found(err: apperr::Error) -> bool {\n err == errno_to_apperr(libc::ENOENT)\n}\n\nconst fn errno_to_apperr(no: c_int) -> apperr::Error {\n apperr::Error::new_sys(if no < 0 { 0 } else { no as u32 })\n}\n\nfn check_int_return(ret: libc::c_int) -> apperr::Result {\n if ret < 0 { Err(errno_to_apperr(errno())) } else { Ok(ret) }\n}\n"], ["/edit/src/buffer/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! A text buffer for a text editor.\n//!\n//! Implements a Unicode-aware, layout-aware text buffer for terminals.\n//! It's based on a gap buffer. It has no line cache and instead relies\n//! on the performance of the ucd module for fast text navigation.\n//!\n//! ---\n//!\n//! If the project ever outgrows a basic gap buffer (e.g. to add time travel)\n//! an ideal, alternative architecture would be a piece table with immutable trees.\n//! The tree nodes can be allocated on the same arena allocator as the added chunks,\n//! making lifetime management fairly easy. The algorithm is described here:\n//! * \n//! * \n//!\n//! The downside is that text navigation & search takes a performance hit due to small chunks.\n//! The solution to the former is to keep line caches, which further complicates the architecture.\n//! There's no solution for the latter. However, there's a chance that the performance will still be sufficient.\n\nmod gap_buffer;\nmod navigation;\n\nuse std::borrow::Cow;\nuse std::cell::UnsafeCell;\nuse std::collections::LinkedList;\nuse std::fmt::Write as _;\nuse std::fs::File;\nuse std::io::{Read as _, Write as _};\nuse std::mem::{self, MaybeUninit};\nuse std::ops::Range;\nuse std::rc::Rc;\nuse std::str;\n\npub use gap_buffer::GapBuffer;\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::cell::SemiRefCell;\nuse crate::clipboard::Clipboard;\nuse crate::document::{ReadableDocument, WriteableDocument};\nuse crate::framebuffer::{Framebuffer, IndexedColor};\nuse crate::helpers::*;\nuse crate::oklab::oklab_blend;\nuse crate::simd::memchr2;\nuse crate::unicode::{self, Cursor, MeasurementConfig, Utf8Chars};\nuse crate::{apperr, icu, simd};\n\n/// The margin template is used for line numbers.\n/// The max. line number we should ever expect is probably 64-bit,\n/// and so this template fits 19 digits, followed by \" │ \".\nconst MARGIN_TEMPLATE: &str = \" │ \";\n/// Just a bunch of whitespace you can use for turning tabs into spaces.\n/// Happens to reuse MARGIN_TEMPLATE, because it has sufficient whitespace.\nconst TAB_WHITESPACE: &str = MARGIN_TEMPLATE;\nconst VISUAL_SPACE: &str = \"・\";\nconst VISUAL_SPACE_PREFIX_ADD: usize = '・'.len_utf8() - 1;\nconst VISUAL_TAB: &str = \"→ \";\nconst VISUAL_TAB_PREFIX_ADD: usize = '→'.len_utf8() - 1;\n\n/// Stores statistics about the whole document.\n#[derive(Copy, Clone)]\npub struct TextBufferStatistics {\n logical_lines: CoordType,\n visual_lines: CoordType,\n}\n\n/// Stores the active text selection anchors.\n///\n/// The two points are not sorted. Instead, `beg` refers to where the selection\n/// started being made and `end` refers to the currently being updated position.\n#[derive(Copy, Clone)]\nstruct TextBufferSelection {\n beg: Point,\n end: Point,\n}\n\n/// In order to group actions into a single undo step,\n/// we need to know the type of action that was performed.\n/// This stores the action type.\n#[derive(Copy, Clone, Eq, PartialEq)]\nenum HistoryType {\n Other,\n Write,\n Delete,\n}\n\n/// An undo/redo entry.\nstruct HistoryEntry {\n /// [`TextBuffer::cursor`] position before the change was made.\n cursor_before: Point,\n /// [`TextBuffer::selection`] before the change was made.\n selection_before: Option,\n /// [`TextBuffer::stats`] before the change was made.\n stats_before: TextBufferStatistics,\n /// [`GapBuffer::generation`] before the change was made.\n ///\n /// **NOTE:** Entries with the same generation are grouped together.\n generation_before: u32,\n /// Logical cursor position where the change took place.\n /// The position is at the start of the changed range.\n cursor: Point,\n /// Text that was deleted from the buffer.\n deleted: Vec,\n /// Text that was added to the buffer.\n added: Vec,\n}\n\n/// Caches an ICU search operation.\nstruct ActiveSearch {\n /// The search pattern.\n pattern: String,\n /// The search options.\n options: SearchOptions,\n /// The ICU `UText` object.\n text: icu::Text,\n /// The ICU `URegularExpression` object.\n regex: icu::Regex,\n /// [`GapBuffer::generation`] when the search was created.\n /// This is used to detect if we need to refresh the\n /// [`ActiveSearch::regex`] object.\n buffer_generation: u32,\n /// [`TextBuffer::selection_generation`] when the search was\n /// created. When the user manually selects text, we need to\n /// refresh the [`ActiveSearch::pattern`] with it.\n selection_generation: u32,\n /// Stores the text buffer offset in between searches.\n next_search_offset: usize,\n /// If we know there were no hits, we can skip searching.\n no_matches: bool,\n}\n\n/// Options for a search operation.\n#[derive(Default, Clone, Copy, Eq, PartialEq)]\npub struct SearchOptions {\n /// If true, the search is case-sensitive.\n pub match_case: bool,\n /// If true, the search matches whole words.\n pub whole_word: bool,\n /// If true, the search uses regex.\n pub use_regex: bool,\n}\n\nenum RegexReplacement<'a> {\n Group(i32),\n Text(Vec),\n}\n\n/// Caches the start and length of the active edit line for a single edit.\n/// This helps us avoid having to remeasure the buffer after an edit.\nstruct ActiveEditLineInfo {\n /// Points to the start of the currently being edited line.\n safe_start: Cursor,\n /// Number of visual rows of the line that starts\n /// at [`ActiveEditLineInfo::safe_start`].\n line_height_in_rows: CoordType,\n /// Byte distance from the start of the line at\n /// [`ActiveEditLineInfo::safe_start`] to the next line.\n distance_next_line_start: usize,\n}\n\n/// Undo/redo grouping works by recording a set of \"overrides\",\n/// which are then applied in [`TextBuffer::edit_begin()`].\n/// This allows us to create a group of edits that all share a\n/// common `generation_before` and can be undone/redone together.\n/// This struct stores those overrides.\nstruct ActiveEditGroupInfo {\n /// [`TextBuffer::cursor`] position before the change was made.\n cursor_before: Point,\n /// [`TextBuffer::selection`] before the change was made.\n selection_before: Option,\n /// [`TextBuffer::stats`] before the change was made.\n stats_before: TextBufferStatistics,\n /// [`GapBuffer::generation`] before the change was made.\n ///\n /// **NOTE:** Entries with the same generation are grouped together.\n generation_before: u32,\n}\n\n/// Char- or word-wise navigation? Your choice.\npub enum CursorMovement {\n Grapheme,\n Word,\n}\n\n/// See [`TextBuffer::move_selected_lines`].\npub enum MoveLineDirection {\n Up,\n Down,\n}\n\n/// The result of a call to [`TextBuffer::render()`].\npub struct RenderResult {\n /// The maximum visual X position we encountered during rendering.\n pub visual_pos_x_max: CoordType,\n}\n\n/// A [`TextBuffer`] with inner mutability.\npub type TextBufferCell = SemiRefCell;\n\n/// A [`TextBuffer`] inside an [`Rc`].\n///\n/// We need this because the TUI system needs to borrow\n/// the given text buffer(s) until after the layout process.\npub type RcTextBuffer = Rc;\n\n/// A text buffer for a text editor.\npub struct TextBuffer {\n buffer: GapBuffer,\n\n undo_stack: LinkedList>,\n redo_stack: LinkedList>,\n last_history_type: HistoryType,\n last_save_generation: u32,\n\n active_edit_group: Option,\n active_edit_line_info: Option,\n active_edit_depth: i32,\n active_edit_off: usize,\n\n stats: TextBufferStatistics,\n cursor: Cursor,\n // When scrolling significant amounts of text away from the cursor,\n // rendering will naturally slow down proportionally to the distance.\n // To avoid this, we cache the cursor position for rendering.\n // Must be cleared on every edit or reflow.\n cursor_for_rendering: Option,\n selection: Option,\n selection_generation: u32,\n search: Option>,\n\n width: CoordType,\n margin_width: CoordType,\n margin_enabled: bool,\n word_wrap_column: CoordType,\n word_wrap_enabled: bool,\n tab_size: CoordType,\n indent_with_tabs: bool,\n line_highlight_enabled: bool,\n ruler: CoordType,\n encoding: &'static str,\n newlines_are_crlf: bool,\n insert_final_newline: bool,\n overtype: bool,\n\n wants_cursor_visibility: bool,\n}\n\nimpl TextBuffer {\n /// Creates a new text buffer inside an [`Rc`].\n /// See [`TextBuffer::new()`].\n pub fn new_rc(small: bool) -> apperr::Result {\n let buffer = Self::new(small)?;\n Ok(Rc::new(SemiRefCell::new(buffer)))\n }\n\n /// Creates a new text buffer. With `small` you can control\n /// if the buffer is optimized for <1MiB contents.\n pub fn new(small: bool) -> apperr::Result {\n Ok(Self {\n buffer: GapBuffer::new(small)?,\n\n undo_stack: LinkedList::new(),\n redo_stack: LinkedList::new(),\n last_history_type: HistoryType::Other,\n last_save_generation: 0,\n\n active_edit_group: None,\n active_edit_line_info: None,\n active_edit_depth: 0,\n active_edit_off: 0,\n\n stats: TextBufferStatistics { logical_lines: 1, visual_lines: 1 },\n cursor: Default::default(),\n cursor_for_rendering: None,\n selection: None,\n selection_generation: 0,\n search: None,\n\n width: 0,\n margin_width: 0,\n margin_enabled: false,\n word_wrap_column: 0,\n word_wrap_enabled: false,\n tab_size: 4,\n indent_with_tabs: false,\n line_highlight_enabled: false,\n ruler: 0,\n encoding: \"UTF-8\",\n newlines_are_crlf: cfg!(windows), // Windows users want CRLF\n insert_final_newline: false,\n overtype: false,\n\n wants_cursor_visibility: false,\n })\n }\n\n /// Length of the document in bytes.\n pub fn text_length(&self) -> usize {\n self.buffer.len()\n }\n\n /// Number of logical lines in the document,\n /// that is, lines separated by newlines.\n pub fn logical_line_count(&self) -> CoordType {\n self.stats.logical_lines\n }\n\n /// Number of visual lines in the document,\n /// that is, the number of lines after layout.\n pub fn visual_line_count(&self) -> CoordType {\n self.stats.visual_lines\n }\n\n /// Does the buffer need to be saved?\n pub fn is_dirty(&self) -> bool {\n self.last_save_generation != self.buffer.generation()\n }\n\n /// The buffer generation changes on every edit.\n /// With this you can check if it has changed since\n /// the last time you called this function.\n pub fn generation(&self) -> u32 {\n self.buffer.generation()\n }\n\n /// Force the buffer to be dirty.\n pub fn mark_as_dirty(&mut self) {\n self.last_save_generation = self.buffer.generation().wrapping_sub(1);\n }\n\n fn mark_as_clean(&mut self) {\n self.last_save_generation = self.buffer.generation();\n }\n\n /// The encoding used during reading/writing. \"UTF-8\" is the default.\n pub fn encoding(&self) -> &'static str {\n self.encoding\n }\n\n /// Set the encoding used during reading/writing.\n pub fn set_encoding(&mut self, encoding: &'static str) {\n if self.encoding != encoding {\n self.encoding = encoding;\n self.mark_as_dirty();\n }\n }\n\n /// The newline type used in the document. LF or CRLF.\n pub fn is_crlf(&self) -> bool {\n self.newlines_are_crlf\n }\n\n /// Changes the newline type without normalizing the document.\n pub fn set_crlf(&mut self, crlf: bool) {\n self.newlines_are_crlf = crlf;\n }\n\n /// Changes the newline type used in the document.\n ///\n /// NOTE: Cannot be undone.\n pub fn normalize_newlines(&mut self, crlf: bool) {\n let newline: &[u8] = if crlf { b\"\\r\\n\" } else { b\"\\n\" };\n let mut off = 0;\n\n let mut cursor_offset = self.cursor.offset;\n let mut cursor_for_rendering_offset =\n self.cursor_for_rendering.map_or(cursor_offset, |c| c.offset);\n\n #[cfg(debug_assertions)]\n let mut adjusted_newlines = 0;\n\n 'outer: loop {\n // Seek to the offset of the next line start.\n loop {\n let chunk = self.read_forward(off);\n if chunk.is_empty() {\n break 'outer;\n }\n\n let (delta, line) = simd::lines_fwd(chunk, 0, 0, 1);\n off += delta;\n if line == 1 {\n break;\n }\n }\n\n // Get the preceding newline.\n let chunk = self.read_backward(off);\n let chunk_newline_len = if chunk.ends_with(b\"\\r\\n\") { 2 } else { 1 };\n let chunk_newline = &chunk[chunk.len() - chunk_newline_len..];\n\n if chunk_newline != newline {\n // If this newline is still before our cursor position, then it still has an effect on its offset.\n // Any newline adjustments past that cursor position are irrelevant.\n let delta = newline.len() as isize - chunk_newline_len as isize;\n if off <= cursor_offset {\n cursor_offset = cursor_offset.saturating_add_signed(delta);\n #[cfg(debug_assertions)]\n {\n adjusted_newlines += 1;\n }\n }\n if off <= cursor_for_rendering_offset {\n cursor_for_rendering_offset =\n cursor_for_rendering_offset.saturating_add_signed(delta);\n }\n\n // Replace the newline.\n off -= chunk_newline_len;\n self.buffer.replace(off..off + chunk_newline_len, newline);\n off += newline.len();\n }\n }\n\n // If this fails, the cursor offset calculation above is wrong.\n #[cfg(debug_assertions)]\n debug_assert_eq!(adjusted_newlines, self.cursor.logical_pos.y);\n\n self.cursor.offset = cursor_offset;\n if let Some(cursor) = &mut self.cursor_for_rendering {\n cursor.offset = cursor_for_rendering_offset;\n }\n\n self.newlines_are_crlf = crlf;\n }\n\n /// If enabled, automatically insert a final newline\n /// when typing at the end of the file.\n pub fn set_insert_final_newline(&mut self, enabled: bool) {\n self.insert_final_newline = enabled;\n }\n\n /// Whether to insert or overtype text when writing.\n pub fn is_overtype(&self) -> bool {\n self.overtype\n }\n\n /// Set the overtype mode.\n pub fn set_overtype(&mut self, overtype: bool) {\n self.overtype = overtype;\n }\n\n /// Gets the logical cursor position, that is,\n /// the position in lines and graphemes per line.\n pub fn cursor_logical_pos(&self) -> Point {\n self.cursor.logical_pos\n }\n\n /// Gets the visual cursor position, that is,\n /// the position in laid out rows and columns.\n pub fn cursor_visual_pos(&self) -> Point {\n self.cursor.visual_pos\n }\n\n /// Gets the width of the left margin.\n pub fn margin_width(&self) -> CoordType {\n self.margin_width\n }\n\n /// Is the left margin enabled?\n pub fn set_margin_enabled(&mut self, enabled: bool) -> bool {\n if self.margin_enabled == enabled {\n false\n } else {\n self.margin_enabled = enabled;\n self.reflow();\n true\n }\n }\n\n /// Gets the width of the text contents for layout.\n pub fn text_width(&self) -> CoordType {\n self.width - self.margin_width\n }\n\n /// Ask the TUI system to scroll the buffer and make the cursor visible.\n ///\n /// TODO: This function shows that [`TextBuffer`] is poorly abstracted\n /// away from the TUI system. The only reason this exists is so that\n /// if someone outside the TUI code enables word-wrap, the TUI code\n /// recognizes this and scrolls the cursor into view. But outside of this\n /// scrolling, views, etc., are all UI concerns = this should not be here.\n pub fn make_cursor_visible(&mut self) {\n self.wants_cursor_visibility = true;\n }\n\n /// For the TUI code to retrieve a prior [`TextBuffer::make_cursor_visible()`] request.\n pub fn take_cursor_visibility_request(&mut self) -> bool {\n mem::take(&mut self.wants_cursor_visibility)\n }\n\n /// Is word-wrap enabled?\n ///\n /// Technically, this is a misnomer, because it's line-wrapping.\n pub fn is_word_wrap_enabled(&self) -> bool {\n self.word_wrap_enabled\n }\n\n /// Enable or disable word-wrap.\n ///\n /// NOTE: It's expected that the tui code calls `set_width()` sometime after this.\n /// This will then trigger the actual recalculation of the cursor position.\n pub fn set_word_wrap(&mut self, enabled: bool) {\n if self.word_wrap_enabled != enabled {\n self.word_wrap_enabled = enabled;\n self.width = 0; // Force a reflow.\n self.make_cursor_visible();\n }\n }\n\n /// Set the width available for layout.\n ///\n /// Ideally this would be a pure UI concern, but the text buffer needs this\n /// so that it can abstract away visual cursor movement such as \"go a line up\".\n /// What would that even mean if it didn't know how wide a line is?\n pub fn set_width(&mut self, width: CoordType) -> bool {\n if width <= 0 || width == self.width {\n false\n } else {\n self.width = width;\n self.reflow();\n true\n }\n }\n\n /// Set the tab width. Could be anything, but is expected to be 1-8.\n pub fn tab_size(&self) -> CoordType {\n self.tab_size\n }\n\n /// Set the tab size. Clamped to 1-8.\n pub fn set_tab_size(&mut self, width: CoordType) -> bool {\n let width = width.clamp(1, 8);\n if width == self.tab_size {\n false\n } else {\n self.tab_size = width;\n self.reflow();\n true\n }\n }\n\n /// Calculates the amount of spaces a tab key press would insert at the given column.\n /// This also equals the visual width of an actual tab character.\n ///\n /// This exists because Rust doesn't have range constraints yet, and without\n /// them assembly blows up in size by 7x. It's a recurring issue with Rust.\n #[inline]\n fn tab_size_eval(&self, column: CoordType) -> CoordType {\n // SAFETY: `set_tab_size` clamps `self.tab_size` to 1-8.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1 && self.tab_size <= 8) };\n self.tab_size - (column % self.tab_size)\n }\n\n /// If the cursor is at an indentation of `column`, this returns\n /// the column to which a backspace key press would delete to.\n #[inline]\n fn tab_size_prev_column(&self, column: CoordType) -> CoordType {\n // SAFETY: `set_tab_size` clamps `self.tab_size` to 1-8.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1 && self.tab_size <= 8) };\n (column - 1).max(0) / self.tab_size * self.tab_size\n }\n\n /// Returns whether tabs are used for indentation.\n pub fn indent_with_tabs(&self) -> bool {\n self.indent_with_tabs\n }\n\n /// Sets whether tabs or spaces are used for indentation.\n pub fn set_indent_with_tabs(&mut self, indent_with_tabs: bool) {\n self.indent_with_tabs = indent_with_tabs;\n }\n\n /// Sets whether the line the cursor is on should be highlighted.\n pub fn set_line_highlight_enabled(&mut self, enabled: bool) {\n self.line_highlight_enabled = enabled;\n }\n\n /// Sets a ruler column, e.g. 80.\n pub fn set_ruler(&mut self, column: CoordType) {\n self.ruler = column;\n }\n\n pub fn reflow(&mut self) {\n self.reflow_internal(true);\n }\n\n fn recalc_after_content_changed(&mut self) {\n self.reflow_internal(false);\n }\n\n fn reflow_internal(&mut self, force: bool) {\n let word_wrap_column_before = self.word_wrap_column;\n\n {\n // +1 onto logical_lines, because line numbers are 1-based.\n // +1 onto log10, because we want the digit width and not the actual log10.\n // +3 onto log10, because we append \" | \" to the line numbers to form the margin.\n self.margin_width = if self.margin_enabled {\n self.stats.logical_lines.ilog10() as CoordType + 4\n } else {\n 0\n };\n\n let text_width = self.text_width();\n // 2 columns are required, because otherwise wide glyphs wouldn't ever fit.\n self.word_wrap_column =\n if self.word_wrap_enabled && text_width >= 2 { text_width } else { 0 };\n }\n\n self.cursor_for_rendering = None;\n\n if force || self.word_wrap_column != word_wrap_column_before {\n // Recalculate the cursor position.\n self.cursor = self.cursor_move_to_logical_internal(\n if self.word_wrap_column > 0 {\n Default::default()\n } else {\n self.goto_line_start(self.cursor, self.cursor.logical_pos.y)\n },\n self.cursor.logical_pos,\n );\n\n // Recalculate the line statistics.\n if self.word_wrap_column > 0 {\n let end = self.cursor_move_to_logical_internal(self.cursor, Point::MAX);\n self.stats.visual_lines = end.visual_pos.y + 1;\n } else {\n self.stats.visual_lines = self.stats.logical_lines;\n }\n }\n }\n\n /// Replaces the entire buffer contents with the given `text`.\n /// Assumes that the line count doesn't change.\n pub fn copy_from_str(&mut self, text: &dyn ReadableDocument) {\n if self.buffer.copy_from(text) {\n self.recalc_after_content_swap();\n self.cursor_move_to_logical(Point { x: CoordType::MAX, y: 0 });\n\n let delete = self.buffer.len() - self.cursor.offset;\n if delete != 0 {\n self.buffer.allocate_gap(self.cursor.offset, 0, delete);\n }\n }\n }\n\n fn recalc_after_content_swap(&mut self) {\n // If the buffer was changed, nothing we previously saved can be relied upon.\n self.undo_stack.clear();\n self.redo_stack.clear();\n self.last_history_type = HistoryType::Other;\n self.cursor = Default::default();\n self.set_selection(None);\n self.mark_as_clean();\n self.reflow();\n }\n\n /// Copies the contents of the buffer into a string.\n pub fn save_as_string(&mut self, dst: &mut dyn WriteableDocument) {\n self.buffer.copy_into(dst);\n self.mark_as_clean();\n }\n\n /// Reads a file from disk into the text buffer, detecting encoding and BOM.\n pub fn read_file(\n &mut self,\n file: &mut File,\n encoding: Option<&'static str>,\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let mut buf = scratch.alloc_uninit().transpose();\n let mut first_chunk_len = 0;\n let mut read = 0;\n\n // Read enough bytes to detect the BOM.\n while first_chunk_len < BOM_MAX_LEN {\n read = file_read_uninit(file, &mut buf[first_chunk_len..])?;\n if read == 0 {\n break;\n }\n first_chunk_len += read;\n }\n\n if let Some(encoding) = encoding {\n self.encoding = encoding;\n } else {\n let bom = detect_bom(unsafe { buf[..first_chunk_len].assume_init_ref() });\n self.encoding = bom.unwrap_or(\"UTF-8\");\n }\n\n // TODO: Since reading the file can fail, we should ensure that we also reset the cursor here.\n // I don't do it, so that `recalc_after_content_swap()` works.\n self.buffer.clear();\n\n let done = read == 0;\n if self.encoding == \"UTF-8\" {\n self.read_file_as_utf8(file, &mut buf, first_chunk_len, done)?;\n } else {\n self.read_file_with_icu(file, &mut buf, first_chunk_len, done)?;\n }\n\n // Figure out\n // * the logical line count\n // * the newline type (LF or CRLF)\n // * the indentation type (tabs or spaces)\n // * whether there's a final newline\n {\n let chunk = self.read_forward(0);\n let mut offset = 0;\n let mut lines = 0;\n // Number of lines ending in CRLF.\n let mut crlf_count = 0;\n // Number of lines starting with a tab.\n let mut tab_indentations = 0;\n // Number of lines starting with a space.\n let mut space_indentations = 0;\n // Histogram of the indentation depth of lines starting with between 2 and 8 spaces.\n // In other words, `space_indentation_sizes[0]` is the number of lines starting with 2 spaces.\n let mut space_indentation_sizes = [0; 7];\n\n loop {\n // Check if the line starts with a tab.\n if offset < chunk.len() && chunk[offset] == b'\\t' {\n tab_indentations += 1;\n } else {\n // Otherwise, check how many spaces the line starts with. Searching for >8 spaces\n // allows us to reject lines that have more than 1 level of indentation.\n let space_indentation =\n chunk[offset..].iter().take(9).take_while(|&&c| c == b' ').count();\n\n // We'll also reject lines starting with 1 space, because that's too fickle as a heuristic.\n if (2..=8).contains(&space_indentation) {\n space_indentations += 1;\n\n // If we encounter an indentation depth of 6, it may either be a 6-space indentation,\n // two 3-space indentation or 3 2-space indentations. To make this work, we increment\n // all 3 possible histogram slots.\n // 2 -> 2\n // 3 -> 3\n // 4 -> 4 2\n // 5 -> 5\n // 6 -> 6 3 2\n // 7 -> 7\n // 8 -> 8 4 2\n space_indentation_sizes[space_indentation - 2] += 1;\n if space_indentation & 4 != 0 {\n space_indentation_sizes[0] += 1;\n }\n if space_indentation == 6 || space_indentation == 8 {\n space_indentation_sizes[space_indentation / 2 - 2] += 1;\n }\n }\n }\n\n (offset, lines) = simd::lines_fwd(chunk, offset, lines, lines + 1);\n\n // Check if the preceding line ended in CRLF.\n if offset >= 2 && &chunk[offset - 2..offset] == b\"\\r\\n\" {\n crlf_count += 1;\n }\n\n // We'll limit our heuristics to the first 1000 lines.\n // That should hopefully be enough in practice.\n if offset >= chunk.len() || lines >= 1000 {\n break;\n }\n }\n\n // We'll assume CRLF if more than half of the lines end in CRLF.\n let newlines_are_crlf = crlf_count >= lines / 2;\n\n // We'll assume tabs if there are more lines starting with tabs than with spaces.\n let indent_with_tabs = tab_indentations > space_indentations;\n let tab_size = if indent_with_tabs {\n // Tabs will get a visual size of 4 spaces by default.\n 4\n } else {\n // Otherwise, we'll assume the most common indentation depth.\n // If there are conflicting indentation depths, we'll prefer the maximum, because in the loop\n // above we incremented the histogram slot for 2-spaces when encountering 4-spaces and so on.\n let mut max = 1;\n let mut tab_size = 4;\n for (i, &count) in space_indentation_sizes.iter().enumerate() {\n if count >= max {\n max = count;\n tab_size = i as CoordType + 2;\n }\n }\n tab_size\n };\n\n // If the file has more than 1000 lines, figure out how many are remaining.\n if offset < chunk.len() {\n (_, lines) = simd::lines_fwd(chunk, offset, lines, CoordType::MAX);\n }\n\n let final_newline = chunk.ends_with(b\"\\n\");\n\n // Add 1, because the last line doesn't end in a newline (it ends in the literal end).\n self.stats.logical_lines = lines + 1;\n self.stats.visual_lines = self.stats.logical_lines;\n self.newlines_are_crlf = newlines_are_crlf;\n self.insert_final_newline = final_newline;\n self.indent_with_tabs = indent_with_tabs;\n self.tab_size = tab_size;\n }\n\n self.recalc_after_content_swap();\n Ok(())\n }\n\n fn read_file_as_utf8(\n &mut self,\n file: &mut File,\n buf: &mut [MaybeUninit; 4 * KIBI],\n first_chunk_len: usize,\n done: bool,\n ) -> apperr::Result<()> {\n {\n let mut first_chunk = unsafe { buf[..first_chunk_len].assume_init_ref() };\n if first_chunk.starts_with(b\"\\xEF\\xBB\\xBF\") {\n first_chunk = &first_chunk[3..];\n self.encoding = \"UTF-8 BOM\";\n }\n\n self.buffer.replace(0..0, first_chunk);\n }\n\n if done {\n return Ok(());\n }\n\n // If we don't have file metadata, the input may be a pipe or a socket.\n // Every read will have the same size until we hit the end.\n let mut chunk_size = 128 * KIBI;\n let mut extra_chunk_size = 128 * KIBI;\n\n if let Ok(m) = file.metadata() {\n // Usually the next read of size `chunk_size` will read the entire file,\n // but if the size has changed for some reason, then `extra_chunk_size`\n // should be large enough to read the rest of the file.\n // 4KiB is not too large and not too slow.\n let len = m.len() as usize;\n chunk_size = len.saturating_sub(first_chunk_len);\n extra_chunk_size = 4 * KIBI;\n }\n\n loop {\n let gap = self.buffer.allocate_gap(self.text_length(), chunk_size, 0);\n if gap.is_empty() {\n break;\n }\n\n let read = file.read(gap)?;\n if read == 0 {\n break;\n }\n\n self.buffer.commit_gap(read);\n chunk_size = extra_chunk_size;\n }\n\n Ok(())\n }\n\n fn read_file_with_icu(\n &mut self,\n file: &mut File,\n buf: &mut [MaybeUninit; 4 * KIBI],\n first_chunk_len: usize,\n mut done: bool,\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let pivot_buffer = scratch.alloc_uninit_slice(4 * KIBI);\n let mut c = icu::Converter::new(pivot_buffer, self.encoding, \"UTF-8\")?;\n let mut first_chunk = unsafe { buf[..first_chunk_len].assume_init_ref() };\n\n while !first_chunk.is_empty() {\n let off = self.text_length();\n let gap = self.buffer.allocate_gap(off, 8 * KIBI, 0);\n let (input_advance, mut output_advance) =\n c.convert(first_chunk, slice_as_uninit_mut(gap))?;\n\n // Remove the BOM from the file, if this is the first chunk.\n // Our caller ensures to only call us once the BOM has been identified,\n // which means that if there's a BOM it must be wholly contained in this chunk.\n if off == 0 {\n let written = &mut gap[..output_advance];\n if written.starts_with(b\"\\xEF\\xBB\\xBF\") {\n written.copy_within(3.., 0);\n output_advance -= 3;\n }\n }\n\n self.buffer.commit_gap(output_advance);\n first_chunk = &first_chunk[input_advance..];\n }\n\n let mut buf_len = 0;\n\n loop {\n if !done {\n let read = file_read_uninit(file, &mut buf[buf_len..])?;\n buf_len += read;\n done = read == 0;\n }\n\n let gap = self.buffer.allocate_gap(self.text_length(), 8 * KIBI, 0);\n if gap.is_empty() {\n break;\n }\n\n let read = unsafe { buf[..buf_len].assume_init_ref() };\n let (input_advance, output_advance) = c.convert(read, slice_as_uninit_mut(gap))?;\n\n self.buffer.commit_gap(output_advance);\n\n let flush = done && buf_len == 0;\n buf_len -= input_advance;\n buf.copy_within(input_advance.., 0);\n\n if flush {\n break;\n }\n }\n\n Ok(())\n }\n\n /// Writes the text buffer contents to a file, handling BOM and encoding.\n pub fn write_file(&mut self, file: &mut File) -> apperr::Result<()> {\n let mut offset = 0;\n\n if self.encoding.starts_with(\"UTF-8\") {\n if self.encoding == \"UTF-8 BOM\" {\n file.write_all(b\"\\xEF\\xBB\\xBF\")?;\n }\n loop {\n let chunk = self.read_forward(offset);\n if chunk.is_empty() {\n break;\n }\n file.write_all(chunk)?;\n offset += chunk.len();\n }\n } else {\n self.write_file_with_icu(file)?;\n }\n\n self.mark_as_clean();\n Ok(())\n }\n\n fn write_file_with_icu(&mut self, file: &mut File) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let pivot_buffer = scratch.alloc_uninit_slice(4 * KIBI);\n let buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut c = icu::Converter::new(pivot_buffer, \"UTF-8\", self.encoding)?;\n let mut offset = 0;\n\n // Write the BOM for the encodings we know need it.\n if self.encoding.starts_with(\"UTF-16\")\n || self.encoding.starts_with(\"UTF-32\")\n || self.encoding == \"GB18030\"\n {\n let (_, output_advance) = c.convert(b\"\\xEF\\xBB\\xBF\", buf)?;\n let chunk = unsafe { buf[..output_advance].assume_init_ref() };\n file.write_all(chunk)?;\n }\n\n loop {\n let chunk = self.read_forward(offset);\n let (input_advance, output_advance) = c.convert(chunk, buf)?;\n let chunk = unsafe { buf[..output_advance].assume_init_ref() };\n\n file.write_all(chunk)?;\n offset += input_advance;\n\n if chunk.is_empty() {\n break;\n }\n }\n\n Ok(())\n }\n\n /// Returns the current selection.\n pub fn has_selection(&self) -> bool {\n self.selection.is_some()\n }\n\n fn set_selection(&mut self, selection: Option) -> u32 {\n self.selection = selection.filter(|s| s.beg != s.end);\n self.selection_generation = self.selection_generation.wrapping_add(1);\n self.selection_generation\n }\n\n /// Moves the cursor by `offset` and updates the selection to contain it.\n pub fn selection_update_offset(&mut self, offset: usize) {\n self.set_cursor_for_selection(self.cursor_move_to_offset_internal(self.cursor, offset));\n }\n\n /// Moves the cursor to `visual_pos` and updates the selection to contain it.\n pub fn selection_update_visual(&mut self, visual_pos: Point) {\n self.set_cursor_for_selection(self.cursor_move_to_visual_internal(self.cursor, visual_pos));\n }\n\n /// Moves the cursor to `logical_pos` and updates the selection to contain it.\n pub fn selection_update_logical(&mut self, logical_pos: Point) {\n self.set_cursor_for_selection(\n self.cursor_move_to_logical_internal(self.cursor, logical_pos),\n );\n }\n\n /// Moves the cursor by `delta` and updates the selection to contain it.\n pub fn selection_update_delta(&mut self, granularity: CursorMovement, delta: CoordType) {\n self.set_cursor_for_selection(self.cursor_move_delta_internal(\n self.cursor,\n granularity,\n delta,\n ));\n }\n\n /// Select the current word.\n pub fn select_word(&mut self) {\n let Range { start, end } = navigation::word_select(&self.buffer, self.cursor.offset);\n let beg = self.cursor_move_to_offset_internal(self.cursor, start);\n let end = self.cursor_move_to_offset_internal(beg, end);\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Select the current line.\n pub fn select_line(&mut self) {\n let beg = self.cursor_move_to_logical_internal(\n self.cursor,\n Point { x: 0, y: self.cursor.logical_pos.y },\n );\n let end = self\n .cursor_move_to_logical_internal(beg, Point { x: 0, y: self.cursor.logical_pos.y + 1 });\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Select the entire document.\n pub fn select_all(&mut self) {\n let beg = Default::default();\n let end = self.cursor_move_to_logical_internal(beg, Point::MAX);\n unsafe { self.set_cursor(end) };\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }));\n }\n\n /// Starts a new selection, if there's none already.\n pub fn start_selection(&mut self) {\n if self.selection.is_none() {\n self.set_selection(Some(TextBufferSelection {\n beg: self.cursor.logical_pos,\n end: self.cursor.logical_pos,\n }));\n }\n }\n\n /// Destroy the current selection.\n pub fn clear_selection(&mut self) -> bool {\n let had_selection = self.selection.is_some();\n self.set_selection(None);\n had_selection\n }\n\n /// Find the next occurrence of the given `pattern` and select it.\n pub fn find_and_select(&mut self, pattern: &str, options: SearchOptions) -> apperr::Result<()> {\n if let Some(search) = &mut self.search {\n let search = search.get_mut();\n // When the search input changes we must reset the search.\n if search.pattern != pattern || search.options != options {\n self.search = None;\n }\n\n // When transitioning from some search to no search, we must clear the selection.\n if pattern.is_empty()\n && let Some(TextBufferSelection { beg, .. }) = self.selection\n {\n self.cursor_move_to_logical(beg);\n }\n }\n\n if pattern.is_empty() {\n return Ok(());\n }\n\n let search = match &self.search {\n Some(search) => unsafe { &mut *search.get() },\n None => {\n let search = self.find_construct_search(pattern, options)?;\n self.search = Some(UnsafeCell::new(search));\n unsafe { &mut *self.search.as_ref().unwrap().get() }\n }\n };\n\n // If we previously searched through the entire document and found 0 matches,\n // then we can avoid searching again.\n if search.no_matches {\n return Ok(());\n }\n\n // If the user moved the cursor since the last search, but the needle remained the same,\n // we still need to move the start of the search to the new cursor position.\n let next_search_offset = match self.selection {\n Some(TextBufferSelection { beg, end }) => {\n if self.selection_generation == search.selection_generation {\n search.next_search_offset\n } else {\n self.cursor_move_to_logical_internal(self.cursor, beg.min(end)).offset\n }\n }\n _ => self.cursor.offset,\n };\n\n self.find_select_next(search, next_search_offset, true);\n Ok(())\n }\n\n /// Find the next occurrence of the given `pattern` and replace it with `replacement`.\n pub fn find_and_replace(\n &mut self,\n pattern: &str,\n options: SearchOptions,\n replacement: &[u8],\n ) -> apperr::Result<()> {\n // Editors traditionally replace the previous search hit, not the next possible one.\n if let (Some(search), Some(..)) = (&self.search, &self.selection) {\n let search = unsafe { &mut *search.get() };\n if search.selection_generation == self.selection_generation {\n let scratch = scratch_arena(None);\n let parsed_replacements =\n Self::find_parse_replacement(&scratch, &mut *search, replacement);\n let replacement =\n self.find_fill_replacement(&mut *search, replacement, &parsed_replacements);\n self.write(&replacement, self.cursor, true);\n }\n }\n\n self.find_and_select(pattern, options)\n }\n\n /// Find all occurrences of the given `pattern` and replace them with `replacement`.\n pub fn find_and_replace_all(\n &mut self,\n pattern: &str,\n options: SearchOptions,\n replacement: &[u8],\n ) -> apperr::Result<()> {\n let scratch = scratch_arena(None);\n let mut search = self.find_construct_search(pattern, options)?;\n let mut offset = 0;\n let parsed_replacements = Self::find_parse_replacement(&scratch, &mut search, replacement);\n\n loop {\n self.find_select_next(&mut search, offset, false);\n if !self.has_selection() {\n break;\n }\n\n let replacement =\n self.find_fill_replacement(&mut search, replacement, &parsed_replacements);\n self.write(&replacement, self.cursor, true);\n offset = self.cursor.offset;\n }\n\n Ok(())\n }\n\n fn find_construct_search(\n &self,\n pattern: &str,\n options: SearchOptions,\n ) -> apperr::Result {\n if pattern.is_empty() {\n return Err(apperr::Error::Icu(1)); // U_ILLEGAL_ARGUMENT_ERROR\n }\n\n let sanitized_pattern = if options.whole_word && options.use_regex {\n Cow::Owned(format!(r\"\\b(?:{pattern})\\b\"))\n } else if options.whole_word {\n let mut p = String::with_capacity(pattern.len() + 16);\n p.push_str(r\"\\b\");\n\n // Escape regex special characters.\n let b = unsafe { p.as_mut_vec() };\n for &byte in pattern.as_bytes() {\n match byte {\n b'*' | b'?' | b'+' | b'[' | b'(' | b')' | b'{' | b'}' | b'^' | b'$' | b'|'\n | b'\\\\' | b'.' => {\n b.push(b'\\\\');\n b.push(byte);\n }\n _ => b.push(byte),\n }\n }\n\n p.push_str(r\"\\b\");\n Cow::Owned(p)\n } else {\n Cow::Borrowed(pattern)\n };\n\n let mut flags = icu::Regex::MULTILINE;\n if !options.match_case {\n flags |= icu::Regex::CASE_INSENSITIVE;\n }\n if !options.use_regex && !options.whole_word {\n flags |= icu::Regex::LITERAL;\n }\n\n // Move the start of the search to the start of the selection,\n // or otherwise to the current cursor position.\n\n let text = unsafe { icu::Text::new(self)? };\n let regex = unsafe { icu::Regex::new(&sanitized_pattern, flags, &text)? };\n\n Ok(ActiveSearch {\n pattern: pattern.to_string(),\n options,\n text,\n regex,\n buffer_generation: self.buffer.generation(),\n selection_generation: 0,\n next_search_offset: 0,\n no_matches: false,\n })\n }\n\n fn find_select_next(&mut self, search: &mut ActiveSearch, offset: usize, wrap: bool) {\n if search.buffer_generation != self.buffer.generation() {\n unsafe { search.regex.set_text(&mut search.text, offset) };\n search.buffer_generation = self.buffer.generation();\n search.next_search_offset = offset;\n } else if search.next_search_offset != offset {\n search.next_search_offset = offset;\n search.regex.reset(offset);\n }\n\n let mut hit = search.regex.next();\n\n // If we hit the end of the buffer, and we know that there's something to find,\n // start the search again from the beginning (= wrap around).\n if wrap && hit.is_none() && search.next_search_offset != 0 {\n search.next_search_offset = 0;\n search.regex.reset(0);\n hit = search.regex.next();\n }\n\n search.selection_generation = if let Some(range) = hit {\n // Now the search offset is no more at the start of the buffer.\n search.next_search_offset = range.end;\n\n let beg = self.cursor_move_to_offset_internal(self.cursor, range.start);\n let end = self.cursor_move_to_offset_internal(beg, range.end);\n\n unsafe { self.set_cursor(end) };\n self.make_cursor_visible();\n\n self.set_selection(Some(TextBufferSelection {\n beg: beg.logical_pos,\n end: end.logical_pos,\n }))\n } else {\n // Avoid searching through the entire document again if we know there's nothing to find.\n search.no_matches = true;\n self.set_selection(None)\n };\n }\n\n fn find_parse_replacement<'a>(\n arena: &'a Arena,\n search: &mut ActiveSearch,\n replacement: &[u8],\n ) -> Vec, &'a Arena> {\n let mut res = Vec::new_in(arena);\n\n if !search.options.use_regex {\n return res;\n }\n\n let group_count = search.regex.group_count();\n let mut text = Vec::new_in(arena);\n let mut text_beg = 0;\n\n loop {\n let mut off = memchr2(b'$', b'\\\\', replacement, text_beg);\n\n // Push the raw, unescaped text, if any.\n if text_beg < off {\n text.extend_from_slice(&replacement[text_beg..off]);\n }\n\n // Unescape any escaped characters.\n while off < replacement.len() && replacement[off] == b'\\\\' {\n off += 2;\n\n // If this backslash is the last character (e.g. because\n // `replacement` is just 1 byte long, holding just b\"\\\\\"),\n // we can't unescape it. In that case, we map it to `b'\\\\'` here.\n // This results in us appending a literal backslash to the text.\n let ch = replacement.get(off - 1).map_or(b'\\\\', |&c| c);\n\n // Unescape and append the character.\n text.push(match ch {\n b'n' => b'\\n',\n b'r' => b'\\r',\n b't' => b'\\t',\n ch => ch,\n });\n }\n\n // Parse out a group number, if any.\n let mut group = -1;\n if off < replacement.len() && replacement[off] == b'$' {\n let mut beg = off;\n let mut end = off + 1;\n let mut acc = 0i32;\n let mut acc_bad = true;\n\n if end < replacement.len() {\n let ch = replacement[end];\n\n if ch == b'$' {\n // Translate \"$$\" to \"$\".\n beg += 1;\n end += 1;\n } else if ch.is_ascii_digit() {\n // Parse \"$1234\" into 1234i32.\n // If the number is larger than the group count,\n // we flag `acc_bad` which causes us to treat it as text.\n acc_bad = false;\n while {\n acc =\n acc.wrapping_mul(10).wrapping_add((replacement[end] - b'0') as i32);\n acc_bad |= acc > group_count;\n end += 1;\n end < replacement.len() && replacement[end].is_ascii_digit()\n } {}\n }\n }\n\n if !acc_bad {\n group = acc;\n } else {\n text.extend_from_slice(&replacement[beg..end]);\n }\n\n off = end;\n }\n\n if !text.is_empty() {\n res.push(RegexReplacement::Text(text));\n text = Vec::new_in(arena);\n }\n if group >= 0 {\n res.push(RegexReplacement::Group(group));\n }\n\n text_beg = off;\n if text_beg >= replacement.len() {\n break;\n }\n }\n\n res\n }\n\n fn find_fill_replacement<'a>(\n &self,\n search: &mut ActiveSearch,\n replacement: &'a [u8],\n parsed_replacements: &[RegexReplacement],\n ) -> Cow<'a, [u8]> {\n if !search.options.use_regex {\n Cow::Borrowed(replacement)\n } else {\n let mut res = Vec::new();\n\n for replacement in parsed_replacements {\n match replacement {\n RegexReplacement::Text(text) => res.extend_from_slice(text),\n RegexReplacement::Group(group) => {\n if let Some(range) = search.regex.group(*group) {\n self.buffer.extract_raw(range, &mut res, usize::MAX);\n }\n }\n }\n }\n\n Cow::Owned(res)\n }\n }\n\n fn measurement_config(&self) -> MeasurementConfig<'_> {\n MeasurementConfig::new(&self.buffer)\n .with_word_wrap_column(self.word_wrap_column)\n .with_tab_size(self.tab_size)\n }\n\n fn goto_line_start(&self, cursor: Cursor, y: CoordType) -> Cursor {\n let mut result = cursor;\n let mut seek_to_line_start = true;\n\n if y > result.logical_pos.y {\n while y > result.logical_pos.y {\n let chunk = self.read_forward(result.offset);\n if chunk.is_empty() {\n break;\n }\n\n let (delta, line) = simd::lines_fwd(chunk, 0, result.logical_pos.y, y);\n result.offset += delta;\n result.logical_pos.y = line;\n }\n\n // If we're at the end of the buffer, we could either be there because the last\n // character in the buffer is genuinely a newline, or because the buffer ends in a\n // line of text without trailing newline. The only way to make sure is to seek\n // backwards to the line start again. But otherwise we can skip that.\n seek_to_line_start =\n result.offset == self.text_length() && result.offset != cursor.offset;\n }\n\n if seek_to_line_start {\n loop {\n let chunk = self.read_backward(result.offset);\n if chunk.is_empty() {\n break;\n }\n\n let (delta, line) = simd::lines_bwd(chunk, chunk.len(), result.logical_pos.y, y);\n result.offset -= chunk.len() - delta;\n result.logical_pos.y = line;\n if delta > 0 {\n break;\n }\n }\n }\n\n if result.offset == cursor.offset {\n return result;\n }\n\n result.logical_pos.x = 0;\n result.visual_pos.x = 0;\n result.visual_pos.y = result.logical_pos.y;\n result.column = 0;\n result.wrap_opp = false;\n\n if self.word_wrap_column > 0 {\n let upward = result.offset < cursor.offset;\n let (top, bottom) = if upward { (result, cursor) } else { (cursor, result) };\n\n let mut bottom_remeasured =\n self.measurement_config().with_cursor(top).goto_logical(bottom.logical_pos);\n\n // The second problem is that visual positions can be ambiguous. A single logical position\n // can map to two visual positions: One at the end of the preceding line in front of\n // a word wrap, and another at the start of the next line after the same word wrap.\n //\n // This, however, only applies if we go upwards, because only then `bottom ≅ cursor`,\n // and thus only then this `bottom` is ambiguous. Otherwise, `bottom ≅ result`\n // and `result` is at a line start which is never ambiguous.\n if upward {\n let a = bottom_remeasured.visual_pos.x;\n let b = bottom.visual_pos.x;\n bottom_remeasured.visual_pos.y = bottom_remeasured.visual_pos.y\n + (a != 0 && b == 0) as CoordType\n - (a == 0 && b != 0) as CoordType;\n }\n\n let mut delta = bottom_remeasured.visual_pos.y - top.visual_pos.y;\n if upward {\n delta = -delta;\n }\n\n result.visual_pos.y = cursor.visual_pos.y + delta;\n }\n\n result\n }\n\n fn cursor_move_to_offset_internal(&self, mut cursor: Cursor, offset: usize) -> Cursor {\n if offset == cursor.offset {\n return cursor;\n }\n\n // goto_line_start() is fast for seeking across lines _if_ line wrapping is disabled.\n // For backward seeking we have to use it either way, so we're covered there.\n // This implements the forward seeking portion, if it's approx. worth doing so.\n if self.word_wrap_column <= 0 && offset.saturating_sub(cursor.offset) > 1024 {\n // Replacing this with a more optimal, direct memchr() loop appears\n // to improve performance only marginally by another 2% or so.\n // Still, it's kind of \"meh\" looking at how poorly this is implemented...\n loop {\n let next = self.goto_line_start(cursor, cursor.logical_pos.y + 1);\n // Stop when we either ran past the target offset,\n // or when we hit the end of the buffer and `goto_line_start` backtracked to the line start.\n if next.offset > offset || next.offset <= cursor.offset {\n break;\n }\n cursor = next;\n }\n }\n\n while offset < cursor.offset {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y - 1);\n }\n\n self.measurement_config().with_cursor(cursor).goto_offset(offset)\n }\n\n fn cursor_move_to_logical_internal(&self, mut cursor: Cursor, pos: Point) -> Cursor {\n let pos = Point { x: pos.x.max(0), y: pos.y.max(0) };\n\n if pos == cursor.logical_pos {\n return cursor;\n }\n\n // goto_line_start() is the fastest way for seeking across lines. As such we always\n // use it if the requested `.y` position is different. We still need to use it if the\n // `.x` position is smaller, but only because `goto_logical()` cannot seek backwards.\n if pos.y != cursor.logical_pos.y || pos.x < cursor.logical_pos.x {\n cursor = self.goto_line_start(cursor, pos.y);\n }\n\n self.measurement_config().with_cursor(cursor).goto_logical(pos)\n }\n\n fn cursor_move_to_visual_internal(&self, mut cursor: Cursor, pos: Point) -> Cursor {\n let pos = Point { x: pos.x.max(0), y: pos.y.max(0) };\n\n if pos == cursor.visual_pos {\n return cursor;\n }\n\n if self.word_wrap_column <= 0 {\n // Identical to the fast-pass in `cursor_move_to_logical_internal()`.\n if pos.y != cursor.visual_pos.y || pos.x < cursor.visual_pos.x {\n cursor = self.goto_line_start(cursor, pos.y);\n }\n } else {\n // `goto_visual()` can only seek forward, so we need to seek backward here if needed.\n // NOTE that this intentionally doesn't use the `Eq` trait of `Point`, because if\n // `pos.y == cursor.visual_pos.y` we don't need to go to `cursor.logical_pos.y - 1`.\n while pos.y < cursor.visual_pos.y {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y - 1);\n }\n if pos.y == cursor.visual_pos.y && pos.x < cursor.visual_pos.x {\n cursor = self.goto_line_start(cursor, cursor.logical_pos.y);\n }\n }\n\n self.measurement_config().with_cursor(cursor).goto_visual(pos)\n }\n\n fn cursor_move_delta_internal(\n &self,\n mut cursor: Cursor,\n granularity: CursorMovement,\n mut delta: CoordType,\n ) -> Cursor {\n if delta == 0 {\n return cursor;\n }\n\n let sign = if delta > 0 { 1 } else { -1 };\n\n match granularity {\n CursorMovement::Grapheme => {\n let start_x = if delta > 0 { 0 } else { CoordType::MAX };\n\n loop {\n let target_x = cursor.logical_pos.x + delta;\n\n cursor = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: target_x, y: cursor.logical_pos.y },\n );\n\n // We can stop if we ran out of remaining delta\n // (or perhaps ran past the goal; in either case the sign would've changed),\n // or if we hit the beginning or end of the buffer.\n delta = target_x - cursor.logical_pos.x;\n if delta.signum() != sign\n || (delta < 0 && cursor.offset == 0)\n || (delta > 0 && cursor.offset >= self.text_length())\n {\n break;\n }\n\n cursor = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: start_x, y: cursor.logical_pos.y + sign },\n );\n\n // We crossed a newline which counts for 1 grapheme cluster.\n // So, we also need to run the same check again.\n delta -= sign;\n if delta.signum() != sign\n || cursor.offset == 0\n || cursor.offset >= self.text_length()\n {\n break;\n }\n }\n }\n CursorMovement::Word => {\n let doc = &self.buffer as &dyn ReadableDocument;\n let mut offset = self.cursor.offset;\n\n while delta != 0 {\n if delta < 0 {\n offset = navigation::word_backward(doc, offset);\n } else {\n offset = navigation::word_forward(doc, offset);\n }\n delta -= sign;\n }\n\n cursor = self.cursor_move_to_offset_internal(cursor, offset);\n }\n }\n\n cursor\n }\n\n /// Moves the cursor to the given offset.\n pub fn cursor_move_to_offset(&mut self, offset: usize) {\n unsafe { self.set_cursor(self.cursor_move_to_offset_internal(self.cursor, offset)) }\n }\n\n /// Moves the cursor to the given logical position.\n pub fn cursor_move_to_logical(&mut self, pos: Point) {\n unsafe { self.set_cursor(self.cursor_move_to_logical_internal(self.cursor, pos)) }\n }\n\n /// Moves the cursor to the given visual position.\n pub fn cursor_move_to_visual(&mut self, pos: Point) {\n unsafe { self.set_cursor(self.cursor_move_to_visual_internal(self.cursor, pos)) }\n }\n\n /// Moves the cursor by the given delta.\n pub fn cursor_move_delta(&mut self, granularity: CursorMovement, delta: CoordType) {\n unsafe { self.set_cursor(self.cursor_move_delta_internal(self.cursor, granularity, delta)) }\n }\n\n /// Sets the cursor to the given position, and clears the selection.\n ///\n /// # Safety\n ///\n /// This function performs no checks that the cursor is valid. \"Valid\" in this case means\n /// that the TextBuffer has not been modified since you received the cursor from this class.\n pub unsafe fn set_cursor(&mut self, cursor: Cursor) {\n self.set_cursor_internal(cursor);\n self.last_history_type = HistoryType::Other;\n self.set_selection(None);\n }\n\n fn set_cursor_for_selection(&mut self, cursor: Cursor) {\n let beg = match self.selection {\n Some(TextBufferSelection { beg, .. }) => beg,\n None => self.cursor.logical_pos,\n };\n\n self.set_cursor_internal(cursor);\n self.last_history_type = HistoryType::Other;\n\n let end = self.cursor.logical_pos;\n self.set_selection(if beg == end { None } else { Some(TextBufferSelection { beg, end }) });\n }\n\n fn set_cursor_internal(&mut self, cursor: Cursor) {\n debug_assert!(\n cursor.offset <= self.text_length()\n && cursor.logical_pos.x >= 0\n && cursor.logical_pos.y >= 0\n && cursor.logical_pos.y <= self.stats.logical_lines\n && cursor.visual_pos.x >= 0\n && (self.word_wrap_column <= 0 || cursor.visual_pos.x <= self.word_wrap_column)\n && cursor.visual_pos.y >= 0\n && cursor.visual_pos.y <= self.stats.visual_lines\n );\n self.cursor = cursor;\n }\n\n /// Extracts a rectangular region of the text buffer and writes it to the framebuffer.\n /// The `destination` rect is framebuffer coordinates. The extracted region within this\n /// text buffer has the given `origin` and the same size as the `destination` rect.\n pub fn render(\n &mut self,\n origin: Point,\n destination: Rect,\n focused: bool,\n fb: &mut Framebuffer,\n ) -> Option {\n if destination.is_empty() {\n return None;\n }\n\n let scratch = scratch_arena(None);\n let width = destination.width();\n let height = destination.height();\n let line_number_width = self.margin_width.max(3) as usize - 3;\n let text_width = width - self.margin_width;\n let mut visualizer_buf = [0xE2, 0x90, 0x80]; // U+2400 in UTF8\n let mut line = ArenaString::new_in(&scratch);\n let mut visual_pos_x_max = 0;\n\n // Pick the cursor closer to the `origin.y`.\n let mut cursor = {\n let a = self.cursor;\n let b = self.cursor_for_rendering.unwrap_or_default();\n let da = (a.visual_pos.y - origin.y).abs();\n let db = (b.visual_pos.y - origin.y).abs();\n if da < db { a } else { b }\n };\n\n let [selection_beg, selection_end] = match self.selection {\n None => [Point::MIN, Point::MIN],\n Some(TextBufferSelection { beg, end }) => minmax(beg, end),\n };\n\n line.reserve(width as usize * 2);\n\n for y in 0..height {\n line.clear();\n\n let visual_line = origin.y + y;\n let mut cursor_beg =\n self.cursor_move_to_visual_internal(cursor, Point { x: origin.x, y: visual_line });\n let cursor_end = self.cursor_move_to_visual_internal(\n cursor_beg,\n Point { x: origin.x + text_width, y: visual_line },\n );\n\n // Accelerate the next render pass by remembering where we started off.\n if y == 0 {\n self.cursor_for_rendering = Some(cursor_beg);\n }\n\n if line_number_width != 0 {\n if visual_line >= self.stats.visual_lines {\n // Past the end of the buffer? Place \" | \" in the margin.\n // Since we know that we won't see line numbers greater than i64::MAX (9223372036854775807)\n // any time soon, we can use a static string as the template (`MARGIN`) and slice it,\n // because `line_number_width` can't possibly be larger than 19.\n let off = 19 - line_number_width;\n unsafe { std::hint::assert_unchecked(off < MARGIN_TEMPLATE.len()) };\n line.push_str(&MARGIN_TEMPLATE[off..]);\n } else if self.word_wrap_column <= 0 || cursor_beg.logical_pos.x == 0 {\n // Regular line? Place \"123 | \" in the margin.\n _ = write!(line, \"{:1$} │ \", cursor_beg.logical_pos.y + 1, line_number_width);\n } else {\n // Wrapped line? Place \" ... | \" in the margin.\n let number_width = (cursor_beg.logical_pos.y + 1).ilog10() as usize + 1;\n _ = write!(\n line,\n \"{0:1$}{0:∙<2$} │ \",\n \"\",\n line_number_width - number_width,\n number_width\n );\n // Blending in the background color will \"dim\" the indicator dots.\n let left = destination.left;\n let top = destination.top + y;\n fb.blend_fg(\n Rect {\n left,\n top,\n right: left + line_number_width as CoordType,\n bottom: top + 1,\n },\n fb.indexed_alpha(IndexedColor::Background, 1, 2),\n );\n }\n }\n\n let mut selection_off = 0..0;\n\n // Figure out the selection range on this line, if any.\n if cursor_beg.visual_pos.y == visual_line\n && selection_beg <= cursor_end.logical_pos\n && selection_end >= cursor_beg.logical_pos\n {\n let mut cursor = cursor_beg;\n\n // By default, we assume the entire line is selected.\n let mut selection_pos_beg = 0;\n let mut selection_pos_end = COORD_TYPE_SAFE_MAX;\n selection_off.start = cursor_beg.offset;\n selection_off.end = cursor_end.offset;\n\n // The start of the selection is within this line. We need to update selection_beg.\n if selection_beg <= cursor_end.logical_pos\n && selection_beg >= cursor_beg.logical_pos\n {\n cursor = self.cursor_move_to_logical_internal(cursor, selection_beg);\n selection_off.start = cursor.offset;\n selection_pos_beg = cursor.visual_pos.x;\n }\n\n // The end of the selection is within this line. We need to update selection_end.\n if selection_end <= cursor_end.logical_pos\n && selection_end >= cursor_beg.logical_pos\n {\n cursor = self.cursor_move_to_logical_internal(cursor, selection_end);\n selection_off.end = cursor.offset;\n selection_pos_end = cursor.visual_pos.x;\n }\n\n let left = destination.left + self.margin_width - origin.x;\n let top = destination.top + y;\n let rect = Rect {\n left: left + selection_pos_beg.max(origin.x),\n top,\n right: left + selection_pos_end.min(origin.x + text_width),\n bottom: top + 1,\n };\n\n let mut bg = oklab_blend(\n fb.indexed(IndexedColor::Foreground),\n fb.indexed_alpha(IndexedColor::BrightBlue, 1, 2),\n );\n if !focused {\n bg = oklab_blend(bg, fb.indexed_alpha(IndexedColor::Background, 1, 2))\n };\n let fg = fb.contrasted(bg);\n fb.blend_bg(rect, bg);\n fb.blend_fg(rect, fg);\n }\n\n // Nothing to do if the entire line is empty.\n if cursor_beg.offset != cursor_end.offset {\n // If we couldn't reach the left edge, we may have stopped short due to a wide glyph.\n // In that case we'll try to find the next character and then compute by how many\n // columns it overlaps the left edge (can be anything between 1 and 7).\n if cursor_beg.visual_pos.x < origin.x {\n let cursor_next = self.cursor_move_to_logical_internal(\n cursor_beg,\n Point { x: cursor_beg.logical_pos.x + 1, y: cursor_beg.logical_pos.y },\n );\n\n if cursor_next.visual_pos.x > origin.x {\n let overlap = cursor_next.visual_pos.x - origin.x;\n debug_assert!((1..=7).contains(&overlap));\n line.push_str(&TAB_WHITESPACE[..overlap as usize]);\n cursor_beg = cursor_next;\n }\n }\n\n let mut global_off = cursor_beg.offset;\n let mut cursor_line = cursor_beg;\n\n while global_off < cursor_end.offset {\n let chunk = self.read_forward(global_off);\n let chunk = &chunk[..chunk.len().min(cursor_end.offset - global_off)];\n let mut it = Utf8Chars::new(chunk, 0);\n\n // TODO: Looping char-by-char is bad for performance.\n // >25% of the total rendering time is spent here.\n loop {\n let chunk_off = it.offset();\n let global_off = global_off + chunk_off;\n let Some(ch) = it.next() else {\n break;\n };\n\n if ch == ' ' || ch == '\\t' {\n let is_tab = ch == '\\t';\n let visualize = selection_off.contains(&global_off);\n let mut whitespace = TAB_WHITESPACE;\n let mut prefix_add = 0;\n\n if is_tab || visualize {\n // We need the character's visual position in order to either compute the tab size,\n // or set the foreground color of the visualizer, respectively.\n // TODO: Doing this char-by-char is of course also bad for performance.\n cursor_line =\n self.cursor_move_to_offset_internal(cursor_line, global_off);\n }\n\n let tab_size =\n if is_tab { self.tab_size_eval(cursor_line.column) } else { 1 };\n\n if visualize {\n // If the whitespace is part of the selection,\n // we replace \" \" with \"・\" and \"\\t\" with \"→\".\n (whitespace, prefix_add) = if is_tab {\n (VISUAL_TAB, VISUAL_TAB_PREFIX_ADD)\n } else {\n (VISUAL_SPACE, VISUAL_SPACE_PREFIX_ADD)\n };\n\n // Make the visualized characters slightly gray.\n let visualizer_rect = {\n let left = destination.left\n + self.margin_width\n + cursor_line.visual_pos.x\n - origin.x;\n let top = destination.top + cursor_line.visual_pos.y - origin.y;\n Rect { left, top, right: left + 1, bottom: top + 1 }\n };\n fb.blend_fg(\n visualizer_rect,\n fb.indexed_alpha(IndexedColor::Foreground, 1, 2),\n );\n }\n\n line.push_str(&whitespace[..prefix_add + tab_size as usize]);\n } else if ch <= '\\x1f' || ('\\u{7f}'..='\\u{9f}').contains(&ch) {\n // Append a Unicode representation of the C0 or C1 control character.\n visualizer_buf[2] = if ch <= '\\x1f' {\n 0x80 | ch as u8 // U+2400..=U+241F\n } else if ch == '\\x7f' {\n 0xA1 // U+2421\n } else {\n 0xA6 // U+2426, because there are no pictures for C1 control characters.\n };\n\n // Our manually constructed UTF8 is never going to be invalid. Trust.\n line.push_str(unsafe { str::from_utf8_unchecked(&visualizer_buf) });\n\n // Highlight the control character yellow.\n cursor_line =\n self.cursor_move_to_offset_internal(cursor_line, global_off);\n let visualizer_rect = {\n let left =\n destination.left + self.margin_width + cursor_line.visual_pos.x\n - origin.x;\n let top = destination.top + cursor_line.visual_pos.y - origin.y;\n Rect { left, top, right: left + 1, bottom: top + 1 }\n };\n let bg = fb.indexed(IndexedColor::Yellow);\n let fg = fb.contrasted(bg);\n fb.blend_bg(visualizer_rect, bg);\n fb.blend_fg(visualizer_rect, fg);\n } else {\n line.push(ch);\n }\n }\n\n global_off += chunk.len();\n }\n\n visual_pos_x_max = visual_pos_x_max.max(cursor_end.visual_pos.x);\n }\n\n fb.replace_text(destination.top + y, destination.left, destination.right, &line);\n\n cursor = cursor_end;\n }\n\n // Colorize the margin that we wrote above.\n if self.margin_width > 0 {\n let margin = Rect {\n left: destination.left,\n top: destination.top,\n right: destination.left + self.margin_width,\n bottom: destination.bottom,\n };\n fb.blend_fg(margin, 0x7f3f3f3f);\n }\n\n if self.ruler > 0 {\n let left = destination.left + self.margin_width + (self.ruler - origin.x).max(0);\n let right = destination.right;\n if left < right {\n fb.blend_bg(\n Rect { left, top: destination.top, right, bottom: destination.bottom },\n fb.indexed_alpha(IndexedColor::BrightRed, 1, 4),\n );\n }\n }\n\n if focused {\n let mut x = self.cursor.visual_pos.x;\n let mut y = self.cursor.visual_pos.y;\n\n if self.word_wrap_column > 0 && x >= self.word_wrap_column {\n // The line the cursor is on wraps exactly on the word wrap column which\n // means the cursor is invisible. We need to move it to the next line.\n x = 0;\n y += 1;\n }\n\n // Move the cursor into screen space.\n x += destination.left - origin.x + self.margin_width;\n y += destination.top - origin.y;\n\n let cursor = Point { x, y };\n let text = Rect {\n left: destination.left + self.margin_width,\n top: destination.top,\n right: destination.right,\n bottom: destination.bottom,\n };\n\n if text.contains(cursor) {\n fb.set_cursor(cursor, self.overtype);\n\n if self.line_highlight_enabled && selection_beg >= selection_end {\n fb.blend_bg(\n Rect {\n left: destination.left,\n top: cursor.y,\n right: destination.right,\n bottom: cursor.y + 1,\n },\n 0x50282828,\n );\n }\n }\n }\n\n Some(RenderResult { visual_pos_x_max })\n }\n\n pub fn cut(&mut self, clipboard: &mut Clipboard) {\n self.cut_copy(clipboard, true);\n }\n\n pub fn copy(&mut self, clipboard: &mut Clipboard) {\n self.cut_copy(clipboard, false);\n }\n\n fn cut_copy(&mut self, clipboard: &mut Clipboard, cut: bool) {\n let line_copy = !self.has_selection();\n let selection = self.extract_selection(cut);\n clipboard.write(selection);\n clipboard.write_was_line_copy(line_copy);\n }\n\n pub fn paste(&mut self, clipboard: &Clipboard) {\n let data = clipboard.read();\n if data.is_empty() {\n return;\n }\n\n let pos = self.cursor_logical_pos();\n let at = if clipboard.is_line_copy() {\n self.goto_line_start(self.cursor, pos.y)\n } else {\n self.cursor\n };\n\n self.write(data, at, true);\n\n if clipboard.is_line_copy() {\n self.cursor_move_to_logical(Point { x: pos.x, y: pos.y + 1 });\n }\n }\n\n /// Inserts the user input `text` at the current cursor position.\n /// Replaces tabs with whitespace if needed, etc.\n pub fn write_canon(&mut self, text: &[u8]) {\n self.write(text, self.cursor, false);\n }\n\n /// Inserts `text` as-is at the current cursor position.\n /// The only transformation applied is that newlines are normalized.\n pub fn write_raw(&mut self, text: &[u8]) {\n self.write(text, self.cursor, true);\n }\n\n fn write(&mut self, text: &[u8], at: Cursor, raw: bool) {\n let history_type = if raw { HistoryType::Other } else { HistoryType::Write };\n let mut edit_begun = false;\n\n // If we have an active selection, writing an empty `text`\n // will still delete the selection. As such, we check this first.\n if let Some((beg, end)) = self.selection_range_internal(false) {\n self.edit_begin(history_type, beg);\n self.edit_delete(end);\n self.set_selection(None);\n edit_begun = true;\n }\n\n // If the text is empty the remaining code won't do anything,\n // allowing us to exit early.\n if text.is_empty() {\n // ...we still need to end any active edit session though.\n if edit_begun {\n self.edit_end();\n }\n return;\n }\n\n if !edit_begun {\n self.edit_begin(history_type, at);\n }\n\n let mut offset = 0;\n let scratch = scratch_arena(None);\n let mut newline_buffer = ArenaString::new_in(&scratch);\n\n loop {\n // Can't use `unicode::newlines_forward` because bracketed paste uses CR instead of LF/CRLF.\n let offset_next = memchr2(b'\\r', b'\\n', text, offset);\n let line = &text[offset..offset_next];\n let column_before = self.cursor.logical_pos.x;\n\n // Write the contents of the line into the buffer.\n let mut line_off = 0;\n while line_off < line.len() {\n // Split the line into chunks of non-tabs and tabs.\n let mut plain = line;\n if !raw && !self.indent_with_tabs {\n let end = memchr2(b'\\t', b'\\t', line, line_off);\n plain = &line[line_off..end];\n }\n\n // Non-tabs are written as-is, because the outer loop already handles newline translation.\n self.edit_write(plain);\n line_off += plain.len();\n\n // Now replace tabs with spaces.\n while line_off < line.len() && line[line_off] == b'\\t' {\n let spaces = self.tab_size_eval(self.cursor.column);\n let spaces = &TAB_WHITESPACE.as_bytes()[..spaces as usize];\n self.edit_write(spaces);\n line_off += 1;\n }\n }\n\n if !raw && self.overtype {\n let delete = self.cursor.logical_pos.x - column_before;\n let end = self.cursor_move_to_logical_internal(\n self.cursor,\n Point { x: self.cursor.logical_pos.x + delete, y: self.cursor.logical_pos.y },\n );\n self.edit_delete(end);\n }\n\n offset += line.len();\n if offset >= text.len() {\n break;\n }\n\n // First, write the newline.\n newline_buffer.clear();\n newline_buffer.push_str(if self.newlines_are_crlf { \"\\r\\n\" } else { \"\\n\" });\n\n if !raw {\n // We'll give the next line the same indentation as the previous one.\n // This block figures out how much that is. We can't reuse that value,\n // because \" a\\n a\\n\" should give the 3rd line a total indentation of 4.\n // Assuming your terminal has bracketed paste, this won't be a concern though.\n // (If it doesn't, use a different terminal.)\n let line_beg = self.goto_line_start(self.cursor, self.cursor.logical_pos.y);\n let limit = self.cursor.offset;\n let mut off = line_beg.offset;\n let mut newline_indentation = 0;\n\n 'outer: while off < limit {\n let chunk = self.read_forward(off);\n let chunk = &chunk[..chunk.len().min(limit - off)];\n\n for &c in chunk {\n if c == b' ' {\n newline_indentation += 1;\n } else if c == b'\\t' {\n newline_indentation += self.tab_size_eval(newline_indentation);\n } else {\n break 'outer;\n }\n }\n\n off += chunk.len();\n }\n\n // If tabs are enabled, add as many tabs as we can.\n if self.indent_with_tabs {\n let tab_count = newline_indentation / self.tab_size;\n newline_buffer.push_repeat('\\t', tab_count as usize);\n newline_indentation -= tab_count * self.tab_size;\n }\n\n // If tabs are disabled, or if the indentation wasn't a multiple of the tab size,\n // add spaces to make up the difference.\n newline_buffer.push_repeat(' ', newline_indentation as usize);\n }\n\n self.edit_write(newline_buffer.as_bytes());\n\n // Skip one CR/LF/CRLF.\n if offset >= text.len() {\n break;\n }\n if text[offset] == b'\\r' {\n offset += 1;\n }\n if offset >= text.len() {\n break;\n }\n if text[offset] == b'\\n' {\n offset += 1;\n }\n if offset >= text.len() {\n break;\n }\n }\n\n // POSIX mandates that all valid lines end in a newline.\n // This isn't all that common on Windows and so we have\n // `self.final_newline` to control this.\n //\n // In order to not annoy people with this, we only add a\n // newline if you just edited the very end of the buffer.\n if self.insert_final_newline\n && self.cursor.offset > 0\n && self.cursor.offset == self.text_length()\n && self.cursor.logical_pos.x > 0\n {\n let cursor = self.cursor;\n self.edit_write(if self.newlines_are_crlf { b\"\\r\\n\" } else { b\"\\n\" });\n self.set_cursor_internal(cursor);\n }\n\n self.edit_end();\n }\n\n /// Deletes 1 grapheme cluster from the buffer.\n /// `cursor_movements` is expected to be -1 for backspace and 1 for delete.\n /// If there's a current selection, it will be deleted and `cursor_movements` ignored.\n /// The selection is cleared after the call.\n /// Deletes characters from the buffer based on a delta from the cursor.\n pub fn delete(&mut self, granularity: CursorMovement, delta: CoordType) {\n if delta == 0 {\n return;\n }\n\n let mut beg;\n let mut end;\n\n if let Some(r) = self.selection_range_internal(false) {\n (beg, end) = r;\n } else {\n if (delta < 0 && self.cursor.offset == 0)\n || (delta > 0 && self.cursor.offset >= self.text_length())\n {\n // Nothing to delete.\n return;\n }\n\n beg = self.cursor;\n end = self.cursor_move_delta_internal(beg, granularity, delta);\n if beg.offset == end.offset {\n return;\n }\n if beg.offset > end.offset {\n mem::swap(&mut beg, &mut end);\n }\n }\n\n self.edit_begin(HistoryType::Delete, beg);\n self.edit_delete(end);\n self.edit_end();\n\n self.set_selection(None);\n }\n\n /// Returns the logical position of the first character on this line.\n /// Return `.x == 0` if there are no non-whitespace characters.\n pub fn indent_end_logical_pos(&self) -> Point {\n let cursor = self.goto_line_start(self.cursor, self.cursor.logical_pos.y);\n let (chars, _) = self.measure_indent_internal(cursor.offset, CoordType::MAX);\n Point { x: chars, y: cursor.logical_pos.y }\n }\n\n /// Indents/unindents the current selection or line.\n pub fn indent_change(&mut self, direction: CoordType) {\n let selection = self.selection;\n let mut selection_beg = self.cursor.logical_pos;\n let mut selection_end = selection_beg;\n\n if let Some(TextBufferSelection { beg, end }) = &selection {\n selection_beg = *beg;\n selection_end = *end;\n }\n\n if direction >= 0 && self.selection.is_none_or(|sel| sel.beg.y == sel.end.y) {\n self.write_canon(b\"\\t\");\n return;\n }\n\n self.edit_begin_grouping();\n\n for y in selection_beg.y.min(selection_end.y)..=selection_beg.y.max(selection_end.y) {\n self.cursor_move_to_logical(Point { x: 0, y });\n\n let line_start_offset = self.cursor.offset;\n let (curr_chars, curr_columns) =\n self.measure_indent_internal(line_start_offset, CoordType::MAX);\n\n self.cursor_move_to_logical(Point { x: curr_chars, y: self.cursor.logical_pos.y });\n\n let delta;\n\n if direction < 0 {\n // Unindent the line. If there's no indentation, skip.\n if curr_columns <= 0 {\n continue;\n }\n\n let (prev_chars, _) = self.measure_indent_internal(\n line_start_offset,\n self.tab_size_prev_column(curr_columns),\n );\n\n delta = prev_chars - curr_chars;\n self.delete(CursorMovement::Grapheme, delta);\n } else {\n // Indent the line. `self.cursor` is already at the level of indentation.\n delta = self.tab_size_eval(curr_columns);\n self.write_canon(b\"\\t\");\n }\n\n // As the lines get unindented, the selection should shift with them.\n if y == selection_beg.y {\n selection_beg.x += delta;\n }\n if y == selection_end.y {\n selection_end.x += delta;\n }\n }\n self.edit_end_grouping();\n\n // Move the cursor to the new end of the selection.\n self.set_cursor_internal(self.cursor_move_to_logical_internal(self.cursor, selection_end));\n\n // NOTE: If the selection was previously `None`,\n // it should continue to be `None` after this.\n self.set_selection(\n selection.map(|_| TextBufferSelection { beg: selection_beg, end: selection_end }),\n );\n }\n\n fn measure_indent_internal(\n &self,\n mut offset: usize,\n max_columns: CoordType,\n ) -> (CoordType, CoordType) {\n let mut chars = 0;\n let mut columns = 0;\n\n 'outer: loop {\n let chunk = self.read_forward(offset);\n if chunk.is_empty() {\n break;\n }\n\n for &c in chunk {\n let next = match c {\n b' ' => columns + 1,\n b'\\t' => columns + self.tab_size_eval(columns),\n _ => break 'outer,\n };\n if next > max_columns {\n break 'outer;\n }\n chars += 1;\n columns = next;\n }\n\n offset += chunk.len();\n\n // No need to do another round if we\n // already got the exact right amount.\n if columns >= max_columns {\n break;\n }\n }\n\n (chars, columns)\n }\n\n /// Displaces the current, cursor or the selection, line(s) in the given direction.\n pub fn move_selected_lines(&mut self, direction: MoveLineDirection) {\n let selection = self.selection;\n let cursor = self.cursor;\n\n // If there's no selection, we move the line the cursor is on instead.\n let [beg, end] = match self.selection {\n Some(s) => minmax(s.beg.y, s.end.y),\n None => [cursor.logical_pos.y, cursor.logical_pos.y],\n };\n\n // Check if this would be a no-op.\n if match direction {\n MoveLineDirection::Up => beg <= 0,\n MoveLineDirection::Down => end >= self.stats.logical_lines - 1,\n } {\n return;\n }\n\n let delta = match direction {\n MoveLineDirection::Up => -1,\n MoveLineDirection::Down => 1,\n };\n let (cut, paste) = match direction {\n MoveLineDirection::Up => (beg - 1, end),\n MoveLineDirection::Down => (end + 1, beg),\n };\n\n self.edit_begin_grouping();\n {\n // Let's say this is `MoveLineDirection::Up`.\n // In that case, we'll cut (remove) the line above the selection here...\n self.cursor_move_to_logical(Point { x: 0, y: cut });\n let line = self.extract_selection(true);\n\n // ...and paste it below the selection. This will then\n // appear to the user as if the selection was moved up.\n self.cursor_move_to_logical(Point { x: 0, y: paste });\n self.edit_begin(HistoryType::Write, self.cursor);\n // The `extract_selection` call can return an empty `Vec`),\n // if the `cut` line was at the end of the file. Since we want to\n // paste the line somewhere it needs a trailing newline at the minimum.\n //\n // Similarly, if the `paste` line is at the end of the file\n // and there's no trailing newline, we'll have failed to reach\n // that end in which case `logical_pos.y != past`.\n if line.is_empty() || self.cursor.logical_pos.y != paste {\n self.write_canon(b\"\\n\");\n }\n if !line.is_empty() {\n self.write_raw(&line);\n }\n self.edit_end();\n }\n self.edit_end_grouping();\n\n // Shift the cursor and selection together with the moved lines.\n self.cursor_move_to_logical(Point {\n x: cursor.logical_pos.x,\n y: cursor.logical_pos.y + delta,\n });\n self.set_selection(selection.map(|mut s| {\n s.beg.y += delta;\n s.end.y += delta;\n s\n }));\n }\n\n /// Extracts the contents of the current selection.\n /// May optionally delete it, if requested. This is meant to be used for Ctrl+X.\n fn extract_selection(&mut self, delete: bool) -> Vec {\n let line_copy = !self.has_selection();\n let Some((beg, end)) = self.selection_range_internal(true) else {\n return Vec::new();\n };\n\n let mut out = Vec::new();\n self.buffer.extract_raw(beg.offset..end.offset, &mut out, 0);\n\n if delete && !out.is_empty() {\n self.edit_begin(HistoryType::Delete, beg);\n self.edit_delete(end);\n self.edit_end();\n self.set_selection(None);\n }\n\n // Line copies (= Ctrl+C when there's no selection) always end with a newline.\n if line_copy && !out.ends_with(b\"\\n\") {\n out.replace_range(out.len().., if self.newlines_are_crlf { b\"\\r\\n\" } else { b\"\\n\" });\n }\n\n out\n }\n\n /// Extracts the contents of the current selection the user made.\n /// This differs from [`TextBuffer::extract_selection()`] in that\n /// it does nothing if the selection was made by searching.\n pub fn extract_user_selection(&mut self, delete: bool) -> Option> {\n if !self.has_selection() {\n return None;\n }\n\n if let Some(search) = &self.search {\n let search = unsafe { &*search.get() };\n if search.selection_generation == self.selection_generation {\n return None;\n }\n }\n\n Some(self.extract_selection(delete))\n }\n\n /// Returns the current selection anchors, or `None` if there\n /// is no selection. The returned logical positions are sorted.\n pub fn selection_range(&self) -> Option<(Cursor, Cursor)> {\n self.selection_range_internal(false)\n }\n\n /// Returns the current selection anchors.\n ///\n /// If there's no selection and `line_fallback` is `true`,\n /// the start/end of the current line are returned.\n /// This is meant to be used for Ctrl+C / Ctrl+X.\n fn selection_range_internal(&self, line_fallback: bool) -> Option<(Cursor, Cursor)> {\n let [beg, end] = match self.selection {\n None if !line_fallback => return None,\n None => [\n Point { x: 0, y: self.cursor.logical_pos.y },\n Point { x: 0, y: self.cursor.logical_pos.y + 1 },\n ],\n Some(TextBufferSelection { beg, end }) => minmax(beg, end),\n };\n\n let beg = self.cursor_move_to_logical_internal(self.cursor, beg);\n let end = self.cursor_move_to_logical_internal(beg, end);\n\n if beg.offset < end.offset { Some((beg, end)) } else { None }\n }\n\n fn edit_begin_grouping(&mut self) {\n self.active_edit_group = Some(ActiveEditGroupInfo {\n cursor_before: self.cursor.logical_pos,\n selection_before: self.selection,\n stats_before: self.stats,\n generation_before: self.buffer.generation(),\n });\n }\n\n fn edit_end_grouping(&mut self) {\n self.active_edit_group = None;\n }\n\n /// Starts a new edit operation.\n /// This is used for tracking the undo/redo history.\n fn edit_begin(&mut self, history_type: HistoryType, cursor: Cursor) {\n self.active_edit_depth += 1;\n if self.active_edit_depth > 1 {\n return;\n }\n\n let cursor_before = self.cursor;\n self.set_cursor_internal(cursor);\n\n // If both the last and this are a Write/Delete operation, we skip allocating a new undo history item.\n if cursor_before.offset != cursor.offset\n || history_type != self.last_history_type\n || !matches!(history_type, HistoryType::Write | HistoryType::Delete)\n {\n self.redo_stack.clear();\n while self.undo_stack.len() > 1000 {\n self.undo_stack.pop_front();\n }\n\n self.last_history_type = history_type;\n self.undo_stack.push_back(SemiRefCell::new(HistoryEntry {\n cursor_before: cursor_before.logical_pos,\n selection_before: self.selection,\n stats_before: self.stats,\n generation_before: self.buffer.generation(),\n cursor: cursor.logical_pos,\n deleted: Vec::new(),\n added: Vec::new(),\n }));\n\n if let Some(info) = &self.active_edit_group\n && let Some(entry) = self.undo_stack.back()\n {\n let mut entry = entry.borrow_mut();\n entry.cursor_before = info.cursor_before;\n entry.selection_before = info.selection_before;\n entry.stats_before = info.stats_before;\n entry.generation_before = info.generation_before;\n }\n }\n\n self.active_edit_off = cursor.offset;\n\n // If word-wrap is enabled, the visual layout of all logical lines affected by the write\n // may have changed. This includes even text before the insertion point up to the line\n // start, because this write may have joined with a word before the initial cursor.\n // See other uses of `word_wrap_cursor_next_line` in this function.\n if self.word_wrap_column > 0 {\n let safe_start = self.goto_line_start(cursor, cursor.logical_pos.y);\n let next_line = self.cursor_move_to_logical_internal(\n cursor,\n Point { x: 0, y: cursor.logical_pos.y + 1 },\n );\n self.active_edit_line_info = Some(ActiveEditLineInfo {\n safe_start,\n line_height_in_rows: next_line.visual_pos.y - safe_start.visual_pos.y,\n distance_next_line_start: next_line.offset - cursor.offset,\n });\n }\n }\n\n /// Writes `text` into the buffer at the current cursor position.\n /// It records the change in the undo stack.\n fn edit_write(&mut self, text: &[u8]) {\n let logical_y_before = self.cursor.logical_pos.y;\n\n // Copy the written portion into the undo entry.\n {\n let mut undo = self.undo_stack.back_mut().unwrap().borrow_mut();\n undo.added.extend_from_slice(text);\n }\n\n // Write!\n self.buffer.replace(self.active_edit_off..self.active_edit_off, text);\n\n // Move self.cursor to the end of the newly written text. Can't use `self.set_cursor_internal`,\n // because we're still in the progress of recalculating the line stats.\n self.active_edit_off += text.len();\n self.cursor = self.cursor_move_to_offset_internal(self.cursor, self.active_edit_off);\n self.stats.logical_lines += self.cursor.logical_pos.y - logical_y_before;\n }\n\n /// Deletes the text between the current cursor position and `to`.\n /// It records the change in the undo stack.\n fn edit_delete(&mut self, to: Cursor) {\n debug_assert!(to.offset >= self.active_edit_off);\n\n let logical_y_before = self.cursor.logical_pos.y;\n let off = self.active_edit_off;\n let mut out_off = usize::MAX;\n\n let mut undo = self.undo_stack.back_mut().unwrap().borrow_mut();\n\n // If this is a continued backspace operation,\n // we need to prepend the deleted portion to the undo entry.\n if self.cursor.logical_pos < undo.cursor {\n out_off = 0;\n undo.cursor = self.cursor.logical_pos;\n }\n\n // Copy the deleted portion into the undo entry.\n let deleted = &mut undo.deleted;\n self.buffer.extract_raw(off..to.offset, deleted, out_off);\n\n // Delete the portion from the buffer by enlarging the gap.\n let count = to.offset - off;\n self.buffer.allocate_gap(off, 0, count);\n\n self.stats.logical_lines += logical_y_before - to.logical_pos.y;\n }\n\n /// Finalizes the current edit operation\n /// and recalculates the line statistics.\n fn edit_end(&mut self) {\n self.active_edit_depth -= 1;\n debug_assert!(self.active_edit_depth >= 0);\n if self.active_edit_depth > 0 {\n return;\n }\n\n #[cfg(debug_assertions)]\n {\n let entry = self.undo_stack.back_mut().unwrap().borrow_mut();\n debug_assert!(!entry.deleted.is_empty() || !entry.added.is_empty());\n }\n\n if let Some(info) = self.active_edit_line_info.take() {\n let deleted_count = self.undo_stack.back_mut().unwrap().borrow_mut().deleted.len();\n let target = self.cursor.logical_pos;\n\n // From our safe position we can measure the actual visual position of the cursor.\n self.set_cursor_internal(self.cursor_move_to_logical_internal(info.safe_start, target));\n\n // If content is added at the insertion position, that's not a problem:\n // We can just remeasure the height of this one line and calculate the delta.\n // `deleted_count` is 0 in this case.\n //\n // The problem is when content is deleted, because it may affect lines\n // beyond the end of the `next_line`. In that case we have to measure\n // the entire buffer contents until the end to compute `self.stats.visual_lines`.\n if deleted_count < info.distance_next_line_start {\n // Now we can measure how many more visual rows this logical line spans.\n let next_line = self\n .cursor_move_to_logical_internal(self.cursor, Point { x: 0, y: target.y + 1 });\n let lines_before = info.line_height_in_rows;\n let lines_after = next_line.visual_pos.y - info.safe_start.visual_pos.y;\n self.stats.visual_lines += lines_after - lines_before;\n } else {\n let end = self.cursor_move_to_logical_internal(self.cursor, Point::MAX);\n self.stats.visual_lines = end.visual_pos.y + 1;\n }\n } else {\n // If word-wrap is disabled the visual line count always matches the logical one.\n self.stats.visual_lines = self.stats.logical_lines;\n }\n\n self.recalc_after_content_changed();\n }\n\n /// Undo the last edit operation.\n pub fn undo(&mut self) {\n self.undo_redo(true);\n }\n\n /// Redo the last undo operation.\n pub fn redo(&mut self) {\n self.undo_redo(false);\n }\n\n fn undo_redo(&mut self, undo: bool) {\n let buffer_generation = self.buffer.generation();\n let mut entry_buffer_generation = None;\n\n loop {\n // Transfer the last entry from the undo stack to the redo stack or vice versa.\n {\n let (from, to) = if undo {\n (&mut self.undo_stack, &mut self.redo_stack)\n } else {\n (&mut self.redo_stack, &mut self.undo_stack)\n };\n\n if let Some(g) = entry_buffer_generation\n && from.back().is_none_or(|c| c.borrow().generation_before != g)\n {\n break;\n }\n\n let Some(list) = from.cursor_back_mut().remove_current_as_list() else {\n break;\n };\n\n to.cursor_back_mut().splice_after(list);\n }\n\n let change = {\n let to = if undo { &self.redo_stack } else { &self.undo_stack };\n to.back().unwrap()\n };\n\n // Remember the buffer generation of the change so we can stop popping undos/redos.\n // Also, move to the point where the modification took place.\n let cursor = {\n let change = change.borrow();\n entry_buffer_generation = Some(change.generation_before);\n self.cursor_move_to_logical_internal(self.cursor, change.cursor)\n };\n\n let safe_cursor = if self.word_wrap_column > 0 {\n // If word-wrap is enabled, we need to move the cursor to the beginning of the line.\n // This is because the undo/redo operation may have changed the visual position of the cursor.\n self.goto_line_start(cursor, cursor.logical_pos.y)\n } else {\n cursor\n };\n\n {\n let mut change = change.borrow_mut();\n let change = &mut *change;\n\n // Undo: Whatever was deleted is now added and vice versa.\n mem::swap(&mut change.deleted, &mut change.added);\n\n // Delete the inserted portion.\n self.buffer.allocate_gap(cursor.offset, 0, change.deleted.len());\n\n // Reinsert the deleted portion.\n {\n let added = &change.added[..];\n let mut beg = 0;\n let mut offset = cursor.offset;\n\n while beg < added.len() {\n let (end, line) = simd::lines_fwd(added, beg, 0, 1);\n let has_newline = line != 0;\n let link = &added[beg..end];\n let line = unicode::strip_newline(link);\n let mut written;\n\n {\n let gap = self.buffer.allocate_gap(offset, line.len() + 2, 0);\n written = slice_copy_safe(gap, line);\n\n if has_newline {\n if self.newlines_are_crlf && written < gap.len() {\n gap[written] = b'\\r';\n written += 1;\n }\n if written < gap.len() {\n gap[written] = b'\\n';\n written += 1;\n }\n }\n\n self.buffer.commit_gap(written);\n }\n\n beg = end;\n offset += written;\n }\n }\n\n // Restore the previous line statistics.\n mem::swap(&mut self.stats, &mut change.stats_before);\n\n // Restore the previous selection.\n mem::swap(&mut self.selection, &mut change.selection_before);\n\n // Pretend as if the buffer was never modified.\n self.buffer.set_generation(change.generation_before);\n change.generation_before = buffer_generation;\n\n // Restore the previous cursor.\n let cursor_before =\n self.cursor_move_to_logical_internal(safe_cursor, change.cursor_before);\n change.cursor_before = self.cursor.logical_pos;\n // Can't use `set_cursor_internal` here, because we haven't updated the line stats yet.\n self.cursor = cursor_before;\n\n if self.undo_stack.is_empty() {\n self.last_history_type = HistoryType::Other;\n }\n }\n }\n\n if entry_buffer_generation.is_some() {\n self.recalc_after_content_changed();\n }\n }\n\n /// For interfacing with ICU.\n pub(crate) fn read_backward(&self, off: usize) -> &[u8] {\n self.buffer.read_backward(off)\n }\n\n /// For interfacing with ICU.\n pub fn read_forward(&self, off: usize) -> &[u8] {\n self.buffer.read_forward(off)\n }\n}\n\npub enum Bom {\n None,\n UTF8,\n UTF16LE,\n UTF16BE,\n UTF32LE,\n UTF32BE,\n GB18030,\n}\n\nconst BOM_MAX_LEN: usize = 4;\n\nfn detect_bom(bytes: &[u8]) -> Option<&'static str> {\n if bytes.len() >= 4 {\n if bytes.starts_with(b\"\\xFF\\xFE\\x00\\x00\") {\n return Some(\"UTF-32LE\");\n }\n if bytes.starts_with(b\"\\x00\\x00\\xFE\\xFF\") {\n return Some(\"UTF-32BE\");\n }\n if bytes.starts_with(b\"\\x84\\x31\\x95\\x33\") {\n return Some(\"GB18030\");\n }\n }\n if bytes.len() >= 3 && bytes.starts_with(b\"\\xEF\\xBB\\xBF\") {\n return Some(\"UTF-8\");\n }\n if bytes.len() >= 2 {\n if bytes.starts_with(b\"\\xFF\\xFE\") {\n return Some(\"UTF-16LE\");\n }\n if bytes.starts_with(b\"\\xFE\\xFF\") {\n return Some(\"UTF-16BE\");\n }\n }\n None\n}\n"], ["/edit/src/sys/windows.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ffi::{OsString, c_char, c_void};\nuse std::fmt::Write as _;\nuse std::fs::{self, File};\nuse std::mem::MaybeUninit;\nuse std::os::windows::io::{AsRawHandle as _, FromRawHandle};\nuse std::path::{Path, PathBuf};\nuse std::ptr::{self, NonNull, null, null_mut};\nuse std::{mem, time};\n\nuse windows_sys::Win32::Storage::FileSystem;\nuse windows_sys::Win32::System::Diagnostics::Debug;\nuse windows_sys::Win32::System::{Console, IO, LibraryLoader, Memory, Threading};\nuse windows_sys::Win32::{Foundation, Globalization};\nuse windows_sys::w;\n\nuse crate::apperr;\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::helpers::*;\n\nmacro_rules! w_env {\n ($s:literal) => {{\n const INPUT: &[u8] = env!($s).as_bytes();\n const OUTPUT_LEN: usize = windows_sys::core::utf16_len(INPUT) + 1;\n const OUTPUT: &[u16; OUTPUT_LEN] = {\n let mut buffer = [0; OUTPUT_LEN];\n let mut input_pos = 0;\n let mut output_pos = 0;\n while let Some((mut code_point, new_pos)) =\n windows_sys::core::decode_utf8_char(INPUT, input_pos)\n {\n input_pos = new_pos;\n if code_point <= 0xffff {\n buffer[output_pos] = code_point as u16;\n output_pos += 1;\n } else {\n code_point -= 0x10000;\n buffer[output_pos] = 0xd800 + (code_point >> 10) as u16;\n output_pos += 1;\n buffer[output_pos] = 0xdc00 + (code_point & 0x3ff) as u16;\n output_pos += 1;\n }\n }\n &{ buffer }\n };\n OUTPUT.as_ptr()\n }};\n}\n\ntype ReadConsoleInputExW = unsafe extern \"system\" fn(\n h_console_input: Foundation::HANDLE,\n lp_buffer: *mut Console::INPUT_RECORD,\n n_length: u32,\n lp_number_of_events_read: *mut u32,\n w_flags: u16,\n) -> Foundation::BOOL;\n\nunsafe extern \"system\" fn read_console_input_ex_placeholder(\n _: Foundation::HANDLE,\n _: *mut Console::INPUT_RECORD,\n _: u32,\n _: *mut u32,\n _: u16,\n) -> Foundation::BOOL {\n panic!();\n}\n\nconst CONSOLE_READ_NOWAIT: u16 = 0x0002;\n\nconst INVALID_CONSOLE_MODE: u32 = u32::MAX;\n\nstruct State {\n read_console_input_ex: ReadConsoleInputExW,\n stdin: Foundation::HANDLE,\n stdout: Foundation::HANDLE,\n stdin_cp_old: u32,\n stdout_cp_old: u32,\n stdin_mode_old: u32,\n stdout_mode_old: u32,\n leading_surrogate: u16,\n inject_resize: bool,\n wants_exit: bool,\n}\n\nstatic mut STATE: State = State {\n read_console_input_ex: read_console_input_ex_placeholder,\n stdin: null_mut(),\n stdout: null_mut(),\n stdin_cp_old: 0,\n stdout_cp_old: 0,\n stdin_mode_old: INVALID_CONSOLE_MODE,\n stdout_mode_old: INVALID_CONSOLE_MODE,\n leading_surrogate: 0,\n inject_resize: false,\n wants_exit: false,\n};\n\nextern \"system\" fn console_ctrl_handler(_ctrl_type: u32) -> Foundation::BOOL {\n unsafe {\n STATE.wants_exit = true;\n IO::CancelIoEx(STATE.stdin, null());\n }\n 1\n}\n\n/// Initializes the platform-specific state.\npub fn init() -> Deinit {\n unsafe {\n // Get the stdin and stdout handles first, so that if this function fails,\n // we at least got something to use for `write_stdout`.\n STATE.stdin = Console::GetStdHandle(Console::STD_INPUT_HANDLE);\n STATE.stdout = Console::GetStdHandle(Console::STD_OUTPUT_HANDLE);\n\n Deinit\n }\n}\n\n/// Switches the terminal into raw mode, etc.\npub fn switch_modes() -> apperr::Result<()> {\n unsafe {\n // `kernel32.dll` doesn't exist on OneCore variants of Windows.\n // NOTE: `kernelbase.dll` is NOT a stable API to rely on. In our case it's the best option though.\n //\n // This is written as two nested `match` statements so that we can return the error from the first\n // `load_read_func` call if it fails. The kernel32.dll lookup may contain some valid information,\n // while the kernelbase.dll lookup may not, since it's not a stable API.\n unsafe fn load_read_func(module: *const u16) -> apperr::Result {\n unsafe {\n get_module(module)\n .and_then(|m| get_proc_address(m, c\"ReadConsoleInputExW\".as_ptr()))\n }\n }\n STATE.read_console_input_ex = match load_read_func(w!(\"kernel32.dll\")) {\n Ok(func) => func,\n Err(err) => match load_read_func(w!(\"kernelbase.dll\")) {\n Ok(func) => func,\n Err(_) => return Err(err),\n },\n };\n\n // Reopen stdin if it's redirected (= piped input).\n if ptr::eq(STATE.stdin, Foundation::INVALID_HANDLE_VALUE)\n || !matches!(FileSystem::GetFileType(STATE.stdin), FileSystem::FILE_TYPE_CHAR)\n {\n STATE.stdin = FileSystem::CreateFileW(\n w!(\"CONIN$\"),\n Foundation::GENERIC_READ | Foundation::GENERIC_WRITE,\n FileSystem::FILE_SHARE_READ | FileSystem::FILE_SHARE_WRITE,\n null_mut(),\n FileSystem::OPEN_EXISTING,\n 0,\n null_mut(),\n );\n }\n if ptr::eq(STATE.stdin, Foundation::INVALID_HANDLE_VALUE)\n || ptr::eq(STATE.stdout, Foundation::INVALID_HANDLE_VALUE)\n {\n return Err(get_last_error());\n }\n\n check_bool_return(Console::SetConsoleCtrlHandler(Some(console_ctrl_handler), 1))?;\n\n STATE.stdin_cp_old = Console::GetConsoleCP();\n STATE.stdout_cp_old = Console::GetConsoleOutputCP();\n check_bool_return(Console::GetConsoleMode(STATE.stdin, &raw mut STATE.stdin_mode_old))?;\n check_bool_return(Console::GetConsoleMode(STATE.stdout, &raw mut STATE.stdout_mode_old))?;\n\n check_bool_return(Console::SetConsoleCP(Globalization::CP_UTF8))?;\n check_bool_return(Console::SetConsoleOutputCP(Globalization::CP_UTF8))?;\n check_bool_return(Console::SetConsoleMode(\n STATE.stdin,\n Console::ENABLE_WINDOW_INPUT\n | Console::ENABLE_EXTENDED_FLAGS\n | Console::ENABLE_VIRTUAL_TERMINAL_INPUT,\n ))?;\n check_bool_return(Console::SetConsoleMode(\n STATE.stdout,\n Console::ENABLE_PROCESSED_OUTPUT\n | Console::ENABLE_WRAP_AT_EOL_OUTPUT\n | Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING\n | Console::DISABLE_NEWLINE_AUTO_RETURN,\n ))?;\n\n Ok(())\n }\n}\n\npub struct Deinit;\n\nimpl Drop for Deinit {\n fn drop(&mut self) {\n unsafe {\n if STATE.stdin_cp_old != 0 {\n Console::SetConsoleCP(STATE.stdin_cp_old);\n STATE.stdin_cp_old = 0;\n }\n if STATE.stdout_cp_old != 0 {\n Console::SetConsoleOutputCP(STATE.stdout_cp_old);\n STATE.stdout_cp_old = 0;\n }\n if STATE.stdin_mode_old != INVALID_CONSOLE_MODE {\n Console::SetConsoleMode(STATE.stdin, STATE.stdin_mode_old);\n STATE.stdin_mode_old = INVALID_CONSOLE_MODE;\n }\n if STATE.stdout_mode_old != INVALID_CONSOLE_MODE {\n Console::SetConsoleMode(STATE.stdout, STATE.stdout_mode_old);\n STATE.stdout_mode_old = INVALID_CONSOLE_MODE;\n }\n }\n }\n}\n\n/// During startup we need to get the window size from the terminal.\n/// Because I didn't want to type a bunch of code, this function tells\n/// [`read_stdin`] to inject a fake sequence, which gets picked up by\n/// the input parser and provided to the TUI code.\npub fn inject_window_size_into_stdin() {\n unsafe {\n STATE.inject_resize = true;\n }\n}\n\nfn get_console_size() -> Option {\n unsafe {\n let mut info: Console::CONSOLE_SCREEN_BUFFER_INFOEX = mem::zeroed();\n info.cbSize = mem::size_of::() as u32;\n if Console::GetConsoleScreenBufferInfoEx(STATE.stdout, &mut info) == 0 {\n return None;\n }\n\n let w = (info.srWindow.Right - info.srWindow.Left + 1).max(1) as CoordType;\n let h = (info.srWindow.Bottom - info.srWindow.Top + 1).max(1) as CoordType;\n Some(Size { width: w, height: h })\n }\n}\n\n/// Reads from stdin.\n///\n/// # Returns\n///\n/// * `None` if there was an error reading from stdin.\n/// * `Some(\"\")` if the given timeout was reached.\n/// * Otherwise, it returns the read, non-empty string.\npub fn read_stdin(arena: &Arena, mut timeout: time::Duration) -> Option> {\n let scratch = scratch_arena(Some(arena));\n\n // On startup we're asked to inject a window size so that the UI system can layout the elements.\n // --> Inject a fake sequence for our input parser.\n let mut resize_event = None;\n if unsafe { STATE.inject_resize } {\n unsafe { STATE.inject_resize = false };\n timeout = time::Duration::ZERO;\n resize_event = get_console_size();\n }\n\n let read_poll = timeout != time::Duration::MAX; // there is a timeout -> don't block in read()\n let input_buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut input_buf_cap = input_buf.len();\n let utf16_buf = scratch.alloc_uninit_slice(4 * KIBI);\n let mut utf16_buf_len = 0;\n\n // If there was a leftover leading surrogate from the last read, we prepend it to the buffer.\n if unsafe { STATE.leading_surrogate } != 0 {\n utf16_buf[0] = MaybeUninit::new(unsafe { STATE.leading_surrogate });\n utf16_buf_len = 1;\n input_buf_cap -= 1;\n unsafe { STATE.leading_surrogate = 0 };\n }\n\n // Read until there's either a timeout or we have something to process.\n loop {\n if timeout != time::Duration::MAX {\n let beg = time::Instant::now();\n\n match unsafe { Threading::WaitForSingleObject(STATE.stdin, timeout.as_millis() as u32) }\n {\n // Ready to read? Continue with reading below.\n Foundation::WAIT_OBJECT_0 => {}\n // Timeout? Skip reading entirely.\n Foundation::WAIT_TIMEOUT => break,\n // Error? Tell the caller stdin is broken.\n _ => return None,\n }\n\n timeout = timeout.saturating_sub(beg.elapsed());\n }\n\n // Read from stdin.\n let input = unsafe {\n // If we had a `inject_resize`, we don't want to block indefinitely for other pending input on startup,\n // but are still interested in any other pending input that may be waiting for us.\n let flags = if read_poll { CONSOLE_READ_NOWAIT } else { 0 };\n let mut read = 0;\n let ok = (STATE.read_console_input_ex)(\n STATE.stdin,\n input_buf[0].as_mut_ptr(),\n input_buf_cap as u32,\n &mut read,\n flags,\n );\n if ok == 0 || STATE.wants_exit {\n return None;\n }\n input_buf[..read as usize].assume_init_ref()\n };\n\n // Convert Win32 input records into UTF16.\n for inp in input {\n match inp.EventType as u32 {\n Console::KEY_EVENT => {\n let event = unsafe { &inp.Event.KeyEvent };\n let ch = unsafe { event.uChar.UnicodeChar };\n if event.bKeyDown != 0 && ch != 0 {\n utf16_buf[utf16_buf_len] = MaybeUninit::new(ch);\n utf16_buf_len += 1;\n }\n }\n Console::WINDOW_BUFFER_SIZE_EVENT => {\n let event = unsafe { &inp.Event.WindowBufferSizeEvent };\n let w = event.dwSize.X as CoordType;\n let h = event.dwSize.Y as CoordType;\n // Windows is prone to sending broken/useless `WINDOW_BUFFER_SIZE_EVENT`s.\n // E.g. starting conhost will emit 3 in a row. Skip rendering in that case.\n if w > 0 && h > 0 {\n resize_event = Some(Size { width: w, height: h });\n }\n }\n _ => {}\n }\n }\n\n if resize_event.is_some() || utf16_buf_len != 0 {\n break;\n }\n }\n\n const RESIZE_EVENT_FMT_MAX_LEN: usize = 16; // \"\\x1b[8;65535;65535t\"\n let resize_event_len = if resize_event.is_some() { RESIZE_EVENT_FMT_MAX_LEN } else { 0 };\n // +1 to account for a potential `STATE.leading_surrogate`.\n let utf8_max_len = (utf16_buf_len + 1) * 3;\n let mut text = ArenaString::new_in(arena);\n text.reserve(utf8_max_len + resize_event_len);\n\n // Now prepend our previously extracted resize event.\n if let Some(resize_event) = resize_event {\n // If I read xterm's documentation correctly, CSI 18 t reports the window size in characters.\n // CSI 8 ; height ; width t is the response. Of course, we didn't send the request,\n // but we can use this fake response to trigger the editor to resize itself.\n _ = write!(text, \"\\x1b[8;{};{}t\", resize_event.height, resize_event.width);\n }\n\n // If the input ends with a lone lead surrogate, we need to remember it for the next read.\n if utf16_buf_len > 0 {\n unsafe {\n let last_char = utf16_buf[utf16_buf_len - 1].assume_init();\n if (0xD800..0xDC00).contains(&last_char) {\n STATE.leading_surrogate = last_char;\n utf16_buf_len -= 1;\n }\n }\n }\n\n // Convert the remaining input to UTF8, the sane encoding.\n if utf16_buf_len > 0 {\n unsafe {\n let vec = text.as_mut_vec();\n let spare = vec.spare_capacity_mut();\n\n let len = Globalization::WideCharToMultiByte(\n Globalization::CP_UTF8,\n 0,\n utf16_buf[0].as_ptr(),\n utf16_buf_len as i32,\n spare.as_mut_ptr() as *mut _,\n spare.len() as i32,\n null(),\n null_mut(),\n );\n\n if len > 0 {\n vec.set_len(vec.len() + len as usize);\n }\n }\n }\n\n text.shrink_to_fit();\n Some(text)\n}\n\n/// Writes a string to stdout.\n///\n/// Use this instead of `print!` or `println!` to avoid\n/// the overhead of Rust's stdio handling. Don't need that.\npub fn write_stdout(text: &str) {\n unsafe {\n let mut offset = 0;\n\n while offset < text.len() {\n let ptr = text.as_ptr().add(offset);\n let write = (text.len() - offset).min(GIBI) as u32;\n let mut written = 0;\n let ok = FileSystem::WriteFile(STATE.stdout, ptr, write, &mut written, null_mut());\n offset += written as usize;\n if ok == 0 || written == 0 {\n break;\n }\n }\n }\n}\n\n/// Check if the stdin handle is redirected to a file, etc.\n///\n/// # Returns\n///\n/// * `Some(file)` if stdin is redirected.\n/// * Otherwise, `None`.\npub fn open_stdin_if_redirected() -> Option {\n unsafe {\n let handle = Console::GetStdHandle(Console::STD_INPUT_HANDLE);\n // Did we reopen stdin during `init()`?\n if !std::ptr::eq(STATE.stdin, handle) { Some(File::from_raw_handle(handle)) } else { None }\n }\n}\n\npub fn drives() -> impl Iterator {\n unsafe {\n let mut mask = FileSystem::GetLogicalDrives();\n std::iter::from_fn(move || {\n let bit = mask.trailing_zeros();\n if bit >= 26 {\n None\n } else {\n mask &= !(1 << bit);\n Some((b'A' + bit as u8) as char)\n }\n })\n }\n}\n\n/// A unique identifier for a file.\npub enum FileId {\n Id(FileSystem::FILE_ID_INFO),\n Path(PathBuf),\n}\n\nimpl PartialEq for FileId {\n fn eq(&self, other: &Self) -> bool {\n match (self, other) {\n (Self::Id(left), Self::Id(right)) => {\n // Lowers to an efficient word-wise comparison.\n const SIZE: usize = std::mem::size_of::();\n let a: &[u8; SIZE] = unsafe { mem::transmute(left) };\n let b: &[u8; SIZE] = unsafe { mem::transmute(right) };\n a == b\n }\n (Self::Path(left), Self::Path(right)) => left == right,\n _ => false,\n }\n }\n}\n\nimpl Eq for FileId {}\n\n/// Returns a unique identifier for the given file by handle or path.\npub fn file_id(file: Option<&File>, path: &Path) -> apperr::Result {\n let file = match file {\n Some(f) => f,\n None => &File::open(path)?,\n };\n\n file_id_from_handle(file).or_else(|_| Ok(FileId::Path(std::fs::canonicalize(path)?)))\n}\n\nfn file_id_from_handle(file: &File) -> apperr::Result {\n unsafe {\n let mut info = MaybeUninit::::uninit();\n check_bool_return(FileSystem::GetFileInformationByHandleEx(\n file.as_raw_handle(),\n FileSystem::FileIdInfo,\n info.as_mut_ptr() as *mut _,\n mem::size_of::() as u32,\n ))?;\n Ok(FileId::Id(info.assume_init()))\n }\n}\n\n/// Canonicalizes the given path.\n///\n/// This differs from [`fs::canonicalize`] in that it strips the `\\\\?\\` UNC\n/// prefix on Windows. This is because it's confusing/ugly when displaying it.\npub fn canonicalize(path: &Path) -> std::io::Result {\n let mut path = fs::canonicalize(path)?;\n let path = path.as_mut_os_string();\n let mut path = mem::take(path).into_encoded_bytes();\n\n if path.len() > 6 && &path[0..4] == br\"\\\\?\\\" && path[4].is_ascii_uppercase() && path[5] == b':'\n {\n path.drain(0..4);\n }\n\n let path = unsafe { OsString::from_encoded_bytes_unchecked(path) };\n let path = PathBuf::from(path);\n Ok(path)\n}\n\n/// Reserves a virtual memory region of the given size.\n/// To commit the memory, use [`virtual_commit`].\n/// To release the memory, use [`virtual_release`].\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Don't forget to release the memory when you're done with it or you'll leak it.\npub unsafe fn virtual_reserve(size: usize) -> apperr::Result> {\n unsafe {\n #[allow(unused_assignments, unused_mut)]\n let mut base = null_mut();\n\n // In debug builds, we use fixed addresses to aid in debugging.\n // Makes it possible to immediately tell which address space a pointer belongs to.\n #[cfg(all(debug_assertions, not(target_pointer_width = \"32\")))]\n {\n static mut S_BASE_GEN: usize = 0x0000100000000000; // 16 TiB\n S_BASE_GEN += 0x0000001000000000; // 64 GiB\n base = S_BASE_GEN as *mut _;\n }\n\n check_ptr_return(Memory::VirtualAlloc(\n base,\n size,\n Memory::MEM_RESERVE,\n Memory::PAGE_READWRITE,\n ) as *mut u8)\n }\n}\n\n/// Releases a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from [`virtual_reserve`].\npub unsafe fn virtual_release(base: NonNull, _size: usize) {\n unsafe {\n // NOTE: `VirtualFree` fails if the pointer isn't\n // a valid base address or if the size isn't zero.\n Memory::VirtualFree(base.as_ptr() as *mut _, 0, Memory::MEM_RELEASE);\n }\n}\n\n/// Commits a virtual memory region of the given size.\n///\n/// # Safety\n///\n/// This function is unsafe because it uses raw pointers.\n/// Make sure to only pass pointers acquired from [`virtual_reserve`]\n/// and to pass a size less than or equal to the size passed to [`virtual_reserve`].\npub unsafe fn virtual_commit(base: NonNull, size: usize) -> apperr::Result<()> {\n unsafe {\n check_ptr_return(Memory::VirtualAlloc(\n base.as_ptr() as *mut _,\n size,\n Memory::MEM_COMMIT,\n Memory::PAGE_READWRITE,\n ))\n .map(|_| ())\n }\n}\n\nunsafe fn get_module(name: *const u16) -> apperr::Result> {\n unsafe { check_ptr_return(LibraryLoader::GetModuleHandleW(name)) }\n}\n\nunsafe fn load_library(name: *const u16) -> apperr::Result> {\n unsafe {\n check_ptr_return(LibraryLoader::LoadLibraryExW(\n name,\n null_mut(),\n LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32,\n ))\n }\n}\n\n/// Loads a function from a dynamic library.\n///\n/// # Safety\n///\n/// This function is highly unsafe as it requires you to know the exact type\n/// of the function you're loading. No type checks whatsoever are performed.\n//\n// It'd be nice to constrain T to std::marker::FnPtr, but that's unstable.\npub unsafe fn get_proc_address(\n handle: NonNull,\n name: *const c_char,\n) -> apperr::Result {\n unsafe {\n let ptr = LibraryLoader::GetProcAddress(handle.as_ptr(), name as *const u8);\n if let Some(ptr) = ptr { Ok(mem::transmute_copy(&ptr)) } else { Err(get_last_error()) }\n }\n}\n\npub struct LibIcu {\n pub libicuuc: NonNull,\n pub libicui18n: NonNull,\n}\n\npub fn load_icu() -> apperr::Result {\n const fn const_ptr_u16_eq(a: *const u16, b: *const u16) -> bool {\n unsafe {\n let mut a = a;\n let mut b = b;\n loop {\n if *a != *b {\n return false;\n }\n if *a == 0 {\n return true;\n }\n a = a.add(1);\n b = b.add(1);\n }\n }\n }\n\n const LIBICUUC: *const u16 = w_env!(\"EDIT_CFG_ICUUC_SONAME\");\n const LIBICUI18N: *const u16 = w_env!(\"EDIT_CFG_ICUI18N_SONAME\");\n\n if const { const_ptr_u16_eq(LIBICUUC, LIBICUI18N) } {\n let icu = unsafe { load_library(LIBICUUC)? };\n Ok(LibIcu { libicuuc: icu, libicui18n: icu })\n } else {\n let libicuuc = unsafe { load_library(LIBICUUC)? };\n let libicui18n = unsafe { load_library(LIBICUI18N)? };\n Ok(LibIcu { libicuuc, libicui18n })\n }\n}\n\n/// Returns a list of preferred languages for the current user.\npub fn preferred_languages(arena: &Arena) -> Vec, &Arena> {\n // If the GetUserPreferredUILanguages() don't fit into 512 characters,\n // honestly, just give up. How many languages do you realistically need?\n const LEN: usize = 512;\n\n let scratch = scratch_arena(Some(arena));\n let mut res = Vec::new_in(arena);\n\n // Get the list of preferred languages via `GetUserPreferredUILanguages`.\n let langs = unsafe {\n let buf = scratch.alloc_uninit_slice(LEN);\n let mut len = buf.len() as u32;\n let mut num = 0;\n\n let ok = Globalization::GetUserPreferredUILanguages(\n Globalization::MUI_LANGUAGE_NAME,\n &mut num,\n buf[0].as_mut_ptr(),\n &mut len,\n );\n\n if ok == 0 || num == 0 {\n len = 0;\n }\n\n // Drop the terminating double-null character.\n len = len.saturating_sub(1);\n\n buf[..len as usize].assume_init_ref()\n };\n\n // Convert UTF16 to UTF8.\n let langs = wide_to_utf8(&scratch, langs);\n\n // Split the null-delimited string into individual chunks\n // and copy them into the given arena.\n res.extend(\n langs\n .split_terminator('\\0')\n .filter(|s| !s.is_empty())\n .map(|s| ArenaString::from_str(arena, s)),\n );\n res\n}\n\nfn wide_to_utf8<'a>(arena: &'a Arena, wide: &[u16]) -> ArenaString<'a> {\n let mut res = ArenaString::new_in(arena);\n res.reserve(wide.len() * 3);\n\n let len = unsafe {\n Globalization::WideCharToMultiByte(\n Globalization::CP_UTF8,\n 0,\n wide.as_ptr(),\n wide.len() as i32,\n res.as_mut_ptr() as *mut _,\n res.capacity() as i32,\n null(),\n null_mut(),\n )\n };\n if len > 0 {\n unsafe { res.as_mut_vec().set_len(len as usize) };\n }\n\n res.shrink_to_fit();\n res\n}\n\n#[cold]\nfn get_last_error() -> apperr::Error {\n unsafe { gle_to_apperr(Foundation::GetLastError()) }\n}\n\n#[inline]\nconst fn gle_to_apperr(gle: u32) -> apperr::Error {\n apperr::Error::new_sys(if gle == 0 { 0x8000FFFF } else { 0x80070000 | gle })\n}\n\n#[inline]\npub(crate) fn io_error_to_apperr(err: std::io::Error) -> apperr::Error {\n gle_to_apperr(err.raw_os_error().unwrap_or(0) as u32)\n}\n\n/// Formats a platform error code into a human-readable string.\npub fn apperr_format(f: &mut std::fmt::Formatter<'_>, code: u32) -> std::fmt::Result {\n unsafe {\n let mut ptr: *mut u8 = null_mut();\n let len = Debug::FormatMessageA(\n Debug::FORMAT_MESSAGE_ALLOCATE_BUFFER\n | Debug::FORMAT_MESSAGE_FROM_SYSTEM\n | Debug::FORMAT_MESSAGE_IGNORE_INSERTS,\n null(),\n code,\n 0,\n &mut ptr as *mut *mut _ as *mut _,\n 0,\n null_mut(),\n );\n\n write!(f, \"Error {code:#08x}\")?;\n\n if len > 0 {\n let msg = str_from_raw_parts(ptr, len as usize);\n let msg = msg.trim_ascii();\n let msg = msg.replace(['\\r', '\\n'], \" \");\n write!(f, \": {msg}\")?;\n Foundation::LocalFree(ptr as *mut _);\n }\n\n Ok(())\n }\n}\n\n/// Checks if the given error is a \"file not found\" error.\npub fn apperr_is_not_found(err: apperr::Error) -> bool {\n err == gle_to_apperr(Foundation::ERROR_FILE_NOT_FOUND)\n}\n\nfn check_bool_return(ret: Foundation::BOOL) -> apperr::Result<()> {\n if ret == 0 { Err(get_last_error()) } else { Ok(()) }\n}\n\nfn check_ptr_return(ret: *mut T) -> apperr::Result> {\n NonNull::new(ret).ok_or_else(get_last_error)\n}\n"], ["/edit/src/tui.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! An immediate mode UI framework for terminals.\n//!\n//! # Why immediate mode?\n//!\n//! This uses an \"immediate mode\" design, similar to [ImGui](https://github.com/ocornut/imgui).\n//! The reason for this is that I expect the UI needs for any terminal application to be\n//! fairly minimal, and for that purpose an immediate mode design is much simpler to use.\n//!\n//! So what's \"immediate mode\"? The primary alternative is called \"retained mode\".\n//! The difference is that when you create a button in this framework in one frame,\n//! and you stop telling this framework in the next frame, the button will vanish.\n//! When you use a regular retained mode UI framework, you create the button once,\n//! set up callbacks for when it is clicked, and then stop worrying about it.\n//!\n//! The downside of immediate mode is that your UI code _may_ become cluttered.\n//! The upside however is that you cannot leak UI elements, you don't need to\n//! worry about lifetimes nor callbacks, and that simple UIs are simple to write.\n//!\n//! More importantly though, the primary reason for this is that the\n//! lack of callbacks means we can use this design across a plain C ABI,\n//! which we'll need once plugins come into play. GTK's `g_signal_connect`\n//! shows that the alternative can be rather cumbersome.\n//!\n//! # Design overview\n//!\n//! While this file is fairly lengthy, the overall algorithm is simple.\n//! On the first frame ever:\n//! * Prepare an empty `arena_next`.\n//! * Parse the incoming [`input::Input`] which should be a resize event.\n//! * Create a new [`Context`] instance and give it the caller.\n//! * Now the caller will draw their UI with the [`Context`] by calling the\n//! various [`Context`] UI methods, such as [`Context::block_begin()`] and\n//! [`Context::block_end()`]. These two are the basis which all other UI\n//! elements are built upon by the way. Each UI element that is created gets\n//! allocated onto `arena_next` and inserted into the UI tree.\n//! That tree works exactly like the DOM tree in HTML: Each node in the tree\n//! has a parent, children, and siblings. The tree layout at the end is then\n//! a direct mirror of the code \"layout\" that created it.\n//! * Once the caller is done and drops the [`Context`], it'll secretly call\n//! `report_context_completion`. This causes a number of things:\n//! * The DOM tree that was built is stored in `prev_tree`.\n//! * A hashmap of all nodes is built and stored in `prev_node_map`.\n//! * `arena_next` is swapped with `arena_prev`.\n//! * Each UI node is measured and laid out.\n//! * Now the caller is expected to repeat this process with a [`None`]\n//! input event until [`Tui::needs_settling()`] returns false.\n//! This is necessary, because when [`Context::button()`] returns `true`\n//! in one frame, it may change the state in the caller's code\n//! and require another frame to be drawn.\n//! * Finally a call to [`Tui::render()`] will render the UI tree into the\n//! framebuffer and return VT output.\n//!\n//! On every subsequent frame the process is similar, but one crucial element\n//! of any immediate mode UI framework is added:\n//! Now when the caller draws their UI, the various [`Context`] UI elements\n//! have access to `prev_node_map` and the previously built UI tree.\n//! This allows the UI framework to reuse the previously computed layout for\n//! hit tests, caching scroll offsets, and so on.\n//!\n//! In the end it looks very similar:\n//! * Prepare an empty `arena_next`.\n//! * Parse the incoming [`input::Input`]...\n//! * **BUT** now we can hit-test mouse clicks onto the previously built\n//! UI tree. This way we can delegate focus on left mouse clicks.\n//! * Create a new [`Context`] instance and give it the caller.\n//! * The caller draws their UI with the [`Context`]...\n//! * **BUT** we can preserve the UI state across frames.\n//! * Continue rendering until [`Tui::needs_settling()`] returns false.\n//! * And the final call to [`Tui::render()`].\n//!\n//! # Classnames and node IDs\n//!\n//! So how do we find which node from the previous tree correlates to the\n//! current node? Each node needs to be constructed with a \"classname\".\n//! The classname is hashed with the parent node ID as the seed. This derived\n//! hash is then used as the new child node ID. Under the assumption that the\n//! collision likelihood of the hash function is low, this serves as true IDs.\n//!\n//! This has the nice added property that finding a node with the same ID\n//! guarantees that all of the parent nodes must have equivalent IDs as well.\n//! This turns \"is the focus anywhere inside this subtree\" into an O(1) check.\n//!\n//! The reason \"classnames\" are used is because I was hoping to add theming\n//! in the future with a syntax similar to CSS (simplified, however).\n//!\n//! # Example\n//!\n//! ```\n//! use edit::helpers::Size;\n//! use edit::input::Input;\n//! use edit::tui::*;\n//! use edit::{arena, arena_format};\n//!\n//! struct State {\n//! counter: i32,\n//! }\n//!\n//! fn main() {\n//! arena::init(128 * 1024 * 1024).unwrap();\n//!\n//! // Create a `Tui` instance which holds state across frames.\n//! let mut tui = Tui::new().unwrap();\n//! let mut state = State { counter: 0 };\n//! let input = Input::Resize(Size { width: 80, height: 24 });\n//!\n//! // Pass the input to the TUI.\n//! {\n//! let mut ctx = tui.create_context(Some(input));\n//! draw(&mut ctx, &mut state);\n//! }\n//!\n//! // Continue until the layout has settled.\n//! while tui.needs_settling() {\n//! let mut ctx = tui.create_context(None);\n//! draw(&mut ctx, &mut state);\n//! }\n//!\n//! // Render the output.\n//! let scratch = arena::scratch_arena(None);\n//! let output = tui.render(&*scratch);\n//! println!(\"{}\", output);\n//! }\n//!\n//! fn draw(ctx: &mut Context, state: &mut State) {\n//! ctx.table_begin(\"classname\");\n//! {\n//! ctx.table_next_row();\n//!\n//! // Thanks to the lack of callbacks, we can use a primitive\n//! // if condition here, as well as in any potential C code.\n//! if ctx.button(\"button\", \"Click me!\", ButtonStyle::default()) {\n//! state.counter += 1;\n//! }\n//!\n//! // Similarly, formatting and showing labels is straightforward.\n//! // It's impossible to forget updating the label this way.\n//! ctx.label(\"label\", &arena_format!(ctx.arena(), \"Counter: {}\", state.counter));\n//! }\n//! ctx.table_end();\n//! }\n//! ```\n\nuse std::arch::breakpoint;\n#[cfg(debug_assertions)]\nuse std::collections::HashSet;\nuse std::fmt::Write as _;\nuse std::{iter, mem, ptr, time};\n\nuse crate::arena::{Arena, ArenaString, scratch_arena};\nuse crate::buffer::{CursorMovement, MoveLineDirection, RcTextBuffer, TextBuffer, TextBufferCell};\nuse crate::cell::*;\nuse crate::clipboard::Clipboard;\nuse crate::document::WriteableDocument;\nuse crate::framebuffer::{Attributes, Framebuffer, INDEXED_COLORS_COUNT, IndexedColor};\nuse crate::hash::*;\nuse crate::helpers::*;\nuse crate::input::{InputKeyMod, kbmod, vk};\nuse crate::{apperr, arena_format, input, simd, unicode};\n\nconst ROOT_ID: u64 = 0x14057B7EF767814F; // Knuth's MMIX constant\nconst SHIFT_TAB: InputKey = vk::TAB.with_modifiers(kbmod::SHIFT);\nconst KBMOD_FOR_WORD_NAV: InputKeyMod =\n if cfg!(target_os = \"macos\") { kbmod::ALT } else { kbmod::CTRL };\n\ntype Input<'input> = input::Input<'input>;\ntype InputKey = input::InputKey;\ntype InputMouseState = input::InputMouseState;\n\n/// Since [`TextBuffer`] creation and management is expensive,\n/// we cache instances of them for reuse between frames.\n/// This is used for [`Context::editline()`].\nstruct CachedTextBuffer {\n node_id: u64,\n editor: RcTextBuffer,\n seen: bool,\n}\n\n/// Since [`Context::editline()`] and [`Context::textarea()`]\n/// do almost the same thing, this abstracts over the two.\nenum TextBufferPayload<'a> {\n Editline(&'a mut dyn WriteableDocument),\n Textarea(RcTextBuffer),\n}\n\n/// In order for the TUI to show the correct Ctrl/Alt/Shift\n/// translations, this struct lets you set them.\npub struct ModifierTranslations {\n pub ctrl: &'static str,\n pub alt: &'static str,\n pub shift: &'static str,\n}\n\n/// Controls to which node the floater is anchored.\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub enum Anchor {\n /// The floater is attached relative to the node created last.\n #[default]\n Last,\n /// The floater is attached relative to the current node (= parent of new nodes).\n Parent,\n /// The floater is attached relative to the root node (= usually the viewport).\n Root,\n}\n\n/// Controls the position of the floater. See [`Context::attr_float`].\n#[derive(Default)]\npub struct FloatSpec {\n /// Controls to which node the floater is anchored.\n pub anchor: Anchor,\n // Specifies the origin of the container relative to the container size. [0, 1]\n pub gravity_x: f32,\n pub gravity_y: f32,\n // Specifies an offset from the origin in cells.\n pub offset_x: f32,\n pub offset_y: f32,\n}\n\n/// Informs you about the change that was made to the list selection.\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum ListSelection {\n /// The selection wasn't changed.\n Unchanged,\n /// The selection was changed to the current list item.\n Selected,\n /// The selection was changed to the current list item\n /// *and* the item was also activated (Enter or Double-click).\n Activated,\n}\n\n/// Controls the position of a node relative to its parent.\n#[derive(Default)]\npub enum Position {\n /// The child is stretched to fill the parent.\n #[default]\n Stretch,\n /// The child is positioned at the left edge of the parent.\n Left,\n /// The child is positioned at the center of the parent.\n Center,\n /// The child is positioned at the right edge of the parent.\n Right,\n}\n\n/// Controls the text overflow behavior of a label\n/// when the text doesn't fit the container.\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub enum Overflow {\n /// Text is simply cut off when it doesn't fit.\n #[default]\n Clip,\n /// An ellipsis is shown at the end of the text.\n TruncateHead,\n /// An ellipsis is shown in the middle of the text.\n TruncateMiddle,\n /// An ellipsis is shown at the beginning of the text.\n TruncateTail,\n}\n\n/// Controls the style with which a button label renders\n#[derive(Clone, Copy)]\npub struct ButtonStyle {\n accelerator: Option,\n checked: Option,\n bracketed: bool,\n}\n\nimpl ButtonStyle {\n /// Draw an accelerator label: `[_E_xample button]` or `[Example button(X)]`\n ///\n /// Must provide an upper-case ASCII character.\n pub fn accelerator(self, char: char) -> Self {\n Self { accelerator: Some(char), ..self }\n }\n /// Draw a checkbox prefix: `[🗹 Example Button]`\n pub fn checked(self, checked: bool) -> Self {\n Self { checked: Some(checked), ..self }\n }\n /// Draw with or without brackets: `[Example Button]` or `Example Button`\n pub fn bracketed(self, bracketed: bool) -> Self {\n Self { bracketed, ..self }\n }\n}\n\nimpl Default for ButtonStyle {\n fn default() -> Self {\n Self {\n accelerator: None,\n checked: None,\n bracketed: true, // Default style for most buttons. Brackets may be disabled e.g. for buttons in menus\n }\n }\n}\n\n/// There's two types of lifetimes the TUI code needs to manage:\n/// * Across frames\n/// * Per frame\n///\n/// [`Tui`] manages the first one. It's also the entrypoint for\n/// everything else you may want to do.\npub struct Tui {\n /// Arena used for the previous frame.\n arena_prev: Arena,\n /// Arena used for the current frame.\n arena_next: Arena,\n /// The UI tree built in the previous frame.\n /// This refers to memory in `arena_prev`.\n prev_tree: Tree<'static>,\n /// A hashmap of all nodes built in the previous frame.\n /// This refers to memory in `arena_prev`.\n prev_node_map: NodeMap<'static>,\n /// The framebuffer used for rendering.\n framebuffer: Framebuffer,\n\n modifier_translations: ModifierTranslations,\n floater_default_bg: u32,\n floater_default_fg: u32,\n modal_default_bg: u32,\n modal_default_fg: u32,\n\n /// Last known terminal size.\n ///\n /// This lives here instead of [`Context`], because we need to\n /// track the state across frames and input events.\n /// This also applies to the remaining members in this block below.\n size: Size,\n /// Last known mouse position.\n mouse_position: Point,\n /// Between mouse down and up, the position where the mouse was pressed.\n /// Otherwise, this contains Point::MIN.\n mouse_down_position: Point,\n /// Node ID of the node that was clicked on.\n /// Used for tracking drag targets.\n left_mouse_down_target: u64,\n /// Timestamp of the last mouse up event.\n /// Used for tracking double/triple clicks.\n mouse_up_timestamp: std::time::Instant,\n /// The current mouse state.\n mouse_state: InputMouseState,\n /// Whether the mouse is currently being dragged.\n mouse_is_drag: bool,\n /// The number of clicks that have happened in a row.\n /// Gets reset when the mouse was released for a while.\n mouse_click_counter: CoordType,\n /// The path to the node that was clicked on.\n mouse_down_node_path: Vec,\n /// The position of the first click in a double/triple click series.\n first_click_position: Point,\n /// The node ID of the node that was first clicked on\n /// in a double/triple click series.\n first_click_target: u64,\n\n /// Path to the currently focused node.\n focused_node_path: Vec,\n /// Contains the last element in [`Tui::focused_node_path`].\n /// This way we can track if the focus changed, because then we\n /// need to scroll the node into view if it's within a scrollarea.\n focused_node_for_scrolling: u64,\n\n /// A list of cached text buffers used for [`Context::editline()`].\n cached_text_buffers: Vec,\n\n /// The clipboard contents.\n clipboard: Clipboard,\n\n settling_have: i32,\n settling_want: i32,\n read_timeout: time::Duration,\n}\n\nimpl Tui {\n /// Creates a new [`Tui`] instance for storing state across frames.\n pub fn new() -> apperr::Result {\n let arena_prev = Arena::new(128 * MEBI)?;\n let arena_next = Arena::new(128 * MEBI)?;\n // SAFETY: Since `prev_tree` refers to `arena_prev`/`arena_next`, from its POV the lifetime\n // is `'static`, requiring us to use `transmute` to circumvent the borrow checker.\n let prev_tree = Tree::new(unsafe { mem::transmute::<&Arena, &Arena>(&arena_next) });\n\n let mut tui = Self {\n arena_prev,\n arena_next,\n prev_tree,\n prev_node_map: Default::default(),\n framebuffer: Framebuffer::new(),\n\n modifier_translations: ModifierTranslations {\n ctrl: \"Ctrl\",\n alt: \"Alt\",\n shift: \"Shift\",\n },\n floater_default_bg: 0,\n floater_default_fg: 0,\n modal_default_bg: 0,\n modal_default_fg: 0,\n\n size: Size { width: 0, height: 0 },\n mouse_position: Point::MIN,\n mouse_down_position: Point::MIN,\n left_mouse_down_target: 0,\n mouse_up_timestamp: std::time::Instant::now(),\n mouse_state: InputMouseState::None,\n mouse_is_drag: false,\n mouse_click_counter: 0,\n mouse_down_node_path: Vec::with_capacity(16),\n first_click_position: Point::MIN,\n first_click_target: 0,\n\n focused_node_path: Vec::with_capacity(16),\n focused_node_for_scrolling: ROOT_ID,\n\n cached_text_buffers: Vec::with_capacity(16),\n\n clipboard: Default::default(),\n\n settling_have: 0,\n settling_want: 0,\n read_timeout: time::Duration::MAX,\n };\n Self::clean_node_path(&mut tui.mouse_down_node_path);\n Self::clean_node_path(&mut tui.focused_node_path);\n Ok(tui)\n }\n\n /// Sets up the framebuffer's color palette.\n pub fn setup_indexed_colors(&mut self, colors: [u32; INDEXED_COLORS_COUNT]) {\n self.framebuffer.set_indexed_colors(colors);\n }\n\n /// Set up translations for Ctrl/Alt/Shift modifiers.\n pub fn setup_modifier_translations(&mut self, translations: ModifierTranslations) {\n self.modifier_translations = translations;\n }\n\n /// Set the default background color for floaters (dropdowns, etc.).\n pub fn set_floater_default_bg(&mut self, color: u32) {\n self.floater_default_bg = color;\n }\n\n /// Set the default foreground color for floaters (dropdowns, etc.).\n pub fn set_floater_default_fg(&mut self, color: u32) {\n self.floater_default_fg = color;\n }\n\n /// Set the default background color for modals.\n pub fn set_modal_default_bg(&mut self, color: u32) {\n self.modal_default_bg = color;\n }\n\n /// Set the default foreground color for modals.\n pub fn set_modal_default_fg(&mut self, color: u32) {\n self.modal_default_fg = color;\n }\n\n /// If the TUI is currently running animations, etc.,\n /// this will return a timeout smaller than [`time::Duration::MAX`].\n pub fn read_timeout(&mut self) -> time::Duration {\n mem::replace(&mut self.read_timeout, time::Duration::MAX)\n }\n\n /// Returns the viewport size.\n pub fn size(&self) -> Size {\n // We don't use the size stored in the framebuffer, because until\n // `render()` is called, the framebuffer will use a stale size.\n self.size\n }\n\n /// Returns an indexed color from the framebuffer.\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.framebuffer.indexed(index)\n }\n\n /// Returns an indexed color from the framebuffer with the given alpha.\n /// See [`Framebuffer::indexed_alpha()`].\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n self.framebuffer.indexed_alpha(index, numerator, denominator)\n }\n\n /// Returns a color in contrast with the given color.\n /// See [`Framebuffer::contrasted()`].\n pub fn contrasted(&self, color: u32) -> u32 {\n self.framebuffer.contrasted(color)\n }\n\n /// Returns the clipboard.\n pub fn clipboard_ref(&self) -> &Clipboard {\n &self.clipboard\n }\n\n /// Returns the clipboard (mutable).\n pub fn clipboard_mut(&mut self) -> &mut Clipboard {\n &mut self.clipboard\n }\n\n /// Starts a new frame and returns a [`Context`] for it.\n pub fn create_context<'a, 'input>(\n &'a mut self,\n input: Option>,\n ) -> Context<'a, 'input> {\n // SAFETY: Since we have a unique `&mut self`, nothing is holding onto `arena_prev`,\n // which will become `arena_next` and get reset. It's safe to reset and reuse its memory.\n mem::swap(&mut self.arena_prev, &mut self.arena_next);\n unsafe { self.arena_next.reset(0) };\n\n // In the input handler below we transformed a mouse up into a release event.\n // Now, a frame later, we must reset it back to none, to stop it from triggering things.\n // Same for Scroll events.\n if self.mouse_state > InputMouseState::Right {\n self.mouse_down_position = Point::MIN;\n self.mouse_down_node_path.clear();\n self.left_mouse_down_target = 0;\n self.mouse_state = InputMouseState::None;\n self.mouse_is_drag = false;\n }\n\n let now = std::time::Instant::now();\n let mut input_text = None;\n let mut input_keyboard = None;\n let mut input_mouse_modifiers = kbmod::NONE;\n let mut input_mouse_click = 0;\n let mut input_scroll_delta = Point { x: 0, y: 0 };\n // `input_consumed` should be `true` if we're in the settling phase which is indicated by\n // `self.needs_settling() == true`. However, there's a possibility for it being true from\n // a previous frame, and we do have fresh new input. In that case want `input_consumed`\n // to be false of course which is ensured by checking for `input.is_none()`.\n let input_consumed = self.needs_settling() && input.is_none();\n\n if self.scroll_to_focused() {\n self.needs_more_settling();\n }\n\n match input {\n None => {}\n Some(Input::Resize(resize)) => {\n assert!(resize.width > 0 && resize.height > 0);\n assert!(resize.width < 32768 && resize.height < 32768);\n self.size = resize;\n }\n Some(Input::Text(text)) => {\n input_text = Some(text);\n // TODO: the .len()==1 check causes us to ignore keyboard inputs that are faster than we process them.\n // For instance, imagine the user presses \"A\" twice and we happen to read it in a single chunk.\n // This causes us to ignore the keyboard input here. We need a way to inform the caller over\n // how much of the input text we actually processed in a single frame. Or perhaps we could use\n // the needs_settling logic?\n if text.len() == 1 {\n let ch = text.as_bytes()[0];\n input_keyboard = InputKey::from_ascii(ch as char)\n }\n }\n Some(Input::Paste(paste)) => {\n let clipboard = self.clipboard_mut();\n clipboard.write(paste);\n clipboard.mark_as_synchronized();\n input_keyboard = Some(kbmod::CTRL | vk::V);\n }\n Some(Input::Keyboard(keyboard)) => {\n input_keyboard = Some(keyboard);\n }\n Some(Input::Mouse(mouse)) => {\n let mut next_state = mouse.state;\n let next_position = mouse.position;\n let next_scroll = mouse.scroll;\n let mouse_down = self.mouse_state == InputMouseState::None\n && next_state != InputMouseState::None;\n let mouse_up = self.mouse_state != InputMouseState::None\n && next_state == InputMouseState::None;\n let is_drag = self.mouse_state == InputMouseState::Left\n && next_state == InputMouseState::Left\n && next_position != self.mouse_position;\n\n let mut hovered_node = None; // Needed for `mouse_down`\n let mut focused_node = None; // Needed for `mouse_down` and `is_click`\n if mouse_down || mouse_up {\n // Roots (aka windows) are ordered in Z order, so we iterate\n // them in reverse order, from topmost to bottommost.\n for root in self.prev_tree.iterate_roots_rev() {\n // Find the node that contains the cursor.\n Tree::visit_all(root, root, true, |node| {\n let n = node.borrow();\n if !n.outer_clipped.contains(next_position) {\n // Skip the entire sub-tree, because it doesn't contain the cursor.\n return VisitControl::SkipChildren;\n }\n hovered_node = Some(node);\n if n.attributes.focusable {\n focused_node = Some(node);\n }\n VisitControl::Continue\n });\n\n // This root/window contains the cursor.\n // We don't care about any lower roots.\n if hovered_node.is_some() {\n break;\n }\n\n // This root is modal and swallows all clicks,\n // no matter whether the click was inside it or not.\n if matches!(root.borrow().content, NodeContent::Modal(_)) {\n break;\n }\n }\n }\n\n if mouse_down {\n // Transition from no mouse input to some mouse input --> Record the mouse down position.\n Self::build_node_path(hovered_node, &mut self.mouse_down_node_path);\n\n // On left-mouse-down we change focus.\n let mut target = 0;\n if next_state == InputMouseState::Left {\n target = focused_node.map_or(0, |n| n.borrow().id);\n Self::build_node_path(focused_node, &mut self.focused_node_path);\n self.needs_more_settling(); // See `needs_more_settling()`.\n }\n\n // Double-/Triple-/Etc.-clicks are triggered on mouse-down,\n // unlike the first initial click, which is triggered on mouse-up.\n if self.mouse_click_counter != 0 {\n if self.first_click_target != target\n || self.first_click_position != next_position\n || (now - self.mouse_up_timestamp)\n > std::time::Duration::from_millis(500)\n {\n // If the cursor moved / the focus changed in between, or if the user did a slow click,\n // we reset the click counter. On mouse-up it'll transition to a regular click.\n self.mouse_click_counter = 0;\n self.first_click_position = Point::MIN;\n self.first_click_target = 0;\n } else {\n self.mouse_click_counter += 1;\n input_mouse_click = self.mouse_click_counter;\n };\n }\n\n // Gets reset at the start of this function.\n self.left_mouse_down_target = target;\n self.mouse_down_position = next_position;\n } else if mouse_up {\n // Transition from some mouse input to no mouse input --> The mouse button was released.\n next_state = InputMouseState::Release;\n\n let target = focused_node.map_or(0, |n| n.borrow().id);\n\n if self.left_mouse_down_target == 0 || self.left_mouse_down_target != target {\n // If `left_mouse_down_target == 0`, then it wasn't a left-click, in which case\n // the target gets reset. Same, if the focus changed in between any clicks.\n self.mouse_click_counter = 0;\n self.first_click_position = Point::MIN;\n self.first_click_target = 0;\n } else if self.mouse_click_counter == 0 {\n // No focus change, and no previous clicks? This is an initial, regular click.\n self.mouse_click_counter = 1;\n self.first_click_position = self.mouse_down_position;\n self.first_click_target = target;\n input_mouse_click = 1;\n }\n\n self.mouse_up_timestamp = now;\n } else if is_drag {\n self.mouse_is_drag = true;\n }\n\n input_mouse_modifiers = mouse.modifiers;\n input_scroll_delta = next_scroll;\n self.mouse_position = next_position;\n self.mouse_state = next_state;\n }\n }\n\n if !input_consumed {\n // Every time there's input, we naturally need to re-render at least once.\n self.settling_have = 0;\n self.settling_want = 1;\n }\n\n // TODO: There should be a way to do this without unsafe.\n // Allocating from the arena borrows the arena, and so allocating the tree here borrows self.\n // This conflicts with us passing a mutable reference to `self` into the struct below.\n let tree = Tree::new(unsafe { mem::transmute::<&Arena, &Arena>(&self.arena_next) });\n\n Context {\n tui: self,\n\n input_text,\n input_keyboard,\n input_mouse_modifiers,\n input_mouse_click,\n input_scroll_delta,\n input_consumed,\n\n tree,\n last_modal: None,\n focused_node: None,\n next_block_id_mixin: 0,\n needs_settling: false,\n\n #[cfg(debug_assertions)]\n seen_ids: HashSet::new(),\n }\n }\n\n fn report_context_completion<'a>(&'a mut self, ctx: &mut Context<'a, '_>) {\n // If this hits, you forgot to block_end() somewhere. The best way to figure\n // out where is to do a binary search of commenting out code in main.rs.\n debug_assert!(\n ctx.tree.current_node.borrow().stack_parent.is_none(),\n \"Dangling parent! Did you miss a block_end?\"\n );\n\n // End the root node.\n ctx.block_end();\n\n // Ensure that focus doesn't escape the active modal.\n if let Some(node) = ctx.last_modal\n && !self.is_subtree_focused(&node.borrow())\n {\n ctx.steal_focus_for(node);\n }\n\n // If nodes have appeared or disappeared, we need to re-render.\n // Same, if the focus has changed (= changes the highlight color, etc.).\n let mut needs_settling = ctx.needs_settling;\n needs_settling |= self.prev_tree.checksum != ctx.tree.checksum;\n\n // Adopt the new tree and recalculate the node hashmap.\n //\n // SAFETY: The memory used by the tree is owned by the `self.arena_next` right now.\n // Stealing the tree here thus doesn't need to copy any memory unless someone resets the arena.\n // (The arena is reset in `reset()` above.)\n unsafe {\n self.prev_tree = mem::transmute_copy(&ctx.tree);\n self.prev_node_map = NodeMap::new(mem::transmute(&self.arena_next), &self.prev_tree);\n }\n\n let mut focus_path_pop_min = 0;\n // If the user pressed Escape, we move the focus to a parent node.\n if !ctx.input_consumed && ctx.consume_shortcut(vk::ESCAPE) {\n focus_path_pop_min = 1;\n }\n\n // Remove any unknown nodes from the focus path.\n // It's important that we do this after the tree has been swapped out,\n // so that pop_focusable_node() has access to the newest version of the tree.\n needs_settling |= self.pop_focusable_node(focus_path_pop_min);\n\n // `needs_more_settling()` depends on the current value\n // of `settling_have` and so we increment it first.\n self.settling_have += 1;\n\n if needs_settling {\n self.needs_more_settling();\n }\n\n // Remove cached text editors that are no longer in use.\n self.cached_text_buffers.retain(|c| c.seen);\n\n for root in Tree::iterate_siblings(Some(self.prev_tree.root_first)) {\n let mut root = root.borrow_mut();\n root.compute_intrinsic_size();\n }\n\n let viewport = self.size.as_rect();\n\n for root in Tree::iterate_siblings(Some(self.prev_tree.root_first)) {\n let mut root = root.borrow_mut();\n let root = &mut *root;\n\n if let Some(float) = &root.attributes.float {\n let mut x = 0;\n let mut y = 0;\n\n if let Some(node) = root.parent {\n let node = node.borrow();\n x = node.outer.left;\n y = node.outer.top;\n }\n\n let size = root.intrinsic_to_outer();\n\n x += (float.offset_x - float.gravity_x * size.width as f32) as CoordType;\n y += (float.offset_y - float.gravity_y * size.height as f32) as CoordType;\n\n root.outer.left = x;\n root.outer.top = y;\n root.outer.right = x + size.width;\n root.outer.bottom = y + size.height;\n root.outer = root.outer.intersect(viewport);\n } else {\n root.outer = viewport;\n }\n\n root.inner = root.outer_to_inner(root.outer);\n root.outer_clipped = root.outer;\n root.inner_clipped = root.inner;\n\n let outer = root.outer;\n root.layout_children(outer);\n }\n }\n\n fn build_node_path(node: Option<&NodeCell>, path: &mut Vec) {\n path.clear();\n if let Some(mut node) = node {\n loop {\n let n = node.borrow();\n path.push(n.id);\n node = match n.parent {\n Some(parent) => parent,\n None => break,\n };\n }\n path.reverse();\n } else {\n path.push(ROOT_ID);\n }\n }\n\n fn clean_node_path(path: &mut Vec) {\n Self::build_node_path(None, path);\n }\n\n /// After you finished processing all input, continue redrawing your UI until this returns false.\n pub fn needs_settling(&mut self) -> bool {\n self.settling_have <= self.settling_want\n }\n\n fn needs_more_settling(&mut self) {\n // If the focus has changed, the new node may need to be re-rendered.\n // Same, every time we encounter a previously unknown node via `get_prev_node`,\n // because that means it likely failed to get crucial information such as the layout size.\n if cfg!(debug_assertions) && self.settling_have == 15 {\n breakpoint();\n }\n self.settling_want = (self.settling_have + 1).min(20);\n }\n\n /// Renders the last frame into the framebuffer and returns the VT output.\n pub fn render<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n self.framebuffer.flip(self.size);\n for child in self.prev_tree.iterate_roots() {\n let mut child = child.borrow_mut();\n self.render_node(&mut child);\n }\n self.framebuffer.render(arena)\n }\n\n /// Recursively renders each node and its children.\n #[allow(clippy::only_used_in_recursion)]\n fn render_node(&mut self, node: &mut Node) {\n let outer_clipped = node.outer_clipped;\n if outer_clipped.is_empty() {\n return;\n }\n\n let scratch = scratch_arena(None);\n\n if node.attributes.bordered {\n // ┌────┐\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('┌');\n fill.push_repeat('─', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('┐');\n self.framebuffer.replace_text(\n outer_clipped.top,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n\n // │ │\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('│');\n fill.push_repeat(' ', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('│');\n\n for y in outer_clipped.top + 1..outer_clipped.bottom - 1 {\n self.framebuffer.replace_text(\n y,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n // └────┘\n {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push('└');\n fill.push_repeat('─', (outer_clipped.right - outer_clipped.left - 2) as usize);\n fill.push('┘');\n self.framebuffer.replace_text(\n outer_clipped.bottom - 1,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n if node.attributes.float.is_some() {\n if !node.attributes.bordered {\n let mut fill = ArenaString::new_in(&scratch);\n fill.push_repeat(' ', (outer_clipped.right - outer_clipped.left) as usize);\n\n for y in outer_clipped.top..outer_clipped.bottom {\n self.framebuffer.replace_text(\n y,\n outer_clipped.left,\n outer_clipped.right,\n &fill,\n );\n }\n }\n\n self.framebuffer.replace_attr(outer_clipped, Attributes::All, Attributes::None);\n\n if matches!(node.content, NodeContent::Modal(_)) {\n let rect =\n Rect { left: 0, top: 0, right: self.size.width, bottom: self.size.height };\n let dim = self.indexed_alpha(IndexedColor::Background, 1, 2);\n self.framebuffer.blend_bg(rect, dim);\n self.framebuffer.blend_fg(rect, dim);\n }\n }\n\n self.framebuffer.blend_bg(outer_clipped, node.attributes.bg);\n self.framebuffer.blend_fg(outer_clipped, node.attributes.fg);\n\n if node.attributes.reverse {\n self.framebuffer.reverse(outer_clipped);\n }\n\n let inner = node.inner;\n let inner_clipped = node.inner_clipped;\n if inner_clipped.is_empty() {\n return;\n }\n\n match &mut node.content {\n NodeContent::Modal(title) => {\n if !title.is_empty() {\n self.framebuffer.replace_text(\n node.outer.top,\n node.outer.left + 2,\n node.outer.right - 1,\n title,\n );\n }\n }\n NodeContent::Text(content) => self.render_styled_text(\n inner,\n node.intrinsic_size.width,\n &content.text,\n &content.chunks,\n content.overflow,\n ),\n NodeContent::Textarea(tc) => {\n let mut tb = tc.buffer.borrow_mut();\n let mut destination = Rect {\n left: inner_clipped.left,\n top: inner_clipped.top,\n right: inner_clipped.right,\n bottom: inner_clipped.bottom,\n };\n\n if !tc.single_line {\n // Account for the scrollbar.\n destination.right -= 1;\n }\n\n if let Some(res) =\n tb.render(tc.scroll_offset, destination, tc.has_focus, &mut self.framebuffer)\n {\n tc.scroll_offset_x_max = res.visual_pos_x_max;\n }\n\n if !tc.single_line {\n // Render the scrollbar.\n let track = Rect {\n left: inner_clipped.right - 1,\n top: inner_clipped.top,\n right: inner_clipped.right,\n bottom: inner_clipped.bottom,\n };\n tc.thumb_height = self.framebuffer.draw_scrollbar(\n inner_clipped,\n track,\n tc.scroll_offset.y,\n tb.visual_line_count() + inner.height() - 1,\n );\n }\n }\n NodeContent::Scrollarea(sc) => {\n let content = node.children.first.unwrap().borrow();\n let track = Rect {\n left: inner.right,\n top: inner.top,\n right: inner.right + 1,\n bottom: inner.bottom,\n };\n sc.thumb_height = self.framebuffer.draw_scrollbar(\n outer_clipped,\n track,\n sc.scroll_offset.y,\n content.intrinsic_size.height,\n );\n }\n _ => {}\n }\n\n for child in Tree::iterate_siblings(node.children.first) {\n let mut child = child.borrow_mut();\n self.render_node(&mut child);\n }\n }\n\n fn render_styled_text(\n &mut self,\n target: Rect,\n actual_width: CoordType,\n text: &str,\n chunks: &[StyledTextChunk],\n overflow: Overflow,\n ) {\n let target_width = target.width();\n // The section of `text` that is skipped by the ellipsis.\n let mut skipped = 0..0;\n // The number of columns skipped by the ellipsis.\n let mut skipped_cols = 0;\n\n if overflow == Overflow::Clip || target_width >= actual_width {\n self.framebuffer.replace_text(target.top, target.left, target.right, text);\n } else {\n let bytes = text.as_bytes();\n let mut cfg = unicode::MeasurementConfig::new(&bytes);\n\n match overflow {\n Overflow::Clip => unreachable!(),\n Overflow::TruncateHead => {\n let beg = cfg.goto_visual(Point { x: actual_width - target_width + 1, y: 0 });\n skipped = 0..beg.offset;\n skipped_cols = beg.visual_pos.x - 1;\n }\n Overflow::TruncateMiddle => {\n let mid_beg_x = (target_width - 1) / 2;\n let mid_end_x = actual_width - target_width / 2;\n let beg = cfg.goto_visual(Point { x: mid_beg_x, y: 0 });\n let end = cfg.goto_visual(Point { x: mid_end_x, y: 0 });\n skipped = beg.offset..end.offset;\n skipped_cols = end.visual_pos.x - beg.visual_pos.x - 1;\n }\n Overflow::TruncateTail => {\n let end = cfg.goto_visual(Point { x: target_width - 1, y: 0 });\n skipped_cols = actual_width - end.visual_pos.x - 1;\n skipped = end.offset..text.len();\n }\n }\n\n let scratch = scratch_arena(None);\n\n let mut modified = ArenaString::new_in(&scratch);\n modified.reserve(text.len() + 3);\n modified.push_str(&text[..skipped.start]);\n modified.push('…');\n modified.push_str(&text[skipped.end..]);\n\n self.framebuffer.replace_text(target.top, target.left, target.right, &modified);\n }\n\n if !chunks.is_empty() {\n let bytes = text.as_bytes();\n let mut cfg = unicode::MeasurementConfig::new(&bytes).with_cursor(unicode::Cursor {\n visual_pos: Point { x: target.left, y: 0 },\n ..Default::default()\n });\n\n let mut iter = chunks.iter().peekable();\n\n while let Some(chunk) = iter.next() {\n let beg = chunk.offset;\n let end = iter.peek().map_or(text.len(), |c| c.offset);\n\n if beg >= skipped.start && end <= skipped.end {\n // Chunk is fully inside the text skipped by the ellipsis.\n // We don't need to render it at all.\n continue;\n }\n\n if beg < skipped.start {\n let beg = cfg.goto_offset(beg).visual_pos.x;\n let end = cfg.goto_offset(end.min(skipped.start)).visual_pos.x;\n let rect =\n Rect { left: beg, top: target.top, right: end, bottom: target.bottom };\n self.framebuffer.blend_fg(rect, chunk.fg);\n self.framebuffer.replace_attr(rect, chunk.attr, chunk.attr);\n }\n\n if end > skipped.end {\n let beg = cfg.goto_offset(beg.max(skipped.end)).visual_pos.x - skipped_cols;\n let end = cfg.goto_offset(end).visual_pos.x - skipped_cols;\n let rect =\n Rect { left: beg, top: target.top, right: end, bottom: target.bottom };\n self.framebuffer.blend_fg(rect, chunk.fg);\n self.framebuffer.replace_attr(rect, chunk.attr, chunk.attr);\n }\n }\n }\n }\n\n /// Outputs a debug string of the layout and focus tree.\n pub fn debug_layout<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n let mut result = ArenaString::new_in(arena);\n result.push_str(\"general:\\r\\n- focus_path:\\r\\n\");\n\n for &id in &self.focused_node_path {\n _ = write!(result, \" - {id:016x}\\r\\n\");\n }\n\n result.push_str(\"\\r\\ntree:\\r\\n\");\n\n for root in self.prev_tree.iterate_roots() {\n Tree::visit_all(root, root, true, |node| {\n let node = node.borrow();\n let depth = node.depth;\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \"- id: {:016x}\\r\\n\", node.id);\n\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" classname: {}\\r\\n\", node.classname);\n\n if depth == 0\n && let Some(parent) = node.parent\n {\n let parent = parent.borrow();\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" parent: {:016x}\\r\\n\", parent.id);\n }\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" intrinsic: {{{}, {}}}\\r\\n\",\n node.intrinsic_size.width, node.intrinsic_size.height\n );\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" outer: {{{}, {}, {}, {}}}\\r\\n\",\n node.outer.left, node.outer.top, node.outer.right, node.outer.bottom\n );\n\n result.push_repeat(' ', depth * 2);\n _ = write!(\n result,\n \" inner: {{{}, {}, {}, {}}}\\r\\n\",\n node.inner.left, node.inner.top, node.inner.right, node.inner.bottom\n );\n\n if node.attributes.bordered {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" bordered: true\\r\\n\");\n }\n\n if node.attributes.bg != 0 {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" bg: #{:08x}\\r\\n\", node.attributes.bg);\n }\n\n if node.attributes.fg != 0 {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" fg: #{:08x}\\r\\n\", node.attributes.fg);\n }\n\n if self.is_node_focused(node.id) {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" focused: true\\r\\n\");\n }\n\n match &node.content {\n NodeContent::Text(content) => {\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" text: \\\"{}\\\"\\r\\n\", &content.text);\n }\n NodeContent::Textarea(content) => {\n let tb = content.buffer.borrow();\n let tb = &*tb;\n result.push_repeat(' ', depth * 2);\n _ = write!(result, \" textarea: {tb:p}\\r\\n\");\n }\n NodeContent::Scrollarea(..) => {\n result.push_repeat(' ', depth * 2);\n result.push_str(\" scrollable: true\\r\\n\");\n }\n _ => {}\n }\n\n VisitControl::Continue\n });\n }\n\n result\n }\n\n fn was_mouse_down_on_node(&self, id: u64) -> bool {\n self.mouse_down_node_path.last() == Some(&id)\n }\n\n fn was_mouse_down_on_subtree(&self, node: &Node) -> bool {\n self.mouse_down_node_path.get(node.depth) == Some(&node.id)\n }\n\n fn is_node_focused(&self, id: u64) -> bool {\n // We construct the focused_node_path always with at least 1 element (the root id).\n unsafe { *self.focused_node_path.last().unwrap_unchecked() == id }\n }\n\n fn is_subtree_focused(&self, node: &Node) -> bool {\n self.focused_node_path.get(node.depth) == Some(&node.id)\n }\n\n fn is_subtree_focused_alt(&self, id: u64, depth: usize) -> bool {\n self.focused_node_path.get(depth) == Some(&id)\n }\n\n fn pop_focusable_node(&mut self, pop_minimum: usize) -> bool {\n let last_before = self.focused_node_path.last().cloned().unwrap_or(0);\n\n // Remove `pop_minimum`-many nodes from the end of the focus path.\n let path = &self.focused_node_path[..];\n let path = &path[..path.len().saturating_sub(pop_minimum)];\n let mut len = 0;\n\n for (i, &id) in path.iter().enumerate() {\n // Truncate the path so that it only contains nodes that still exist.\n let Some(node) = self.prev_node_map.get(id) else {\n break;\n };\n\n let n = node.borrow();\n // If the caller requested upward movement, pop out of the current focus void, if any.\n // This is kind of janky, to be fair.\n if pop_minimum != 0 && n.attributes.focus_void {\n break;\n }\n\n // Skip over those that aren't focusable.\n if n.attributes.focusable {\n // At this point `n.depth == i` should be true,\n // but I kind of don't want to rely on that.\n len = i + 1;\n }\n }\n\n self.focused_node_path.truncate(len);\n\n // If it's empty now, push `ROOT_ID` because there must always be >=1 element.\n if self.focused_node_path.is_empty() {\n self.focused_node_path.push(ROOT_ID);\n }\n\n // Return true if the focus path changed.\n let last_after = self.focused_node_path.last().cloned().unwrap_or(0);\n last_before != last_after\n }\n\n // Scroll the focused node(s) into view inside scrollviews\n fn scroll_to_focused(&mut self) -> bool {\n let focused_id = self.focused_node_path.last().cloned().unwrap_or(0);\n if self.focused_node_for_scrolling == focused_id {\n return false;\n }\n\n let Some(node) = self.prev_node_map.get(focused_id) else {\n // Node not found because we're using the old layout tree.\n // Retry in the next rendering loop.\n return true;\n };\n\n let mut node = node.borrow_mut();\n let mut scroll_to = node.outer;\n\n while node.parent.is_some() && node.attributes.float.is_none() {\n let n = &mut *node;\n if let NodeContent::Scrollarea(sc) = &mut n.content {\n let off_y = sc.scroll_offset.y.max(0);\n let mut y = off_y;\n y = y.min(scroll_to.top - n.inner.top + off_y);\n y = y.max(scroll_to.bottom - n.inner.bottom + off_y);\n sc.scroll_offset.y = y;\n scroll_to = n.outer;\n }\n node = node.parent.unwrap().borrow_mut();\n }\n\n self.focused_node_for_scrolling = focused_id;\n true\n }\n}\n\n/// Context is a temporary object that is created for each frame.\n/// Its primary purpose is to build a UI tree.\npub struct Context<'a, 'input> {\n tui: &'a mut Tui,\n\n /// Current text input, if any.\n input_text: Option<&'input str>,\n /// Current keyboard input, if any.\n input_keyboard: Option,\n input_mouse_modifiers: InputKeyMod,\n input_mouse_click: CoordType,\n /// By how much the mouse wheel was scrolled since the last frame.\n input_scroll_delta: Point,\n input_consumed: bool,\n\n tree: Tree<'a>,\n last_modal: Option<&'a NodeCell<'a>>,\n focused_node: Option<&'a NodeCell<'a>>,\n next_block_id_mixin: u64,\n needs_settling: bool,\n\n #[cfg(debug_assertions)]\n seen_ids: HashSet,\n}\n\nimpl<'a> Drop for Context<'a, '_> {\n fn drop(&mut self) {\n let tui: &'a mut Tui = unsafe { mem::transmute(&mut *self.tui) };\n tui.report_context_completion(self);\n }\n}\n\nimpl<'a> Context<'a, '_> {\n /// Get an arena for temporary allocations such as for [`arena_format`].\n pub fn arena(&self) -> &'a Arena {\n // TODO:\n // `Context` borrows `Tui` for lifetime 'a, so `self.tui` should be `&'a Tui`, right?\n // And if I do `&self.tui.arena` then that should be 'a too, right?\n // Searching for and failing to find a workaround for this was _very_ annoying.\n //\n // SAFETY: Both the returned reference and its allocations outlive &self.\n unsafe { mem::transmute::<&'_ Arena, &'a Arena>(&self.tui.arena_next) }\n }\n\n /// Returns the viewport size.\n pub fn size(&self) -> Size {\n self.tui.size()\n }\n\n /// Returns an indexed color from the framebuffer.\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.tui.framebuffer.indexed(index)\n }\n\n /// Returns an indexed color from the framebuffer with the given alpha.\n /// See [`Framebuffer::indexed_alpha()`].\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n self.tui.framebuffer.indexed_alpha(index, numerator, denominator)\n }\n\n /// Returns a color in contrast with the given color.\n /// See [`Framebuffer::contrasted()`].\n pub fn contrasted(&self, color: u32) -> u32 {\n self.tui.framebuffer.contrasted(color)\n }\n\n /// Returns the clipboard.\n pub fn clipboard_ref(&self) -> &Clipboard {\n &self.tui.clipboard\n }\n\n /// Returns the clipboard (mutable).\n pub fn clipboard_mut(&mut self) -> &mut Clipboard {\n &mut self.tui.clipboard\n }\n\n /// Tell the UI framework that your state changed and you need another layout pass.\n pub fn needs_rerender(&mut self) {\n // If this hits, the call stack is responsible is trying to deadlock you.\n debug_assert!(self.tui.settling_have < 15);\n self.needs_settling = true;\n }\n\n /// Begins a generic UI block (container) with a unique ID derived from the given `classname`.\n pub fn block_begin(&mut self, classname: &'static str) {\n let parent = self.tree.current_node;\n\n let mut id = hash_str(parent.borrow().id, classname);\n if self.next_block_id_mixin != 0 {\n id = hash(id, &self.next_block_id_mixin.to_ne_bytes());\n self.next_block_id_mixin = 0;\n }\n\n // If this hits, you have tried to create a block with the same ID as a previous one\n // somewhere up this call stack. Change the classname, or use next_block_id_mixin().\n // TODO: HashMap\n #[cfg(debug_assertions)]\n if !self.seen_ids.insert(id) {\n panic!(\"Duplicate node ID: {id:x}\");\n }\n\n let node = Tree::alloc_node(self.arena());\n {\n let mut n = node.borrow_mut();\n n.id = id;\n n.classname = classname;\n }\n\n self.tree.push_child(node);\n }\n\n /// Ends the current UI block, returning to its parent container.\n pub fn block_end(&mut self) {\n self.tree.pop_stack();\n self.block_end_move_focus();\n }\n\n fn block_end_move_focus(&mut self) {\n // At this point, it's more like \"focus_well?\" instead of \"focus_well!\".\n let focus_well = self.tree.last_node;\n\n // Remember the focused node, if any, because once the code below runs,\n // we need it for the `Tree::visit_all` call.\n if self.is_focused() {\n self.focused_node = Some(focus_well);\n }\n\n // The mere fact that there's a `focused_node` indicates that we're the\n // first `block_end()` call that's a focus well and also contains the focus.\n let Some(focused) = self.focused_node else {\n return;\n };\n\n // Filter down to nodes that are focus wells and contain the focus. They're\n // basically the \"tab container\". We test for the node depth to ensure that\n // we don't accidentally pick a focus well next to or inside the focused node.\n {\n let n = focus_well.borrow();\n if !n.attributes.focus_well || n.depth > focused.borrow().depth {\n return;\n }\n }\n\n // Filter down to Tab/Shift+Tab inputs.\n if self.input_consumed {\n return;\n }\n let Some(input) = self.input_keyboard else {\n return;\n };\n if !matches!(input, SHIFT_TAB | vk::TAB) {\n return;\n }\n\n let forward = input == vk::TAB;\n let mut focused_start = focused;\n let mut focused_next = focused;\n\n // We may be in a focus void right now (= doesn't want to be tabbed into),\n // so first we must go up the tree until we're outside of it.\n loop {\n if ptr::eq(focused_start, focus_well) {\n // If we hit the root / focus well, we weren't in a focus void,\n // and can reset `focused_before` to the current focused node.\n focused_start = focused;\n break;\n }\n\n focused_start = focused_start.borrow().parent.unwrap();\n if focused_start.borrow().attributes.focus_void {\n break;\n }\n }\n\n Tree::visit_all(focus_well, focused_start, forward, |node| {\n let n = node.borrow();\n if n.attributes.focusable && !ptr::eq(node, focused_start) {\n focused_next = node;\n VisitControl::Stop\n } else if n.attributes.focus_void {\n VisitControl::SkipChildren\n } else {\n VisitControl::Continue\n }\n });\n\n if ptr::eq(focused_next, focused_start) {\n return;\n }\n\n Tui::build_node_path(Some(focused_next), &mut self.tui.focused_node_path);\n self.set_input_consumed();\n self.needs_rerender();\n }\n\n /// Mixes in an extra value to the next UI block's ID for uniqueness.\n /// Use this when you build a list of items with the same classname.\n pub fn next_block_id_mixin(&mut self, id: u64) {\n self.next_block_id_mixin = id;\n }\n\n fn attr_focusable(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focusable = true;\n }\n\n /// If this is the first time the current node is being drawn,\n /// it'll steal the active focus.\n pub fn focus_on_first_present(&mut self) {\n let steal = {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focusable = true;\n self.tui.prev_node_map.get(last_node.id).is_none()\n };\n if steal {\n self.steal_focus();\n }\n }\n\n /// Steals the focus unconditionally.\n pub fn steal_focus(&mut self) {\n self.steal_focus_for(self.tree.last_node);\n }\n\n fn steal_focus_for(&mut self, node: &NodeCell<'a>) {\n if !self.tui.is_node_focused(node.borrow().id) {\n Tui::build_node_path(Some(node), &mut self.tui.focused_node_path);\n self.needs_rerender();\n }\n }\n\n /// If the current node owns the focus, it'll be given to the parent.\n pub fn toss_focus_up(&mut self) {\n if self.tui.pop_focusable_node(1) {\n self.needs_rerender();\n }\n }\n\n /// If the parent node owns the focus, it'll be given to the current node.\n pub fn inherit_focus(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n let Some(parent) = last_node.parent else {\n return;\n };\n\n last_node.attributes.focusable = true;\n\n // Mark the parent as focusable, so that if the user presses Escape,\n // and `block_end` bubbles the focus up the tree, it'll stop on our parent,\n // which will then focus us on the next iteration.\n let mut parent = parent.borrow_mut();\n parent.attributes.focusable = true;\n\n if self.tui.is_node_focused(parent.id) {\n self.needs_rerender();\n self.tui.focused_node_path.push(last_node.id);\n }\n }\n\n /// Causes keyboard focus to be unable to escape this node and its children.\n /// It's a \"well\" because if the focus is inside it, it can't escape.\n pub fn attr_focus_well(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.focus_well = true;\n }\n\n /// Explicitly sets the intrinsic size of the current node.\n /// The intrinsic size is the size the node ideally wants to be.\n pub fn attr_intrinsic_size(&mut self, size: Size) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.intrinsic_size = size;\n last_node.intrinsic_size_set = true;\n }\n\n /// Turns the current node into a floating node,\n /// like a popup, modal or a tooltip.\n pub fn attr_float(&mut self, spec: FloatSpec) {\n let last_node = self.tree.last_node;\n let anchor = {\n let ln = last_node.borrow();\n match spec.anchor {\n Anchor::Last if ln.siblings.prev.is_some() => ln.siblings.prev,\n Anchor::Last | Anchor::Parent => ln.parent,\n // By not giving such floats a parent, they get the same origin as the original root node,\n // but they also gain their own \"root id\" in the tree. That way, their focus path is totally unique,\n // which means that we can easily check if a modal is open by calling `is_focused()` on the original root.\n Anchor::Root => None,\n }\n };\n\n self.tree.move_node_to_root(last_node, anchor);\n\n let mut ln = last_node.borrow_mut();\n ln.attributes.focus_well = true;\n ln.attributes.float = Some(FloatAttributes {\n gravity_x: spec.gravity_x.clamp(0.0, 1.0),\n gravity_y: spec.gravity_y.clamp(0.0, 1.0),\n offset_x: spec.offset_x,\n offset_y: spec.offset_y,\n });\n ln.attributes.bg = self.tui.floater_default_bg;\n ln.attributes.fg = self.tui.floater_default_fg;\n }\n\n /// Gives the current node a border.\n pub fn attr_border(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.bordered = true;\n }\n\n /// Sets the current node's position inside the parent.\n pub fn attr_position(&mut self, align: Position) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.position = align;\n }\n\n /// Assigns padding to the current node.\n pub fn attr_padding(&mut self, padding: Rect) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.padding = Self::normalize_rect(padding);\n }\n\n fn normalize_rect(rect: Rect) -> Rect {\n Rect {\n left: rect.left.max(0),\n top: rect.top.max(0),\n right: rect.right.max(0),\n bottom: rect.bottom.max(0),\n }\n }\n\n /// Assigns a sRGB background color to the current node.\n pub fn attr_background_rgba(&mut self, bg: u32) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.bg = bg;\n }\n\n /// Assigns a sRGB foreground color to the current node.\n pub fn attr_foreground_rgba(&mut self, fg: u32) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.fg = fg;\n }\n\n /// Applies reverse-video to the current node:\n /// Background and foreground colors are swapped.\n pub fn attr_reverse(&mut self) {\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.attributes.reverse = true;\n }\n\n /// Checks if the current keyboard input matches the given shortcut,\n /// consumes it if it is and returns true in that case.\n pub fn consume_shortcut(&mut self, shortcut: InputKey) -> bool {\n if !self.input_consumed && self.input_keyboard == Some(shortcut) {\n self.set_input_consumed();\n true\n } else {\n false\n }\n }\n\n /// Returns current keyboard input, if any.\n /// Returns None if the input was already consumed.\n pub fn keyboard_input(&self) -> Option {\n if self.input_consumed { None } else { self.input_keyboard }\n }\n\n #[inline]\n pub fn set_input_consumed(&mut self) {\n debug_assert!(!self.input_consumed);\n self.set_input_consumed_unchecked();\n }\n\n #[inline]\n fn set_input_consumed_unchecked(&mut self) {\n self.input_consumed = true;\n }\n\n /// Returns whether the mouse was pressed down on the current node.\n pub fn was_mouse_down(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.was_mouse_down_on_node(last_node.id)\n }\n\n /// Returns whether the mouse was pressed down on the current node's subtree.\n pub fn contains_mouse_down(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.was_mouse_down_on_subtree(&last_node)\n }\n\n /// Returns whether the current node is focused.\n pub fn is_focused(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.is_node_focused(last_node.id)\n }\n\n /// Returns whether the current node's subtree is focused.\n pub fn contains_focus(&mut self) -> bool {\n let last_node = self.tree.last_node.borrow();\n self.tui.is_subtree_focused(&last_node)\n }\n\n /// Begins a modal window. Call [`Context::modal_end()`].\n pub fn modal_begin(&mut self, classname: &'static str, title: &str) {\n self.block_begin(classname);\n self.attr_float(FloatSpec {\n anchor: Anchor::Root,\n gravity_x: 0.5,\n gravity_y: 0.5,\n offset_x: self.tui.size.width as f32 * 0.5,\n offset_y: self.tui.size.height as f32 * 0.5,\n });\n self.attr_border();\n self.attr_background_rgba(self.tui.modal_default_bg);\n self.attr_foreground_rgba(self.tui.modal_default_fg);\n self.attr_focus_well();\n self.focus_on_first_present();\n\n let mut last_node = self.tree.last_node.borrow_mut();\n let title = if title.is_empty() {\n ArenaString::new_in(self.arena())\n } else {\n arena_format!(self.arena(), \" {} \", title)\n };\n last_node.content = NodeContent::Modal(title);\n self.last_modal = Some(self.tree.last_node);\n }\n\n /// Ends the current modal window block.\n /// Returns true if the user pressed Escape (a request to close).\n pub fn modal_end(&mut self) -> bool {\n self.block_end();\n\n // Consume the input unconditionally, so that the root (the \"main window\")\n // doesn't accidentally receive any input via `consume_shortcut()`.\n if self.contains_focus() {\n let exit = !self.input_consumed && self.input_keyboard == Some(vk::ESCAPE);\n self.set_input_consumed_unchecked();\n exit\n } else {\n false\n }\n }\n\n /// Begins a table block. Call [`Context::table_end()`].\n /// Tables are the primary way to create a grid layout,\n /// and to layout controls on a single row (= a table with 1 row).\n pub fn table_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n\n let mut last_node = self.tree.last_node.borrow_mut();\n last_node.content = NodeContent::Table(TableContent {\n columns: Vec::new_in(self.arena()),\n cell_gap: Default::default(),\n });\n }\n\n /// Assigns widths to the columns of the current table.\n /// By default, the table will left-align all columns.\n pub fn table_set_columns(&mut self, columns: &[CoordType]) {\n let mut last_node = self.tree.last_node.borrow_mut();\n if let NodeContent::Table(spec) = &mut last_node.content {\n spec.columns.clear();\n spec.columns.extend_from_slice(columns);\n } else {\n debug_assert!(false);\n }\n }\n\n /// Assigns the gap between cells in the current table.\n pub fn table_set_cell_gap(&mut self, cell_gap: Size) {\n let mut last_node = self.tree.last_node.borrow_mut();\n if let NodeContent::Table(spec) = &mut last_node.content {\n spec.cell_gap = cell_gap;\n } else {\n debug_assert!(false);\n }\n }\n\n /// Starts the next row in the current table.\n pub fn table_next_row(&mut self) {\n {\n let current_node = self.tree.current_node.borrow();\n\n // If this is the first call to table_next_row() inside a new table, the\n // current_node will refer to the table. Otherwise, it'll refer to the current row.\n if !matches!(current_node.content, NodeContent::Table(_)) {\n let Some(parent) = current_node.parent else {\n return;\n };\n\n let parent = parent.borrow();\n // Neither the current nor its parent nodes are a table?\n // You definitely called this outside of a table block.\n debug_assert!(matches!(parent.content, NodeContent::Table(_)));\n\n self.block_end();\n self.table_end_row();\n\n self.next_block_id_mixin(parent.child_count as u64);\n }\n }\n\n self.block_begin(\"row\");\n }\n\n fn table_end_row(&mut self) {\n self.table_move_focus(vk::LEFT, vk::RIGHT);\n }\n\n /// Ends the current table block.\n pub fn table_end(&mut self) {\n let current_node = self.tree.current_node.borrow();\n\n // If this is the first call to table_next_row() inside a new table, the\n // current_node will refer to the table. Otherwise, it'll refer to the current row.\n if !matches!(current_node.content, NodeContent::Table(_)) {\n self.block_end();\n self.table_end_row();\n }\n\n self.block_end(); // table\n self.table_move_focus(vk::UP, vk::DOWN);\n }\n\n fn table_move_focus(&mut self, prev_key: InputKey, next_key: InputKey) {\n // Filter down to table rows that are focused.\n if !self.contains_focus() {\n return;\n }\n\n // Filter down to our prev/next inputs.\n if self.input_consumed {\n return;\n }\n let Some(input) = self.input_keyboard else {\n return;\n };\n if input != prev_key && input != next_key {\n return;\n }\n\n let container = self.tree.last_node;\n let Some(&focused_id) = self.tui.focused_node_path.get(container.borrow().depth + 1) else {\n return;\n };\n\n let mut prev_next = NodeSiblings { prev: None, next: None };\n let mut focused = None;\n\n // Iterate through the cells in the row / the rows in the table, looking for focused_id.\n // Take note of the previous and next focusable cells / rows around the focused one.\n for cell in Tree::iterate_siblings(container.borrow().children.first) {\n let n = cell.borrow();\n if n.id == focused_id {\n focused = Some(cell);\n } else if n.attributes.focusable {\n if focused.is_none() {\n prev_next.prev = Some(cell);\n } else {\n prev_next.next = Some(cell);\n break;\n }\n }\n }\n\n if focused.is_none() {\n return;\n }\n\n let forward = input == next_key;\n let children_idx = if forward { NodeChildren::FIRST } else { NodeChildren::LAST };\n let siblings_idx = if forward { NodeSiblings::NEXT } else { NodeSiblings::PREV };\n let Some(focused_next) =\n prev_next.get(siblings_idx).or_else(|| container.borrow().children.get(children_idx))\n else {\n return;\n };\n\n Tui::build_node_path(Some(focused_next), &mut self.tui.focused_node_path);\n self.set_input_consumed();\n self.needs_rerender();\n }\n\n /// Creates a simple text label.\n pub fn label(&mut self, classname: &'static str, text: &str) {\n self.styled_label_begin(classname);\n self.styled_label_add_text(text);\n self.styled_label_end();\n }\n\n /// Creates a styled text label.\n ///\n /// # Example\n /// ```\n /// use edit::framebuffer::IndexedColor;\n /// use edit::tui::Context;\n ///\n /// fn draw(ctx: &mut Context) {\n /// ctx.styled_label_begin(\"label\");\n /// // Shows \"Hello\" in the inherited foreground color.\n /// ctx.styled_label_add_text(\"Hello\");\n /// // Shows \", World!\" next to \"Hello\" in red.\n /// ctx.styled_label_set_foreground(ctx.indexed(IndexedColor::Red));\n /// ctx.styled_label_add_text(\", World!\");\n /// }\n /// ```\n pub fn styled_label_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n self.tree.last_node.borrow_mut().content = NodeContent::Text(TextContent {\n text: ArenaString::new_in(self.arena()),\n chunks: Vec::with_capacity_in(4, self.arena()),\n overflow: Overflow::Clip,\n });\n }\n\n /// Changes the active pencil color of the current label.\n pub fn styled_label_set_foreground(&mut self, fg: u32) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n let last = content.chunks.last().unwrap_or(&INVALID_STYLED_TEXT_CHUNK);\n if last.offset != content.text.len() && last.fg != fg {\n content.chunks.push(StyledTextChunk {\n offset: content.text.len(),\n fg,\n attr: last.attr,\n });\n }\n }\n\n /// Changes the active pencil attributes of the current label.\n pub fn styled_label_set_attributes(&mut self, attr: Attributes) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n let last = content.chunks.last().unwrap_or(&INVALID_STYLED_TEXT_CHUNK);\n if last.offset != content.text.len() && last.attr != attr {\n content.chunks.push(StyledTextChunk { offset: content.text.len(), fg: last.fg, attr });\n }\n }\n\n /// Adds text to the current label.\n pub fn styled_label_add_text(&mut self, text: &str) {\n let mut node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut node.content else {\n unreachable!();\n };\n\n content.text.push_str(text);\n }\n\n /// Ends the current label block.\n pub fn styled_label_end(&mut self) {\n {\n let mut last_node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &last_node.content else {\n return;\n };\n\n let cursor = unicode::MeasurementConfig::new(&content.text.as_bytes())\n .goto_visual(Point { x: CoordType::MAX, y: 0 });\n last_node.intrinsic_size.width = cursor.visual_pos.x;\n last_node.intrinsic_size.height = 1;\n last_node.intrinsic_size_set = true;\n }\n\n self.block_end();\n }\n\n /// Sets the overflow behavior of the current label.\n pub fn attr_overflow(&mut self, overflow: Overflow) {\n let mut last_node = self.tree.last_node.borrow_mut();\n let NodeContent::Text(content) = &mut last_node.content else {\n return;\n };\n\n content.overflow = overflow;\n }\n\n /// Creates a button with the given text.\n /// Returns true if the button was activated.\n pub fn button(&mut self, classname: &'static str, text: &str, style: ButtonStyle) -> bool {\n self.button_label(classname, text, style);\n self.attr_focusable();\n if self.is_focused() {\n self.attr_reverse();\n }\n self.button_activated()\n }\n\n /// Creates a checkbox with the given text.\n /// Returns true if the checkbox was activated.\n pub fn checkbox(&mut self, classname: &'static str, text: &str, checked: &mut bool) -> bool {\n self.styled_label_begin(classname);\n self.attr_focusable();\n if self.is_focused() {\n self.attr_reverse();\n }\n self.styled_label_add_text(if *checked { \"[🗹 \" } else { \"[☐ \" });\n self.styled_label_add_text(text);\n self.styled_label_add_text(\"]\");\n self.styled_label_end();\n\n let activated = self.button_activated();\n if activated {\n *checked = !*checked;\n }\n activated\n }\n\n fn button_activated(&mut self) -> bool {\n if !self.input_consumed\n && ((self.input_mouse_click != 0 && self.contains_mouse_down())\n || self.input_keyboard == Some(vk::RETURN)\n || self.input_keyboard == Some(vk::SPACE))\n && self.is_focused()\n {\n self.set_input_consumed();\n true\n } else {\n false\n }\n }\n\n /// Creates a text input field.\n /// Returns true if the text contents changed.\n pub fn editline(&mut self, classname: &'static str, text: &mut dyn WriteableDocument) -> bool {\n self.textarea_internal(classname, TextBufferPayload::Editline(text))\n }\n\n /// Creates a text area.\n pub fn textarea(&mut self, classname: &'static str, tb: RcTextBuffer) {\n self.textarea_internal(classname, TextBufferPayload::Textarea(tb));\n }\n\n fn textarea_internal(&mut self, classname: &'static str, payload: TextBufferPayload) -> bool {\n self.block_begin(classname);\n self.block_end();\n\n let mut node = self.tree.last_node.borrow_mut();\n let node = &mut *node;\n let single_line = match &payload {\n TextBufferPayload::Editline(_) => true,\n TextBufferPayload::Textarea(_) => false,\n };\n\n let buffer = {\n let buffers = &mut self.tui.cached_text_buffers;\n\n let cached = match buffers.iter_mut().find(|t| t.node_id == node.id) {\n Some(cached) => {\n if let TextBufferPayload::Textarea(tb) = &payload {\n cached.editor = tb.clone();\n };\n cached.seen = true;\n cached\n }\n None => {\n // If the node is not in the cache, we need to create a new one.\n buffers.push(CachedTextBuffer {\n node_id: node.id,\n editor: match &payload {\n TextBufferPayload::Editline(_) => TextBuffer::new_rc(true).unwrap(),\n TextBufferPayload::Textarea(tb) => tb.clone(),\n },\n seen: true,\n });\n buffers.last_mut().unwrap()\n }\n };\n\n // SAFETY: *Assuming* that there are no duplicate node IDs in the tree that\n // would cause this cache slot to be overwritten, then this operation is safe.\n // The text buffer cache will keep the buffer alive for us long enough.\n unsafe { mem::transmute(&*cached.editor) }\n };\n\n node.content = NodeContent::Textarea(TextareaContent {\n buffer,\n scroll_offset: Default::default(),\n scroll_offset_y_drag_start: CoordType::MIN,\n scroll_offset_x_max: 0,\n thumb_height: 0,\n preferred_column: 0,\n single_line,\n has_focus: self.tui.is_node_focused(node.id),\n });\n\n let content = match node.content {\n NodeContent::Textarea(ref mut content) => content,\n _ => unreachable!(),\n };\n\n if let TextBufferPayload::Editline(text) = &payload {\n content.buffer.borrow_mut().copy_from_str(*text);\n }\n\n if let Some(node_prev) = self.tui.prev_node_map.get(node.id) {\n let node_prev = node_prev.borrow();\n if let NodeContent::Textarea(content_prev) = &node_prev.content {\n content.scroll_offset = content_prev.scroll_offset;\n content.scroll_offset_y_drag_start = content_prev.scroll_offset_y_drag_start;\n content.scroll_offset_x_max = content_prev.scroll_offset_x_max;\n content.thumb_height = content_prev.thumb_height;\n content.preferred_column = content_prev.preferred_column;\n\n let mut text_width = node_prev.inner.width();\n if !single_line {\n // Subtract -1 to account for the scrollbar.\n text_width -= 1;\n }\n\n let mut make_cursor_visible;\n {\n let mut tb = content.buffer.borrow_mut();\n make_cursor_visible = tb.take_cursor_visibility_request();\n make_cursor_visible |= tb.set_width(text_width);\n }\n\n make_cursor_visible |= self.textarea_handle_input(content, &node_prev, single_line);\n\n if make_cursor_visible {\n self.textarea_make_cursor_visible(content, &node_prev);\n }\n } else {\n debug_assert!(false);\n }\n }\n\n let dirty;\n {\n let mut tb = content.buffer.borrow_mut();\n dirty = tb.is_dirty();\n if dirty && let TextBufferPayload::Editline(text) = payload {\n tb.save_as_string(text);\n }\n }\n\n self.textarea_adjust_scroll_offset(content);\n\n if single_line {\n node.attributes.fg = self.indexed(IndexedColor::Foreground);\n node.attributes.bg = self.indexed(IndexedColor::Background);\n if !content.has_focus {\n node.attributes.fg = self.contrasted(node.attributes.bg);\n node.attributes.bg = self.indexed_alpha(IndexedColor::Background, 1, 2);\n }\n }\n\n node.attributes.focusable = true;\n node.intrinsic_size.height = content.buffer.borrow().visual_line_count();\n node.intrinsic_size_set = true;\n\n dirty\n }\n\n fn textarea_handle_input(\n &mut self,\n tc: &mut TextareaContent,\n node_prev: &Node,\n single_line: bool,\n ) -> bool {\n if self.input_consumed {\n return false;\n }\n\n let mut tb = tc.buffer.borrow_mut();\n let tb = &mut *tb;\n let mut make_cursor_visible = false;\n let mut change_preferred_column = false;\n\n if self.tui.mouse_state != InputMouseState::None\n && self.tui.was_mouse_down_on_node(node_prev.id)\n {\n // Scrolling works even if the node isn't focused.\n if self.tui.mouse_state == InputMouseState::Scroll {\n tc.scroll_offset.x += self.input_scroll_delta.x;\n tc.scroll_offset.y += self.input_scroll_delta.y;\n self.set_input_consumed();\n } else if self.tui.is_node_focused(node_prev.id) {\n let mouse = self.tui.mouse_position;\n let inner = node_prev.inner;\n let text_rect = Rect {\n left: inner.left + tb.margin_width(),\n top: inner.top,\n right: inner.right - !single_line as CoordType,\n bottom: inner.bottom,\n };\n let track_rect = Rect {\n left: text_rect.right,\n top: inner.top,\n right: inner.right,\n bottom: inner.bottom,\n };\n let pos = Point {\n x: mouse.x - inner.left - tb.margin_width() + tc.scroll_offset.x,\n y: mouse.y - inner.top + tc.scroll_offset.y,\n };\n\n if text_rect.contains(self.tui.mouse_down_position) {\n if self.tui.mouse_is_drag {\n tb.selection_update_visual(pos);\n tc.preferred_column = tb.cursor_visual_pos().x;\n\n let height = inner.height();\n\n // If the editor is only 1 line tall we can't possibly scroll up or down.\n if height >= 2 {\n fn calc(min: CoordType, max: CoordType, mouse: CoordType) -> CoordType {\n // Otherwise, the scroll zone is up to 3 lines at the top/bottom.\n let zone_height = ((max - min) / 2).min(3);\n\n // The .y positions where the scroll zones begin:\n // Mouse coordinates above top and below bottom respectively.\n let scroll_min = min + zone_height;\n let scroll_max = max - zone_height - 1;\n\n // Calculate the delta for scrolling up or down.\n let delta_min = (mouse - scroll_min).clamp(-zone_height, 0);\n let delta_max = (mouse - scroll_max).clamp(0, zone_height);\n\n // If I didn't mess up my logic here, only one of the two values can possibly be !=0.\n let idx = 3 + delta_min + delta_max;\n\n const SPEEDS: [CoordType; 7] = [-9, -3, -1, 0, 1, 3, 9];\n let idx = idx.clamp(0, SPEEDS.len() as CoordType) as usize;\n SPEEDS[idx]\n }\n\n let delta_x = calc(text_rect.left, text_rect.right, mouse.x);\n let delta_y = calc(text_rect.top, text_rect.bottom, mouse.y);\n\n tc.scroll_offset.x += delta_x;\n tc.scroll_offset.y += delta_y;\n\n if delta_x != 0 || delta_y != 0 {\n self.tui.read_timeout = time::Duration::from_millis(25);\n }\n }\n } else {\n match self.input_mouse_click {\n 5.. => {}\n 4 => tb.select_all(),\n 3 => tb.select_line(),\n 2 => tb.select_word(),\n _ => match self.tui.mouse_state {\n InputMouseState::Left => {\n if self.input_mouse_modifiers.contains(kbmod::SHIFT) {\n // TODO: Untested because Windows Terminal surprisingly doesn't support Shift+Click.\n tb.selection_update_visual(pos);\n } else {\n tb.cursor_move_to_visual(pos);\n }\n tc.preferred_column = tb.cursor_visual_pos().x;\n make_cursor_visible = true;\n }\n _ => return false,\n },\n }\n }\n } else if track_rect.contains(self.tui.mouse_down_position) {\n if self.tui.mouse_state == InputMouseState::Release {\n tc.scroll_offset_y_drag_start = CoordType::MIN;\n } else if self.tui.mouse_is_drag {\n if tc.scroll_offset_y_drag_start == CoordType::MIN {\n tc.scroll_offset_y_drag_start = tc.scroll_offset.y;\n }\n\n // The textarea supports 1 height worth of \"scrolling beyond the end\".\n // `track_height` is the same as the viewport height.\n let scrollable_height = tb.visual_line_count() - 1;\n\n if scrollable_height > 0 {\n let trackable = track_rect.height() - tc.thumb_height;\n let delta_y = mouse.y - self.tui.mouse_down_position.y;\n tc.scroll_offset.y = tc.scroll_offset_y_drag_start\n + (delta_y as i64 * scrollable_height as i64 / trackable as i64)\n as CoordType;\n }\n }\n }\n\n self.set_input_consumed();\n }\n\n return make_cursor_visible;\n }\n\n if !tc.has_focus {\n return false;\n }\n\n let mut write: &[u8] = &[];\n\n if let Some(input) = &self.input_text {\n write = input.as_bytes();\n } else if let Some(input) = &self.input_keyboard {\n let key = input.key();\n let modifiers = input.modifiers();\n\n make_cursor_visible = true;\n\n match key {\n vk::BACK => {\n let granularity = if modifiers == kbmod::CTRL {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n tb.delete(granularity, -1);\n }\n vk::TAB => {\n if single_line {\n // If this is just a simple input field, don't consume Tab (= early return).\n return false;\n }\n tb.indent_change(if modifiers == kbmod::SHIFT { -1 } else { 1 });\n }\n vk::RETURN => {\n if single_line {\n // If this is just a simple input field, don't consume Enter (= early return).\n return false;\n }\n write = b\"\\n\";\n }\n vk::ESCAPE => {\n // If there was a selection, clear it and show the cursor (= fallthrough).\n if !tb.clear_selection() {\n if single_line {\n // If this is just a simple input field, don't consume the escape key\n // (early return) and don't show the cursor (= return false).\n return false;\n }\n\n // If this is a textarea, don't show the cursor if\n // the escape key was pressed and nothing happened.\n make_cursor_visible = false;\n }\n }\n vk::PRIOR => {\n let height = node_prev.inner.height() - 1;\n\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if tb.cursor_visual_pos().y == 0 {\n tc.preferred_column = 0;\n }\n\n if modifiers == kbmod::SHIFT {\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - height,\n });\n } else {\n tb.cursor_move_to_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - height,\n });\n }\n }\n vk::NEXT => {\n let height = node_prev.inner.height() - 1;\n\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if tb.cursor_visual_pos().y >= tb.visual_line_count() - 1 {\n tc.preferred_column = CoordType::MAX;\n }\n\n if modifiers == kbmod::SHIFT {\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + height,\n });\n } else {\n tb.cursor_move_to_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + height,\n });\n }\n\n if tc.preferred_column == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n vk::END => {\n let logical_before = tb.cursor_logical_pos();\n let destination = if modifiers.contains(kbmod::CTRL) {\n Point::MAX\n } else {\n Point { x: CoordType::MAX, y: tb.cursor_visual_pos().y }\n };\n\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_visual(destination);\n } else {\n tb.cursor_move_to_visual(destination);\n }\n\n if !modifiers.contains(kbmod::CTRL) {\n let logical_after = tb.cursor_logical_pos();\n\n // If word-wrap is enabled and the user presses End the first time,\n // it moves to the start of the visual line. The second time they\n // press it, it moves to the start of the logical line.\n if tb.is_word_wrap_enabled() && logical_after == logical_before {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(Point {\n x: CoordType::MAX,\n y: tb.cursor_logical_pos().y,\n });\n } else {\n tb.cursor_move_to_logical(Point {\n x: CoordType::MAX,\n y: tb.cursor_logical_pos().y,\n });\n }\n }\n }\n }\n vk::HOME => {\n let logical_before = tb.cursor_logical_pos();\n let destination = if modifiers.contains(kbmod::CTRL) {\n Default::default()\n } else {\n Point { x: 0, y: tb.cursor_visual_pos().y }\n };\n\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_visual(destination);\n } else {\n tb.cursor_move_to_visual(destination);\n }\n\n if !modifiers.contains(kbmod::CTRL) {\n let mut logical_after = tb.cursor_logical_pos();\n\n // If word-wrap is enabled and the user presses Home the first time,\n // it moves to the start of the visual line. The second time they\n // press it, it moves to the start of the logical line.\n if tb.is_word_wrap_enabled() && logical_after == logical_before {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(Point {\n x: 0,\n y: tb.cursor_logical_pos().y,\n });\n } else {\n tb.cursor_move_to_logical(Point {\n x: 0,\n y: tb.cursor_logical_pos().y,\n });\n }\n logical_after = tb.cursor_logical_pos();\n }\n\n // If the line has some indentation and the user pressed Home,\n // the first time it'll stop at the indentation. The second time\n // they press it, it'll move to the true start of the line.\n //\n // If the cursor is already at the start of the line,\n // we move it back to the end of the indentation.\n if logical_after.x == 0\n && let indent_end = tb.indent_end_logical_pos()\n && (logical_before > indent_end || logical_before.x == 0)\n {\n if modifiers == kbmod::SHIFT {\n tb.selection_update_logical(indent_end);\n } else {\n tb.cursor_move_to_logical(indent_end);\n }\n }\n }\n }\n vk::LEFT => {\n let granularity = if modifiers.contains(KBMOD_FOR_WORD_NAV) {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_delta(granularity, -1);\n } else if let Some((beg, _)) = tb.selection_range() {\n unsafe { tb.set_cursor(beg) };\n } else {\n tb.cursor_move_delta(granularity, -1);\n }\n }\n vk::UP => {\n if single_line {\n return false;\n }\n match modifiers {\n kbmod::NONE => {\n let mut x = tc.preferred_column;\n let mut y = tb.cursor_visual_pos().y - 1;\n\n // If there's a selection we put the cursor above it.\n if let Some((beg, _)) = tb.selection_range() {\n x = beg.visual_pos.x;\n y = beg.visual_pos.y - 1;\n tc.preferred_column = x;\n }\n\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if y < 0 {\n x = 0;\n tc.preferred_column = 0;\n }\n\n tb.cursor_move_to_visual(Point { x, y });\n }\n kbmod::CTRL => {\n tc.scroll_offset.y -= 1;\n make_cursor_visible = false;\n }\n kbmod::SHIFT => {\n // If the cursor was already on the first line,\n // move it to the start of the buffer.\n if tb.cursor_visual_pos().y == 0 {\n tc.preferred_column = 0;\n }\n\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y - 1,\n });\n }\n kbmod::ALT => tb.move_selected_lines(MoveLineDirection::Up),\n kbmod::CTRL_ALT => {\n // TODO: Add cursor above\n }\n _ => return false,\n }\n }\n vk::RIGHT => {\n let granularity = if modifiers.contains(KBMOD_FOR_WORD_NAV) {\n CursorMovement::Word\n } else {\n CursorMovement::Grapheme\n };\n if modifiers.contains(kbmod::SHIFT) {\n tb.selection_update_delta(granularity, 1);\n } else if let Some((_, end)) = tb.selection_range() {\n unsafe { tb.set_cursor(end) };\n } else {\n tb.cursor_move_delta(granularity, 1);\n }\n }\n vk::DOWN => {\n if single_line {\n return false;\n }\n match modifiers {\n kbmod::NONE => {\n let mut x = tc.preferred_column;\n let mut y = tb.cursor_visual_pos().y + 1;\n\n // If there's a selection we put the cursor below it.\n if let Some((_, end)) = tb.selection_range() {\n x = end.visual_pos.x;\n y = end.visual_pos.y + 1;\n tc.preferred_column = x;\n }\n\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if y >= tb.visual_line_count() {\n x = CoordType::MAX;\n }\n\n tb.cursor_move_to_visual(Point { x, y });\n\n // If we fell into the `if y >= tb.get_visual_line_count()` above, we wanted to\n // update the `preferred_column` but didn't know yet what it was. Now we know!\n if x == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n kbmod::CTRL => {\n tc.scroll_offset.y += 1;\n make_cursor_visible = false;\n }\n kbmod::SHIFT => {\n // If the cursor was already on the last line,\n // move it to the end of the buffer.\n if tb.cursor_visual_pos().y >= tb.visual_line_count() - 1 {\n tc.preferred_column = CoordType::MAX;\n }\n\n tb.selection_update_visual(Point {\n x: tc.preferred_column,\n y: tb.cursor_visual_pos().y + 1,\n });\n\n if tc.preferred_column == CoordType::MAX {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n }\n kbmod::ALT => tb.move_selected_lines(MoveLineDirection::Down),\n kbmod::CTRL_ALT => {\n // TODO: Add cursor above\n }\n _ => return false,\n }\n }\n vk::INSERT => match modifiers {\n kbmod::SHIFT => tb.paste(self.clipboard_ref()),\n kbmod::CTRL => tb.copy(self.clipboard_mut()),\n _ => tb.set_overtype(!tb.is_overtype()),\n },\n vk::DELETE => match modifiers {\n kbmod::SHIFT => tb.cut(self.clipboard_mut()),\n kbmod::CTRL => tb.delete(CursorMovement::Word, 1),\n _ => tb.delete(CursorMovement::Grapheme, 1),\n },\n vk::A => match modifiers {\n kbmod::CTRL => tb.select_all(),\n _ => return false,\n },\n vk::B => match modifiers {\n kbmod::ALT if cfg!(target_os = \"macos\") => {\n // On macOS, terminals commonly emit the Emacs style\n // Alt+B (ESC b) sequence for Alt+Left.\n tb.cursor_move_delta(CursorMovement::Word, -1);\n }\n _ => return false,\n },\n vk::F => match modifiers {\n kbmod::ALT if cfg!(target_os = \"macos\") => {\n // On macOS, terminals commonly emit the Emacs style\n // Alt+F (ESC f) sequence for Alt+Right.\n tb.cursor_move_delta(CursorMovement::Word, 1);\n }\n _ => return false,\n },\n vk::H => match modifiers {\n kbmod::CTRL => tb.delete(CursorMovement::Word, -1),\n _ => return false,\n },\n vk::L => match modifiers {\n kbmod::CTRL => tb.select_line(),\n _ => return false,\n },\n vk::X => match modifiers {\n kbmod::CTRL => tb.cut(self.clipboard_mut()),\n _ => return false,\n },\n vk::C => match modifiers {\n kbmod::CTRL => tb.copy(self.clipboard_mut()),\n _ => return false,\n },\n vk::V => match modifiers {\n kbmod::CTRL => tb.paste(self.clipboard_ref()),\n _ => return false,\n },\n vk::Y => match modifiers {\n kbmod::CTRL => tb.redo(),\n _ => return false,\n },\n vk::Z => match modifiers {\n kbmod::CTRL => tb.undo(),\n kbmod::CTRL_SHIFT => tb.redo(),\n kbmod::ALT => tb.set_word_wrap(!tb.is_word_wrap_enabled()),\n _ => return false,\n },\n _ => return false,\n }\n\n change_preferred_column = !matches!(key, vk::PRIOR | vk::NEXT | vk::UP | vk::DOWN);\n } else {\n return false;\n }\n\n if single_line && !write.is_empty() {\n let (end, _) = simd::lines_fwd(write, 0, 0, 1);\n write = unicode::strip_newline(&write[..end]);\n }\n if !write.is_empty() {\n tb.write_canon(write);\n change_preferred_column = true;\n make_cursor_visible = true;\n }\n\n if change_preferred_column {\n tc.preferred_column = tb.cursor_visual_pos().x;\n }\n\n self.set_input_consumed();\n make_cursor_visible\n }\n\n fn textarea_make_cursor_visible(&self, tc: &mut TextareaContent, node_prev: &Node) {\n let tb = tc.buffer.borrow();\n let mut scroll_x = tc.scroll_offset.x;\n let mut scroll_y = tc.scroll_offset.y;\n\n let text_width = tb.text_width();\n let cursor_x = tb.cursor_visual_pos().x;\n scroll_x = scroll_x.min(cursor_x - 10);\n scroll_x = scroll_x.max(cursor_x - text_width + 10);\n\n let viewport_height = node_prev.inner.height();\n let cursor_y = tb.cursor_visual_pos().y;\n // Scroll up if the cursor is above the visible area.\n scroll_y = scroll_y.min(cursor_y);\n // Scroll down if the cursor is below the visible area.\n scroll_y = scroll_y.max(cursor_y - viewport_height + 1);\n\n tc.scroll_offset.x = scroll_x;\n tc.scroll_offset.y = scroll_y;\n }\n\n fn textarea_adjust_scroll_offset(&self, tc: &mut TextareaContent) {\n let tb = tc.buffer.borrow();\n let mut scroll_x = tc.scroll_offset.x;\n let mut scroll_y = tc.scroll_offset.y;\n\n scroll_x = scroll_x.min(tc.scroll_offset_x_max.max(tb.cursor_visual_pos().x) - 10);\n scroll_x = scroll_x.max(0);\n scroll_y = scroll_y.clamp(0, tb.visual_line_count() - 1);\n\n if tb.is_word_wrap_enabled() {\n scroll_x = 0;\n }\n\n tc.scroll_offset.x = scroll_x;\n tc.scroll_offset.y = scroll_y;\n }\n\n /// Creates a scrollable area.\n pub fn scrollarea_begin(&mut self, classname: &'static str, intrinsic_size: Size) {\n self.block_begin(classname);\n\n let container_node = self.tree.last_node;\n {\n let mut container = self.tree.last_node.borrow_mut();\n container.content = NodeContent::Scrollarea(ScrollareaContent {\n scroll_offset: Point::MIN,\n scroll_offset_y_drag_start: CoordType::MIN,\n thumb_height: 0,\n });\n\n if intrinsic_size.width > 0 || intrinsic_size.height > 0 {\n container.intrinsic_size.width = intrinsic_size.width.max(0);\n container.intrinsic_size.height = intrinsic_size.height.max(0);\n container.intrinsic_size_set = true;\n }\n }\n\n self.block_begin(\"content\");\n self.inherit_focus();\n\n // Ensure that attribute modifications apply to the outer container.\n self.tree.last_node = container_node;\n }\n\n /// Scrolls the current scrollable area to the given position.\n pub fn scrollarea_scroll_to(&mut self, pos: Point) {\n let mut container = self.tree.last_node.borrow_mut();\n if let NodeContent::Scrollarea(sc) = &mut container.content {\n sc.scroll_offset = pos;\n } else {\n debug_assert!(false);\n }\n }\n\n /// Ends the current scrollarea block.\n pub fn scrollarea_end(&mut self) {\n self.block_end(); // content block\n self.block_end(); // outer container\n\n let mut container = self.tree.last_node.borrow_mut();\n let container_id = container.id;\n let container_depth = container.depth;\n let Some(prev_container) = self.tui.prev_node_map.get(container_id) else {\n return;\n };\n\n let prev_container = prev_container.borrow();\n let NodeContent::Scrollarea(sc) = &mut container.content else {\n unreachable!();\n };\n\n if sc.scroll_offset == Point::MIN\n && let NodeContent::Scrollarea(sc_prev) = &prev_container.content\n {\n *sc = sc_prev.clone();\n }\n\n if !self.input_consumed {\n if self.tui.mouse_state != InputMouseState::None {\n let container_rect = prev_container.inner;\n\n match self.tui.mouse_state {\n InputMouseState::Left => {\n if self.tui.mouse_is_drag {\n // We don't need to look up the previous track node,\n // since it has a fixed size based on the container size.\n let track_rect = Rect {\n left: container_rect.right,\n top: container_rect.top,\n right: container_rect.right + 1,\n bottom: container_rect.bottom,\n };\n if track_rect.contains(self.tui.mouse_down_position) {\n if sc.scroll_offset_y_drag_start == CoordType::MIN {\n sc.scroll_offset_y_drag_start = sc.scroll_offset.y;\n }\n\n let content = prev_container.children.first.unwrap().borrow();\n let content_rect = content.inner;\n let content_height = content_rect.height();\n let track_height = track_rect.height();\n let scrollable_height = content_height - track_height;\n\n if scrollable_height > 0 {\n let trackable = track_height - sc.thumb_height;\n let delta_y =\n self.tui.mouse_position.y - self.tui.mouse_down_position.y;\n sc.scroll_offset.y = sc.scroll_offset_y_drag_start\n + (delta_y as i64 * scrollable_height as i64\n / trackable as i64)\n as CoordType;\n }\n\n self.set_input_consumed();\n }\n }\n }\n InputMouseState::Release => {\n sc.scroll_offset_y_drag_start = CoordType::MIN;\n }\n InputMouseState::Scroll => {\n if container_rect.contains(self.tui.mouse_position) {\n sc.scroll_offset.x += self.input_scroll_delta.x;\n sc.scroll_offset.y += self.input_scroll_delta.y;\n self.set_input_consumed();\n }\n }\n _ => {}\n }\n } else if self.tui.is_subtree_focused_alt(container_id, container_depth)\n && let Some(key) = self.input_keyboard\n {\n match key {\n vk::PRIOR => sc.scroll_offset.y -= prev_container.inner_clipped.height(),\n vk::NEXT => sc.scroll_offset.y += prev_container.inner_clipped.height(),\n vk::END => sc.scroll_offset.y = CoordType::MAX,\n vk::HOME => sc.scroll_offset.y = 0,\n _ => return,\n }\n self.set_input_consumed();\n }\n }\n }\n\n /// Creates a list where exactly one item is selected.\n pub fn list_begin(&mut self, classname: &'static str) {\n self.block_begin(classname);\n self.attr_focusable();\n\n let mut last_node = self.tree.last_node.borrow_mut();\n let content = self\n .tui\n .prev_node_map\n .get(last_node.id)\n .and_then(|node| match &node.borrow().content {\n NodeContent::List(content) => {\n Some(ListContent { selected: content.selected, selected_node: None })\n }\n _ => None,\n })\n .unwrap_or(ListContent { selected: 0, selected_node: None });\n\n last_node.attributes.focus_void = true;\n last_node.content = NodeContent::List(content);\n }\n\n /// Creates a list item with the given text.\n pub fn list_item(&mut self, select: bool, text: &str) -> ListSelection {\n self.styled_list_item_begin();\n self.styled_label_add_text(text);\n self.styled_list_item_end(select)\n }\n\n /// Creates a list item consisting of a styled label.\n /// See [`Context::styled_label_begin`].\n pub fn styled_list_item_begin(&mut self) {\n let list = self.tree.current_node;\n let idx = list.borrow().child_count;\n\n self.next_block_id_mixin(idx as u64);\n self.styled_label_begin(\"item\");\n self.styled_label_add_text(\" \");\n self.attr_focusable();\n }\n\n /// Ends the current styled list item.\n pub fn styled_list_item_end(&mut self, select: bool) -> ListSelection {\n self.styled_label_end();\n\n let list = self.tree.current_node;\n\n let selected_before;\n let selected_now;\n let focused;\n {\n let mut list = list.borrow_mut();\n let content = match &mut list.content {\n NodeContent::List(content) => content,\n _ => unreachable!(),\n };\n\n let item = self.tree.last_node.borrow();\n let item_id = item.id;\n selected_before = content.selected == item_id;\n focused = self.is_focused();\n\n // Inherit the default selection & Click changes selection\n selected_now = selected_before || (select && content.selected == 0) || focused;\n\n // Note down the selected node for keyboard navigation.\n if selected_now {\n content.selected_node = Some(self.tree.last_node);\n if !selected_before {\n content.selected = item_id;\n self.needs_rerender();\n }\n }\n }\n\n // Clicking an item activates it\n let clicked =\n !self.input_consumed && (self.input_mouse_click == 2 && self.was_mouse_down());\n // Pressing Enter on a selected item activates it as well\n let entered = focused\n && selected_before\n && !self.input_consumed\n && matches!(self.input_keyboard, Some(vk::RETURN));\n let activated = clicked || entered;\n if activated {\n self.set_input_consumed();\n }\n\n if selected_before && activated {\n ListSelection::Activated\n } else if selected_now && !selected_before {\n ListSelection::Selected\n } else {\n ListSelection::Unchanged\n }\n }\n\n /// [`Context::steal_focus`], but for a list view.\n ///\n /// This exists, because didn't want to figure out how to get\n /// [`Context::styled_list_item_end`] to recognize a regular,\n /// programmatic focus steal.\n pub fn list_item_steal_focus(&mut self) {\n self.steal_focus();\n\n match &mut self.tree.current_node.borrow_mut().content {\n NodeContent::List(content) => {\n content.selected = self.tree.last_node.borrow().id;\n content.selected_node = Some(self.tree.last_node);\n }\n _ => unreachable!(),\n }\n }\n\n /// Ends the current list block.\n pub fn list_end(&mut self) {\n self.block_end();\n\n let contains_focus;\n let selected_now;\n let mut selected_next;\n {\n let list = self.tree.last_node.borrow();\n\n contains_focus = self.tui.is_subtree_focused(&list);\n selected_now = match &list.content {\n NodeContent::List(content) => content.selected_node,\n _ => unreachable!(),\n };\n selected_next = match selected_now.or(list.children.first) {\n Some(node) => node,\n None => return,\n };\n }\n\n if contains_focus\n && !self.input_consumed\n && let Some(key) = self.input_keyboard\n && let Some(selected_now) = selected_now\n {\n let list = self.tree.last_node.borrow();\n\n if let Some(prev_container) = self.tui.prev_node_map.get(list.id) {\n let mut consumed = true;\n\n match key {\n vk::PRIOR => {\n selected_next = selected_now;\n for _ in 0..prev_container.borrow().inner_clipped.height() - 1 {\n let node = selected_next.borrow();\n selected_next = match node.siblings.prev {\n Some(node) => node,\n None => break,\n };\n }\n }\n vk::NEXT => {\n selected_next = selected_now;\n for _ in 0..prev_container.borrow().inner_clipped.height() - 1 {\n let node = selected_next.borrow();\n selected_next = match node.siblings.next {\n Some(node) => node,\n None => break,\n };\n }\n }\n vk::END => {\n selected_next = list.children.last.unwrap_or(selected_next);\n }\n vk::HOME => {\n selected_next = list.children.first.unwrap_or(selected_next);\n }\n vk::UP => {\n selected_next = selected_now\n .borrow()\n .siblings\n .prev\n .or(list.children.last)\n .unwrap_or(selected_next);\n }\n vk::DOWN => {\n selected_next = selected_now\n .borrow()\n .siblings\n .next\n .or(list.children.first)\n .unwrap_or(selected_next);\n }\n _ => consumed = false,\n }\n\n if consumed {\n self.set_input_consumed();\n }\n }\n }\n\n // Now that we know which item is selected we can mark it as such.\n if !opt_ptr_eq(selected_now, Some(selected_next))\n && let NodeContent::List(content) = &mut self.tree.last_node.borrow_mut().content\n {\n content.selected_node = Some(selected_next);\n }\n\n // Now that we know which item is selected we can mark it as such.\n if let NodeContent::Text(content) = &mut selected_next.borrow_mut().content {\n unsafe {\n content.text.as_bytes_mut()[0] = b'>';\n }\n }\n\n // If the list has focus, we also delegate focus to the selected item and colorize it.\n if contains_focus {\n {\n let mut node = selected_next.borrow_mut();\n node.attributes.bg = self.indexed(IndexedColor::Green);\n node.attributes.fg = self.contrasted(self.indexed(IndexedColor::Green));\n }\n self.steal_focus_for(selected_next);\n }\n }\n\n /// Creates a menubar, to be shown at the top of the screen.\n pub fn menubar_begin(&mut self) {\n self.table_begin(\"menubar\");\n self.attr_focus_well();\n self.table_next_row();\n }\n\n /// Appends a menu to the current menubar.\n ///\n /// Returns true if the menu is open. Continue appending items to it in that case.\n pub fn menubar_menu_begin(&mut self, text: &str, accelerator: char) -> bool {\n let accelerator = if cfg!(target_os = \"macos\") { '\\0' } else { accelerator };\n let mixin = self.tree.current_node.borrow().child_count as u64;\n self.next_block_id_mixin(mixin);\n\n self.button_label(\n \"menu_button\",\n text,\n ButtonStyle::default().accelerator(accelerator).bracketed(false),\n );\n self.attr_focusable();\n self.attr_padding(Rect::two(0, 1));\n\n let contains_focus = self.contains_focus();\n let keyboard_focus = accelerator != '\\0'\n && !contains_focus\n && self.consume_shortcut(kbmod::ALT | InputKey::new(accelerator as u32));\n\n if contains_focus || keyboard_focus {\n self.attr_background_rgba(self.tui.floater_default_bg);\n self.attr_foreground_rgba(self.tui.floater_default_fg);\n\n if self.is_focused() {\n self.attr_background_rgba(self.indexed(IndexedColor::Green));\n self.attr_foreground_rgba(self.contrasted(self.indexed(IndexedColor::Green)));\n }\n\n self.next_block_id_mixin(mixin);\n self.table_begin(\"flyout\");\n self.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 0.0,\n offset_x: 0.0,\n offset_y: 1.0,\n });\n self.attr_border();\n self.attr_focus_well();\n\n if keyboard_focus {\n self.steal_focus();\n }\n\n true\n } else {\n false\n }\n }\n\n /// Appends a button to the current menu.\n pub fn menubar_menu_button(\n &mut self,\n text: &str,\n accelerator: char,\n shortcut: InputKey,\n ) -> bool {\n self.menubar_menu_checkbox(text, accelerator, shortcut, false)\n }\n\n /// Appends a checkbox to the current menu.\n /// Returns true if the checkbox was activated.\n pub fn menubar_menu_checkbox(\n &mut self,\n text: &str,\n accelerator: char,\n shortcut: InputKey,\n checked: bool,\n ) -> bool {\n self.table_next_row();\n self.attr_focusable();\n\n // First menu item? Steal focus.\n if self.tree.current_node.borrow_mut().siblings.prev.is_none() {\n self.inherit_focus();\n }\n\n if self.is_focused() {\n self.attr_background_rgba(self.indexed(IndexedColor::Green));\n self.attr_foreground_rgba(self.contrasted(self.indexed(IndexedColor::Green)));\n }\n\n let clicked =\n self.button_activated() || self.consume_shortcut(InputKey::new(accelerator as u32));\n\n self.button_label(\n \"menu_checkbox\",\n text,\n ButtonStyle::default().bracketed(false).checked(checked).accelerator(accelerator),\n );\n self.menubar_shortcut(shortcut);\n\n if clicked {\n // TODO: This should reassign the previous focused path.\n self.needs_rerender();\n Tui::clean_node_path(&mut self.tui.focused_node_path);\n }\n\n clicked\n }\n\n /// Ends the current menu.\n pub fn menubar_menu_end(&mut self) {\n self.table_end();\n\n if !self.input_consumed\n && let Some(key) = self.input_keyboard\n && matches!(key, vk::ESCAPE | vk::UP | vk::DOWN)\n {\n if matches!(key, vk::UP | vk::DOWN) {\n // If the focus is on the menubar, and the user presses up/down,\n // focus the first/last item of the flyout respectively.\n let ln = self.tree.last_node.borrow();\n if self.tui.is_node_focused(ln.parent.map_or(0, |n| n.borrow().id)) {\n let selected_next =\n if key == vk::UP { ln.children.last } else { ln.children.first };\n if let Some(selected_next) = selected_next {\n self.steal_focus_for(selected_next);\n self.set_input_consumed();\n }\n }\n } else if self.contains_focus() {\n // Otherwise, if the menu is the focused one and the\n // user presses Escape, pass focus back to the menubar.\n self.tui.pop_focusable_node(1);\n }\n }\n }\n\n /// Ends the current menubar.\n pub fn menubar_end(&mut self) {\n self.table_end();\n }\n\n /// Renders a button label with an optional accelerator character\n /// May also renders a checkbox or square brackets for inline buttons\n fn button_label(&mut self, classname: &'static str, text: &str, style: ButtonStyle) {\n // Label prefix\n self.styled_label_begin(classname);\n if style.bracketed {\n self.styled_label_add_text(\"[\");\n }\n if let Some(checked) = style.checked {\n self.styled_label_add_text(if checked { \"🗹 \" } else { \" \" });\n }\n // Label text\n match style.accelerator {\n Some(accelerator) if accelerator.is_ascii_uppercase() => {\n // Complex case:\n // Locate the offset of the accelerator character in the label text\n let mut off = text.len();\n for (i, c) in text.bytes().enumerate() {\n // Perfect match (uppercase character) --> stop\n if c as char == accelerator {\n off = i;\n break;\n }\n // Inexact match (lowercase character) --> use first hit\n if (c & !0x20) as char == accelerator && off == text.len() {\n off = i;\n }\n }\n\n if off < text.len() {\n // Add an underline to the accelerator.\n self.styled_label_add_text(&text[..off]);\n self.styled_label_set_attributes(Attributes::Underlined);\n self.styled_label_add_text(&text[off..off + 1]);\n self.styled_label_set_attributes(Attributes::None);\n self.styled_label_add_text(&text[off + 1..]);\n } else {\n // Add the accelerator in parentheses and underline it.\n let ch = accelerator as u8;\n self.styled_label_add_text(text);\n self.styled_label_add_text(\"(\");\n self.styled_label_set_attributes(Attributes::Underlined);\n self.styled_label_add_text(unsafe { str_from_raw_parts(&ch, 1) });\n self.styled_label_set_attributes(Attributes::None);\n self.styled_label_add_text(\")\");\n }\n }\n _ => {\n // Simple case:\n // no accelerator character\n self.styled_label_add_text(text);\n }\n }\n // Label postfix\n if style.bracketed {\n self.styled_label_add_text(\"]\");\n }\n self.styled_label_end();\n }\n\n fn menubar_shortcut(&mut self, shortcut: InputKey) {\n let shortcut_letter = shortcut.value() as u8 as char;\n if shortcut_letter.is_ascii_uppercase() {\n let mut shortcut_text = ArenaString::new_in(self.arena());\n if shortcut.modifiers_contains(kbmod::CTRL) {\n shortcut_text.push_str(self.tui.modifier_translations.ctrl);\n shortcut_text.push('+');\n }\n if shortcut.modifiers_contains(kbmod::ALT) {\n shortcut_text.push_str(self.tui.modifier_translations.alt);\n shortcut_text.push('+');\n }\n if shortcut.modifiers_contains(kbmod::SHIFT) {\n shortcut_text.push_str(self.tui.modifier_translations.shift);\n shortcut_text.push('+');\n }\n shortcut_text.push(shortcut_letter);\n\n self.label(\"shortcut\", &shortcut_text);\n } else {\n self.block_begin(\"shortcut\");\n self.block_end();\n }\n self.attr_padding(Rect { left: 2, top: 0, right: 2, bottom: 0 });\n }\n}\n\n/// See [`Tree::visit_all`].\n#[derive(Clone, Copy)]\nenum VisitControl {\n Continue,\n SkipChildren,\n Stop,\n}\n\n/// Stores the root of the \"DOM\" tree of the UI.\nstruct Tree<'a> {\n tail: &'a NodeCell<'a>,\n root_first: &'a NodeCell<'a>,\n root_last: &'a NodeCell<'a>,\n last_node: &'a NodeCell<'a>,\n current_node: &'a NodeCell<'a>,\n\n count: usize,\n checksum: u64,\n}\n\nimpl<'a> Tree<'a> {\n /// Creates a new tree inside the given arena.\n /// A single root node is added for the main contents.\n fn new(arena: &'a Arena) -> Self {\n let root = Self::alloc_node(arena);\n {\n let mut r = root.borrow_mut();\n r.id = ROOT_ID;\n r.classname = \"root\";\n r.attributes.focusable = true;\n r.attributes.focus_well = true;\n }\n Self {\n tail: root,\n root_first: root,\n root_last: root,\n last_node: root,\n current_node: root,\n count: 1,\n checksum: ROOT_ID,\n }\n }\n\n fn alloc_node(arena: &'a Arena) -> &'a NodeCell<'a> {\n arena.alloc_uninit().write(Default::default())\n }\n\n /// Appends a child node to the current node.\n fn push_child(&mut self, node: &'a NodeCell<'a>) {\n let mut n = node.borrow_mut();\n n.parent = Some(self.current_node);\n n.stack_parent = Some(self.current_node);\n\n {\n let mut p = self.current_node.borrow_mut();\n n.siblings.prev = p.children.last;\n n.depth = p.depth + 1;\n\n if let Some(child_last) = p.children.last {\n let mut child_last = child_last.borrow_mut();\n child_last.siblings.next = Some(node);\n }\n if p.children.first.is_none() {\n p.children.first = Some(node);\n }\n p.children.last = Some(node);\n p.child_count += 1;\n }\n\n n.prev = Some(self.tail);\n {\n let mut tail = self.tail.borrow_mut();\n tail.next = Some(node);\n }\n self.tail = node;\n\n self.last_node = node;\n self.current_node = node;\n self.count += 1;\n // wymix is weak, but both checksum and node.id are proper random, so... it's not *that* bad.\n self.checksum = wymix(self.checksum, n.id);\n }\n\n /// Removes the current node from its parent and appends it as a new root.\n /// Used for [`Context::attr_float`].\n fn move_node_to_root(&mut self, node: &'a NodeCell<'a>, anchor: Option<&'a NodeCell<'a>>) {\n let mut n = node.borrow_mut();\n let Some(parent) = n.parent else {\n return;\n };\n\n if let Some(sibling_prev) = n.siblings.prev {\n let mut sibling_prev = sibling_prev.borrow_mut();\n sibling_prev.siblings.next = n.siblings.next;\n }\n if let Some(sibling_next) = n.siblings.next {\n let mut sibling_next = sibling_next.borrow_mut();\n sibling_next.siblings.prev = n.siblings.prev;\n }\n\n {\n let mut p = parent.borrow_mut();\n if opt_ptr_eq(p.children.first, Some(node)) {\n p.children.first = n.siblings.next;\n }\n if opt_ptr_eq(p.children.last, Some(node)) {\n p.children.last = n.siblings.prev;\n }\n p.child_count -= 1;\n }\n\n n.parent = anchor;\n n.depth = anchor.map_or(0, |n| n.borrow().depth + 1);\n n.siblings.prev = Some(self.root_last);\n n.siblings.next = None;\n\n self.root_last.borrow_mut().siblings.next = Some(node);\n self.root_last = node;\n }\n\n /// Completes the current node and moves focus to the parent.\n fn pop_stack(&mut self) {\n let current_node = self.current_node.borrow();\n if let Some(stack_parent) = current_node.stack_parent {\n self.last_node = self.current_node;\n self.current_node = stack_parent;\n }\n }\n\n fn iterate_siblings(\n mut node: Option<&'a NodeCell<'a>>,\n ) -> impl Iterator> + use<'a> {\n iter::from_fn(move || {\n let n = node?;\n node = n.borrow().siblings.next;\n Some(n)\n })\n }\n\n fn iterate_siblings_rev(\n mut node: Option<&'a NodeCell<'a>>,\n ) -> impl Iterator> + use<'a> {\n iter::from_fn(move || {\n let n = node?;\n node = n.borrow().siblings.prev;\n Some(n)\n })\n }\n\n fn iterate_roots(&self) -> impl Iterator> + use<'a> {\n Self::iterate_siblings(Some(self.root_first))\n }\n\n fn iterate_roots_rev(&self) -> impl Iterator> + use<'a> {\n Self::iterate_siblings_rev(Some(self.root_last))\n }\n\n /// Visits all nodes under and including `root` in depth order.\n /// Starts with node `start`.\n ///\n /// WARNING: Breaks in hilarious ways if `start` is not within `root`.\n fn visit_all) -> VisitControl>(\n root: &'a NodeCell<'a>,\n start: &'a NodeCell<'a>,\n forward: bool,\n mut cb: T,\n ) {\n let root_depth = root.borrow().depth;\n let mut node = start;\n let children_idx = if forward { NodeChildren::FIRST } else { NodeChildren::LAST };\n let siblings_idx = if forward { NodeSiblings::NEXT } else { NodeSiblings::PREV };\n\n while {\n 'traverse: {\n match cb(node) {\n VisitControl::Continue => {\n // Depth first search: It has a child? Go there.\n if let Some(child) = node.borrow().children.get(children_idx) {\n node = child;\n break 'traverse;\n }\n }\n VisitControl::SkipChildren => {}\n VisitControl::Stop => return,\n }\n\n loop {\n // If we hit the root while going up, we restart the traversal at\n // `root` going down again until we hit `start` again.\n let n = node.borrow();\n if n.depth <= root_depth {\n break 'traverse;\n }\n\n // Go to the parent's next sibling. --> Next subtree.\n if let Some(sibling) = n.siblings.get(siblings_idx) {\n node = sibling;\n break;\n }\n\n // Out of children? Go back to the parent.\n node = n.parent.unwrap();\n }\n }\n\n // We're done once we wrapped around to the `start`.\n !ptr::eq(node, start)\n } {}\n }\n}\n\n/// A hashmap of node IDs to nodes.\n///\n/// This map uses a simple open addressing scheme with linear probing.\n/// It's fast, simple, and sufficient for the small number of nodes we have.\nstruct NodeMap<'a> {\n slots: &'a [Option<&'a NodeCell<'a>>],\n shift: usize,\n mask: u64,\n}\n\nimpl Default for NodeMap<'static> {\n fn default() -> Self {\n Self { slots: &[None, None], shift: 63, mask: 0 }\n }\n}\n\nimpl<'a> NodeMap<'a> {\n /// Creates a new node map for the given tree.\n fn new(arena: &'a Arena, tree: &Tree<'a>) -> Self {\n // Since we aren't expected to have millions of nodes,\n // we allocate 4x the number of slots for a 25% fill factor.\n let width = (4 * tree.count + 1).ilog2().max(1) as usize;\n let slots = 1 << width;\n let shift = 64 - width;\n let mask = (slots - 1) as u64;\n\n let slots = arena.alloc_uninit_slice(slots).write_filled(None);\n let mut node = tree.root_first;\n\n loop {\n let n = node.borrow();\n let mut slot = n.id >> shift;\n\n loop {\n if slots[slot as usize].is_none() {\n slots[slot as usize] = Some(node);\n break;\n }\n slot = (slot + 1) & mask;\n }\n\n node = match n.next {\n Some(node) => node,\n None => break,\n };\n }\n\n Self { slots, shift, mask }\n }\n\n /// Gets a node by its ID.\n fn get(&mut self, id: u64) -> Option<&'a NodeCell<'a>> {\n let shift = self.shift;\n let mask = self.mask;\n let mut slot = id >> shift;\n\n loop {\n let node = self.slots[slot as usize]?;\n if node.borrow().id == id {\n return Some(node);\n }\n slot = (slot + 1) & mask;\n }\n }\n}\n\nstruct FloatAttributes {\n // Specifies the origin of the container relative to the container size. [0, 1]\n gravity_x: f32,\n gravity_y: f32,\n // Specifies an offset from the origin in cells.\n offset_x: f32,\n offset_y: f32,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeAttributes {\n float: Option,\n position: Position,\n padding: Rect,\n bg: u32,\n fg: u32,\n reverse: bool,\n bordered: bool,\n focusable: bool,\n focus_well: bool, // Prevents focus from leaving via Tab\n focus_void: bool, // Prevents focus from entering via Tab\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct ListContent<'a> {\n selected: u64,\n // Points to the Node that holds this ListContent instance, if any>.\n selected_node: Option<&'a NodeCell<'a>>,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct TableContent<'a> {\n columns: Vec,\n cell_gap: Size,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct StyledTextChunk {\n offset: usize,\n fg: u32,\n attr: Attributes,\n}\n\nconst INVALID_STYLED_TEXT_CHUNK: StyledTextChunk =\n StyledTextChunk { offset: usize::MAX, fg: 0, attr: Attributes::None };\n\n/// NOTE: Must not contain items that require drop().\nstruct TextContent<'a> {\n text: ArenaString<'a>,\n chunks: Vec,\n overflow: Overflow,\n}\n\n/// NOTE: Must not contain items that require drop().\nstruct TextareaContent<'a> {\n buffer: &'a TextBufferCell,\n\n // Carries over between frames.\n scroll_offset: Point,\n scroll_offset_y_drag_start: CoordType,\n scroll_offset_x_max: CoordType,\n thumb_height: CoordType,\n preferred_column: CoordType,\n\n single_line: bool,\n has_focus: bool,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Clone)]\nstruct ScrollareaContent {\n scroll_offset: Point,\n scroll_offset_y_drag_start: CoordType,\n thumb_height: CoordType,\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nenum NodeContent<'a> {\n #[default]\n None,\n List(ListContent<'a>),\n Modal(ArenaString<'a>), // title\n Table(TableContent<'a>),\n Text(TextContent<'a>),\n Textarea(TextareaContent<'a>),\n Scrollarea(ScrollareaContent),\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeSiblings<'a> {\n prev: Option<&'a NodeCell<'a>>,\n next: Option<&'a NodeCell<'a>>,\n}\n\nimpl<'a> NodeSiblings<'a> {\n const PREV: usize = 0;\n const NEXT: usize = 1;\n\n fn get(&self, off: usize) -> Option<&'a NodeCell<'a>> {\n match off & 1 {\n 0 => self.prev,\n 1 => self.next,\n _ => unreachable!(),\n }\n }\n}\n\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct NodeChildren<'a> {\n first: Option<&'a NodeCell<'a>>,\n last: Option<&'a NodeCell<'a>>,\n}\n\nimpl<'a> NodeChildren<'a> {\n const FIRST: usize = 0;\n const LAST: usize = 1;\n\n fn get(&self, off: usize) -> Option<&'a NodeCell<'a>> {\n match off & 1 {\n 0 => self.first,\n 1 => self.last,\n _ => unreachable!(),\n }\n }\n}\n\ntype NodeCell<'a> = SemiRefCell>;\n\n/// A node in the UI tree.\n///\n/// NOTE: Must not contain items that require drop().\n#[derive(Default)]\nstruct Node<'a> {\n prev: Option<&'a NodeCell<'a>>,\n next: Option<&'a NodeCell<'a>>,\n stack_parent: Option<&'a NodeCell<'a>>,\n\n id: u64,\n classname: &'static str,\n parent: Option<&'a NodeCell<'a>>,\n depth: usize,\n siblings: NodeSiblings<'a>,\n children: NodeChildren<'a>,\n child_count: usize,\n\n attributes: NodeAttributes,\n content: NodeContent<'a>,\n\n intrinsic_size: Size,\n intrinsic_size_set: bool,\n outer: Rect, // in screen-space, calculated during layout\n inner: Rect, // in screen-space, calculated during layout\n outer_clipped: Rect, // in screen-space, calculated during layout, restricted to the viewport\n inner_clipped: Rect, // in screen-space, calculated during layout, restricted to the viewport\n}\n\nimpl Node<'_> {\n /// Given an outer rectangle (including padding and borders) of this node,\n /// this returns the inner rectangle (excluding padding and borders).\n fn outer_to_inner(&self, mut outer: Rect) -> Rect {\n let l = self.attributes.bordered;\n let t = self.attributes.bordered;\n let r = self.attributes.bordered || matches!(self.content, NodeContent::Scrollarea(..));\n let b = self.attributes.bordered;\n\n outer.left += self.attributes.padding.left + l as CoordType;\n outer.top += self.attributes.padding.top + t as CoordType;\n outer.right -= self.attributes.padding.right + r as CoordType;\n outer.bottom -= self.attributes.padding.bottom + b as CoordType;\n outer\n }\n\n /// Given an intrinsic size (excluding padding and borders) of this node,\n /// this returns the outer size (including padding and borders).\n fn intrinsic_to_outer(&self) -> Size {\n let l = self.attributes.bordered;\n let t = self.attributes.bordered;\n let r = self.attributes.bordered || matches!(self.content, NodeContent::Scrollarea(..));\n let b = self.attributes.bordered;\n\n let mut size = self.intrinsic_size;\n size.width += self.attributes.padding.left\n + self.attributes.padding.right\n + l as CoordType\n + r as CoordType;\n size.height += self.attributes.padding.top\n + self.attributes.padding.bottom\n + t as CoordType\n + b as CoordType;\n size\n }\n\n /// Computes the intrinsic size of this node and its children.\n fn compute_intrinsic_size(&mut self) {\n match &mut self.content {\n NodeContent::Table(spec) => {\n // Calculate each row's height and the maximum width of each of its columns.\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n let mut row_height = 0;\n\n for (column, cell) in Tree::iterate_siblings(row.children.first).enumerate() {\n let mut cell = cell.borrow_mut();\n cell.compute_intrinsic_size();\n\n let size = cell.intrinsic_to_outer();\n\n // If the spec.columns[] value is positive, it's an absolute width.\n // Otherwise, it's a fraction of the remaining space.\n //\n // TODO: The latter is computed incorrectly.\n // Example: If the items are \"a\",\"b\",\"c\" then the intrinsic widths are [1,1,1].\n // If the column spec is [0,-3,-1], then this code assigns an intrinsic row\n // width of 3, but it should be 5 (1+1+3), because the spec says that the\n // last column (flexible 1/1) must be 3 times as wide as the 2nd one (1/3rd).\n // It's not a big deal yet, because such functionality isn't needed just yet.\n if column >= spec.columns.len() {\n spec.columns.push(0);\n }\n spec.columns[column] = spec.columns[column].max(size.width);\n\n row_height = row_height.max(size.height);\n }\n\n row.intrinsic_size.height = row_height;\n }\n\n // Assuming each column has the width of the widest cell in that column,\n // calculate the total width of the table.\n let total_gap_width =\n spec.cell_gap.width * spec.columns.len().saturating_sub(1) as CoordType;\n let total_inner_width = spec.columns.iter().sum::() + total_gap_width;\n let mut total_width = 0;\n let mut total_height = 0;\n\n // Assign the total width to each row.\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n row.intrinsic_size.width = total_inner_width;\n row.intrinsic_size_set = true;\n\n let size = row.intrinsic_to_outer();\n total_width = total_width.max(size.width);\n total_height += size.height;\n }\n\n let total_gap_height =\n spec.cell_gap.height * self.child_count.saturating_sub(1) as CoordType;\n total_height += total_gap_height;\n\n // Assign the total width/height to the table.\n if !self.intrinsic_size_set {\n self.intrinsic_size.width = total_width;\n self.intrinsic_size.height = total_height;\n self.intrinsic_size_set = true;\n }\n }\n _ => {\n let mut max_width = 0;\n let mut total_height = 0;\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n child.compute_intrinsic_size();\n\n let size = child.intrinsic_to_outer();\n max_width = max_width.max(size.width);\n total_height += size.height;\n }\n\n if !self.intrinsic_size_set {\n self.intrinsic_size.width = max_width;\n self.intrinsic_size.height = total_height;\n self.intrinsic_size_set = true;\n }\n }\n }\n }\n\n /// Lays out the children of this node.\n /// The clip rect restricts \"rendering\" to a certain area (the viewport).\n fn layout_children(&mut self, clip: Rect) {\n if self.children.first.is_none() || self.inner.is_empty() {\n return;\n }\n\n match &mut self.content {\n NodeContent::Table(spec) => {\n let width = self.inner.right - self.inner.left;\n let mut x = self.inner.left;\n let mut y = self.inner.top;\n\n for row in Tree::iterate_siblings(self.children.first) {\n let mut row = row.borrow_mut();\n let mut size = row.intrinsic_to_outer();\n size.width = width;\n row.outer.left = x;\n row.outer.top = y;\n row.outer.right = x + size.width;\n row.outer.bottom = y + size.height;\n row.outer = row.outer.intersect(self.inner);\n row.inner = row.outer_to_inner(row.outer);\n row.outer_clipped = row.outer.intersect(clip);\n row.inner_clipped = row.inner.intersect(clip);\n\n let mut row_height = 0;\n\n for (column, cell) in Tree::iterate_siblings(row.children.first).enumerate() {\n let mut cell = cell.borrow_mut();\n let mut size = cell.intrinsic_to_outer();\n size.width = spec.columns[column];\n cell.outer.left = x;\n cell.outer.top = y;\n cell.outer.right = x + size.width;\n cell.outer.bottom = y + size.height;\n cell.outer = cell.outer.intersect(self.inner);\n cell.inner = cell.outer_to_inner(cell.outer);\n cell.outer_clipped = cell.outer.intersect(clip);\n cell.inner_clipped = cell.inner.intersect(clip);\n\n x += size.width + spec.cell_gap.width;\n row_height = row_height.max(size.height);\n\n cell.layout_children(clip);\n }\n\n x = self.inner.left;\n y += row_height + spec.cell_gap.height;\n }\n }\n NodeContent::Scrollarea(sc) => {\n let mut content = self.children.first.unwrap().borrow_mut();\n\n // content available viewport size (-1 for the track)\n let sx = self.inner.right - self.inner.left;\n let sy = self.inner.bottom - self.inner.top;\n // actual content size\n let cx = sx;\n let cy = content.intrinsic_size.height.max(sy);\n // scroll offset\n let ox = 0;\n let oy = sc.scroll_offset.y.clamp(0, cy - sy);\n\n sc.scroll_offset.x = ox;\n sc.scroll_offset.y = oy;\n\n content.outer.left = self.inner.left - ox;\n content.outer.top = self.inner.top - oy;\n content.outer.right = content.outer.left + cx;\n content.outer.bottom = content.outer.top + cy;\n content.inner = content.outer_to_inner(content.outer);\n content.outer_clipped = content.outer.intersect(self.inner_clipped);\n content.inner_clipped = content.inner.intersect(self.inner_clipped);\n\n let clip = content.inner_clipped;\n content.layout_children(clip);\n }\n _ => {\n let width = self.inner.right - self.inner.left;\n let x = self.inner.left;\n let mut y = self.inner.top;\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n let size = child.intrinsic_to_outer();\n let remaining = (width - size.width).max(0);\n\n child.outer.left = x + match child.attributes.position {\n Position::Stretch | Position::Left => 0,\n Position::Center => remaining / 2,\n Position::Right => remaining,\n };\n child.outer.right = child.outer.left\n + match child.attributes.position {\n Position::Stretch => width,\n _ => size.width,\n };\n child.outer.top = y;\n child.outer.bottom = y + size.height;\n\n child.outer = child.outer.intersect(self.inner);\n child.inner = child.outer_to_inner(child.outer);\n child.outer_clipped = child.outer.intersect(clip);\n child.inner_clipped = child.inner.intersect(clip);\n\n y += size.height;\n }\n\n for child in Tree::iterate_siblings(self.children.first) {\n let mut child = child.borrow_mut();\n child.layout_children(clip);\n }\n }\n }\n }\n}\n"], ["/edit/src/framebuffer.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! A shoddy framebuffer for terminal applications.\n\nuse std::cell::Cell;\nuse std::fmt::Write;\nuse std::ops::{BitOr, BitXor};\nuse std::ptr;\nuse std::slice::ChunksExact;\n\nuse crate::arena::{Arena, ArenaString};\nuse crate::helpers::{CoordType, Point, Rect, Size};\nuse crate::oklab::{oklab_blend, srgb_to_oklab};\nuse crate::simd::{MemsetSafe, memset};\nuse crate::unicode::MeasurementConfig;\n\n// Same constants as used in the PCG family of RNGs.\n#[cfg(target_pointer_width = \"32\")]\nconst HASH_MULTIPLIER: usize = 747796405; // https://doi.org/10.1090/S0025-5718-99-00996-5, Table 5\n#[cfg(target_pointer_width = \"64\")]\nconst HASH_MULTIPLIER: usize = 6364136223846793005; // Knuth's MMIX multiplier\n\n/// The size of our cache table. 1<<8 = 256.\nconst CACHE_TABLE_LOG2_SIZE: usize = 8;\nconst CACHE_TABLE_SIZE: usize = 1 << CACHE_TABLE_LOG2_SIZE;\n/// To index into the cache table, we use `color * HASH_MULTIPLIER` as the hash.\n/// Since the multiplication \"shifts\" the bits up, we don't just mask the lowest\n/// 8 bits out, but rather shift 56 bits down to get the best bits from the top.\nconst CACHE_TABLE_SHIFT: usize = usize::BITS as usize - CACHE_TABLE_LOG2_SIZE;\n\n/// Standard 16 VT & default foreground/background colors.\n#[derive(Clone, Copy)]\npub enum IndexedColor {\n Black,\n Red,\n Green,\n Yellow,\n Blue,\n Magenta,\n Cyan,\n White,\n BrightBlack,\n BrightRed,\n BrightGreen,\n BrightYellow,\n BrightBlue,\n BrightMagenta,\n BrightCyan,\n BrightWhite,\n\n Background,\n Foreground,\n}\n\n/// Number of indices used by [`IndexedColor`].\npub const INDEXED_COLORS_COUNT: usize = 18;\n\n/// Fallback theme. Matches Windows Terminal's Ottosson theme.\npub const DEFAULT_THEME: [u32; INDEXED_COLORS_COUNT] = [\n 0xff000000, // Black\n 0xff212cbe, // Red\n 0xff3aae3f, // Green\n 0xff4a9abe, // Yellow\n 0xffbe4d20, // Blue\n 0xffbe54bb, // Magenta\n 0xffb2a700, // Cyan\n 0xffbebebe, // White\n 0xff808080, // BrightBlack\n 0xff303eff, // BrightRed\n 0xff51ea58, // BrightGreen\n 0xff44c9ff, // BrightYellow\n 0xffff6a2f, // BrightBlue\n 0xffff74fc, // BrightMagenta\n 0xfff0e100, // BrightCyan\n 0xffffffff, // BrightWhite\n // --------\n 0xff000000, // Background\n 0xffbebebe, // Foreground\n];\n\n/// A shoddy framebuffer for terminal applications.\n///\n/// The idea is that you create a [`Framebuffer`], draw a bunch of text and\n/// colors into it, and it takes care of figuring out what changed since the\n/// last rendering and sending the differences as VT to the terminal.\n///\n/// This is an improvement over how many other terminal applications work,\n/// as they fail to accurately track what changed. If you watch the output\n/// of `vim` for instance, you'll notice that it redraws unrelated parts of\n/// the screen all the time.\npub struct Framebuffer {\n /// Store the color palette.\n indexed_colors: [u32; INDEXED_COLORS_COUNT],\n /// Front and back buffers. Indexed by `frame_counter & 1`.\n buffers: [Buffer; 2],\n /// The current frame counter. Increments on every `flip` call.\n frame_counter: usize,\n /// The colors used for `contrast()`. It stores the default colors\n /// of the palette as [dark, light], unless the palette is recognized\n /// as a light them, in which case it swaps them.\n auto_colors: [u32; 2],\n /// A cache table for previously contrasted colors.\n /// See: \n contrast_colors: [Cell<(u32, u32)>; CACHE_TABLE_SIZE],\n background_fill: u32,\n foreground_fill: u32,\n}\n\nimpl Framebuffer {\n /// Creates a new framebuffer.\n pub fn new() -> Self {\n Self {\n indexed_colors: DEFAULT_THEME,\n buffers: Default::default(),\n frame_counter: 0,\n auto_colors: [\n DEFAULT_THEME[IndexedColor::Black as usize],\n DEFAULT_THEME[IndexedColor::BrightWhite as usize],\n ],\n contrast_colors: [const { Cell::new((0, 0)) }; CACHE_TABLE_SIZE],\n background_fill: DEFAULT_THEME[IndexedColor::Background as usize],\n foreground_fill: DEFAULT_THEME[IndexedColor::Foreground as usize],\n }\n }\n\n /// Sets the base color palette.\n ///\n /// If you call this method, [`Framebuffer`] expects that you\n /// successfully detect the light/dark mode of the terminal.\n pub fn set_indexed_colors(&mut self, colors: [u32; INDEXED_COLORS_COUNT]) {\n self.indexed_colors = colors;\n self.background_fill = 0;\n self.foreground_fill = 0;\n\n self.auto_colors = [\n self.indexed_colors[IndexedColor::Black as usize],\n self.indexed_colors[IndexedColor::BrightWhite as usize],\n ];\n if !Self::is_dark(self.auto_colors[0]) {\n self.auto_colors.swap(0, 1);\n }\n }\n\n /// Begins a new frame with the given `size`.\n pub fn flip(&mut self, size: Size) {\n if size != self.buffers[0].bg_bitmap.size {\n for buffer in &mut self.buffers {\n buffer.text = LineBuffer::new(size);\n buffer.bg_bitmap = Bitmap::new(size);\n buffer.fg_bitmap = Bitmap::new(size);\n buffer.attributes = AttributeBuffer::new(size);\n }\n\n let front = &mut self.buffers[self.frame_counter & 1];\n // Trigger a full redraw. (Yes, it's a hack.)\n front.fg_bitmap.fill(1);\n // Trigger a cursor update as well, just to be sure.\n front.cursor = Cursor::new_invalid();\n }\n\n self.frame_counter = self.frame_counter.wrapping_add(1);\n\n let back = &mut self.buffers[self.frame_counter & 1];\n\n back.text.fill_whitespace();\n back.bg_bitmap.fill(self.background_fill);\n back.fg_bitmap.fill(self.foreground_fill);\n back.attributes.reset();\n back.cursor = Cursor::new_disabled();\n }\n\n /// Replaces text contents in a single line of the framebuffer.\n /// All coordinates are in viewport coordinates.\n /// Assumes that control characters have been replaced or escaped.\n pub fn replace_text(\n &mut self,\n y: CoordType,\n origin_x: CoordType,\n clip_right: CoordType,\n text: &str,\n ) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.text.replace_text(y, origin_x, clip_right, text)\n }\n\n /// Draws a scrollbar in the given `track` rectangle.\n ///\n /// Not entirely sure why I put it here instead of elsewhere.\n ///\n /// # Parameters\n ///\n /// * `clip_rect`: Clips the rendering to this rectangle.\n /// This is relevant when you have scrollareas inside scrollareas.\n /// * `track`: The rectangle in which to draw the scrollbar.\n /// In absolute viewport coordinates.\n /// * `content_offset`: The current offset of the scrollarea.\n /// * `content_height`: The height of the scrollarea content.\n pub fn draw_scrollbar(\n &mut self,\n clip_rect: Rect,\n track: Rect,\n content_offset: CoordType,\n content_height: CoordType,\n ) -> CoordType {\n let track_clipped = track.intersect(clip_rect);\n if track_clipped.is_empty() {\n return 0;\n }\n\n let viewport_height = track.height();\n // The content height is at least the viewport height.\n let content_height = content_height.max(viewport_height);\n\n // No need to draw a scrollbar if the content fits in the viewport.\n let content_offset_max = content_height - viewport_height;\n if content_offset_max == 0 {\n return 0;\n }\n\n // The content offset must be at least one viewport height from the bottom.\n // You don't want to scroll past the end after all...\n let content_offset = content_offset.clamp(0, content_offset_max);\n\n // In order to increase the visual resolution of the scrollbar,\n // we'll use 1/8th blocks to represent the thumb.\n // First, scale the offsets to get that 1/8th resolution.\n let viewport_height = viewport_height as i64 * 8;\n let content_offset_max = content_offset_max as i64 * 8;\n let content_offset = content_offset as i64 * 8;\n let content_height = content_height as i64 * 8;\n\n // The proportional thumb height (0-1) is the fraction of viewport and\n // content height. The taller the content, the smaller the thumb:\n // = viewport_height / content_height\n // We then scale that to the viewport height to get the height in 1/8th units.\n // = viewport_height * viewport_height / content_height\n // We add content_height/2 to round the integer division, which results in a numerator of:\n // = viewport_height * viewport_height + content_height / 2\n let numerator = viewport_height * viewport_height + content_height / 2;\n let thumb_height = numerator / content_height;\n // Ensure the thumb has a minimum size of 1 row.\n let thumb_height = thumb_height.max(8);\n\n // The proportional thumb top position (0-1) is:\n // = content_offset / content_offset_max\n // The maximum thumb top position is the viewport height minus the thumb height:\n // = viewport_height - thumb_height\n // To get the thumb top position in 1/8th units, we multiply both:\n // = (viewport_height - thumb_height) * content_offset / content_offset_max\n // We add content_offset_max/2 to round the integer division, which results in a numerator of:\n // = (viewport_height - thumb_height) * content_offset + content_offset_max / 2\n let numerator = (viewport_height - thumb_height) * content_offset + content_offset_max / 2;\n let thumb_top = numerator / content_offset_max;\n // The thumb bottom position is the thumb top position plus the thumb height.\n let thumb_bottom = thumb_top + thumb_height;\n\n // Shift to absolute coordinates.\n let thumb_top = thumb_top + track.top as i64 * 8;\n let thumb_bottom = thumb_bottom + track.top as i64 * 8;\n\n // Clamp to the visible area.\n let thumb_top = thumb_top.max(track_clipped.top as i64 * 8);\n let thumb_bottom = thumb_bottom.min(track_clipped.bottom as i64 * 8);\n\n // Calculate the height of the top/bottom cell of the thumb.\n let top_fract = (thumb_top % 8) as CoordType;\n let bottom_fract = (thumb_bottom % 8) as CoordType;\n\n // Shift to absolute coordinates.\n let thumb_top = ((thumb_top + 7) / 8) as CoordType;\n let thumb_bottom = (thumb_bottom / 8) as CoordType;\n\n self.blend_bg(track_clipped, self.indexed(IndexedColor::BrightBlack));\n self.blend_fg(track_clipped, self.indexed(IndexedColor::BrightWhite));\n\n // Draw the full blocks.\n for y in thumb_top..thumb_bottom {\n self.replace_text(y, track_clipped.left, track_clipped.right, \"█\");\n }\n\n // Draw the top/bottom cell of the thumb.\n // U+2581 to U+2588, 1/8th block to 8/8th block elements glyphs: ▁▂▃▄▅▆▇█\n // In UTF8: E2 96 81 to E2 96 88\n let mut fract_buf = [0xE2, 0x96, 0x88];\n if top_fract != 0 {\n fract_buf[2] = (0x88 - top_fract) as u8;\n self.replace_text(thumb_top - 1, track_clipped.left, track_clipped.right, unsafe {\n std::str::from_utf8_unchecked(&fract_buf)\n });\n }\n if bottom_fract != 0 {\n fract_buf[2] = (0x88 - bottom_fract) as u8;\n self.replace_text(thumb_bottom, track_clipped.left, track_clipped.right, unsafe {\n std::str::from_utf8_unchecked(&fract_buf)\n });\n let rect = Rect {\n left: track_clipped.left,\n top: thumb_bottom,\n right: track_clipped.right,\n bottom: thumb_bottom + 1,\n };\n self.blend_bg(rect, self.indexed(IndexedColor::BrightWhite));\n self.blend_fg(rect, self.indexed(IndexedColor::BrightBlack));\n }\n\n ((thumb_height + 4) / 8) as CoordType\n }\n\n #[inline]\n pub fn indexed(&self, index: IndexedColor) -> u32 {\n self.indexed_colors[index as usize]\n }\n\n /// Returns a color from the palette.\n ///\n /// To facilitate constant folding by the compiler,\n /// alpha is given as a fraction (`numerator` / `denominator`).\n #[inline]\n pub fn indexed_alpha(&self, index: IndexedColor, numerator: u32, denominator: u32) -> u32 {\n let c = self.indexed_colors[index as usize];\n let a = 255 * numerator / denominator;\n let r = (((c >> 16) & 0xFF) * numerator) / denominator;\n let g = (((c >> 8) & 0xFF) * numerator) / denominator;\n let b = ((c & 0xFF) * numerator) / denominator;\n a << 24 | r << 16 | g << 8 | b\n }\n\n /// Returns a color opposite to the brightness of the given `color`.\n pub fn contrasted(&self, color: u32) -> u32 {\n let idx = (color as usize).wrapping_mul(HASH_MULTIPLIER) >> CACHE_TABLE_SHIFT;\n let slot = self.contrast_colors[idx].get();\n if slot.0 == color { slot.1 } else { self.contrasted_slow(color) }\n }\n\n #[cold]\n fn contrasted_slow(&self, color: u32) -> u32 {\n let idx = (color as usize).wrapping_mul(HASH_MULTIPLIER) >> CACHE_TABLE_SHIFT;\n let contrast = self.auto_colors[Self::is_dark(color) as usize];\n self.contrast_colors[idx].set((color, contrast));\n contrast\n }\n\n fn is_dark(color: u32) -> bool {\n srgb_to_oklab(color).l < 0.5\n }\n\n /// Blends the given sRGB color onto the background bitmap.\n ///\n /// TODO: The current approach blends foreground/background independently,\n /// but ideally `blend_bg` with semi-transparent dark should also darken text below it.\n pub fn blend_bg(&mut self, target: Rect, bg: u32) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.bg_bitmap.blend(target, bg);\n }\n\n /// Blends the given sRGB color onto the foreground bitmap.\n ///\n /// TODO: The current approach blends foreground/background independently,\n /// but ideally `blend_fg` should blend with the background color below it.\n pub fn blend_fg(&mut self, target: Rect, fg: u32) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.fg_bitmap.blend(target, fg);\n }\n\n /// Reverses the foreground and background colors in the given rectangle.\n pub fn reverse(&mut self, target: Rect) {\n let back = &mut self.buffers[self.frame_counter & 1];\n\n let target = target.intersect(back.bg_bitmap.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = back.bg_bitmap.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let bg = &mut back.bg_bitmap.data[beg..end];\n let fg = &mut back.fg_bitmap.data[beg..end];\n bg.swap_with_slice(fg);\n }\n }\n\n /// Replaces VT attributes in the given rectangle.\n pub fn replace_attr(&mut self, target: Rect, mask: Attributes, attr: Attributes) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.attributes.replace(target, mask, attr);\n }\n\n /// Sets the current visible cursor position and type.\n ///\n /// Call this when focus is inside an editable area and you want to show the cursor.\n pub fn set_cursor(&mut self, pos: Point, overtype: bool) {\n let back = &mut self.buffers[self.frame_counter & 1];\n back.cursor.pos = pos;\n back.cursor.overtype = overtype;\n }\n\n /// Renders the framebuffer contents accumulated since the\n /// last call to `flip()` and returns them serialized as VT.\n pub fn render<'a>(&mut self, arena: &'a Arena) -> ArenaString<'a> {\n let idx = self.frame_counter & 1;\n // Borrows the front/back buffers without letting Rust know that we have a reference to self.\n // SAFETY: Well this is certainly correct, but whether Rust and its strict rules likes it is another question.\n let (back, front) = unsafe {\n let ptr = self.buffers.as_mut_ptr();\n let back = &mut *ptr.add(idx);\n let front = &*ptr.add(1 - idx);\n (back, front)\n };\n\n let mut front_lines = front.text.lines.iter(); // hahaha\n let mut front_bgs = front.bg_bitmap.iter();\n let mut front_fgs = front.fg_bitmap.iter();\n let mut front_attrs = front.attributes.iter();\n\n let mut back_lines = back.text.lines.iter();\n let mut back_bgs = back.bg_bitmap.iter();\n let mut back_fgs = back.fg_bitmap.iter();\n let mut back_attrs = back.attributes.iter();\n\n let mut result = ArenaString::new_in(arena);\n let mut last_bg = u64::MAX;\n let mut last_fg = u64::MAX;\n let mut last_attr = Attributes::None;\n\n for y in 0..front.text.size.height {\n // SAFETY: The only thing that changes the size of these containers,\n // is the reset() method and it always resets front/back to the same size.\n let front_line = unsafe { front_lines.next().unwrap_unchecked() };\n let front_bg = unsafe { front_bgs.next().unwrap_unchecked() };\n let front_fg = unsafe { front_fgs.next().unwrap_unchecked() };\n let front_attr = unsafe { front_attrs.next().unwrap_unchecked() };\n\n let back_line = unsafe { back_lines.next().unwrap_unchecked() };\n let back_bg = unsafe { back_bgs.next().unwrap_unchecked() };\n let back_fg = unsafe { back_fgs.next().unwrap_unchecked() };\n let back_attr = unsafe { back_attrs.next().unwrap_unchecked() };\n\n // TODO: Ideally, we should properly diff the contents and so if\n // only parts of a line change, we should only update those parts.\n if front_line == back_line\n && front_bg == back_bg\n && front_fg == back_fg\n && front_attr == back_attr\n {\n continue;\n }\n\n let line_bytes = back_line.as_bytes();\n let mut cfg = MeasurementConfig::new(&line_bytes);\n let mut chunk_end = 0;\n\n if result.is_empty() {\n result.push_str(\"\\x1b[m\");\n }\n _ = write!(result, \"\\x1b[{};1H\", y + 1);\n\n while {\n let bg = back_bg[chunk_end];\n let fg = back_fg[chunk_end];\n let attr = back_attr[chunk_end];\n\n // Chunk into runs of the same color.\n while {\n chunk_end += 1;\n chunk_end < back_bg.len()\n && back_bg[chunk_end] == bg\n && back_fg[chunk_end] == fg\n && back_attr[chunk_end] == attr\n } {}\n\n if last_bg != bg as u64 {\n last_bg = bg as u64;\n self.format_color(&mut result, false, bg);\n }\n\n if last_fg != fg as u64 {\n last_fg = fg as u64;\n self.format_color(&mut result, true, fg);\n }\n\n if last_attr != attr {\n let diff = last_attr ^ attr;\n if diff.is(Attributes::Italic) {\n if attr.is(Attributes::Italic) {\n result.push_str(\"\\x1b[3m\");\n } else {\n result.push_str(\"\\x1b[23m\");\n }\n }\n if diff.is(Attributes::Underlined) {\n if attr.is(Attributes::Underlined) {\n result.push_str(\"\\x1b[4m\");\n } else {\n result.push_str(\"\\x1b[24m\");\n }\n }\n last_attr = attr;\n }\n\n let beg = cfg.cursor().offset;\n let end = cfg.goto_visual(Point { x: chunk_end as CoordType, y: 0 }).offset;\n result.push_str(&back_line[beg..end]);\n\n chunk_end < back_bg.len()\n } {}\n }\n\n // If the cursor has changed since the last frame we naturally need to update it,\n // but this also applies if the code above wrote to the screen,\n // as it uses CUP sequences to reposition the cursor for writing.\n if !result.is_empty() || back.cursor != front.cursor {\n if back.cursor.pos.x >= 0 && back.cursor.pos.y >= 0 {\n // CUP to the cursor position.\n // DECSCUSR to set the cursor style.\n // DECTCEM to show the cursor.\n _ = write!(\n result,\n \"\\x1b[{};{}H\\x1b[{} q\\x1b[?25h\",\n back.cursor.pos.y + 1,\n back.cursor.pos.x + 1,\n if back.cursor.overtype { 1 } else { 5 }\n );\n } else {\n // DECTCEM to hide the cursor.\n result.push_str(\"\\x1b[?25l\");\n }\n }\n\n result\n }\n\n fn format_color(&self, dst: &mut ArenaString, fg: bool, mut color: u32) {\n let typ = if fg { '3' } else { '4' };\n\n // Some terminals support transparent backgrounds which are used\n // if the default background color is active (CSI 49 m).\n //\n // If [`Framebuffer::set_indexed_colors`] was never called, we assume\n // that the terminal doesn't support transparency and initialize the\n // background bitmap with the `DEFAULT_THEME` default background color.\n // Otherwise, we assume that the terminal supports transparency\n // and initialize it with 0x00000000 (transparent).\n //\n // We also apply this to the foreground color, because it compresses\n // the output slightly and ensures that we keep \"default foreground\"\n // and \"color that happens to be default foreground\" separate.\n // (This also applies to the background color by the way.)\n if color == 0 {\n _ = write!(dst, \"\\x1b[{typ}9m\");\n return;\n }\n\n if (color & 0xff000000) != 0xff000000 {\n let idx = if fg { IndexedColor::Foreground } else { IndexedColor::Background };\n let dst = self.indexed(idx);\n color = oklab_blend(dst, color);\n }\n\n let r = color & 0xff;\n let g = (color >> 8) & 0xff;\n let b = (color >> 16) & 0xff;\n _ = write!(dst, \"\\x1b[{typ}8;2;{r};{g};{b}m\");\n }\n}\n\n#[derive(Default)]\nstruct Buffer {\n text: LineBuffer,\n bg_bitmap: Bitmap,\n fg_bitmap: Bitmap,\n attributes: AttributeBuffer,\n cursor: Cursor,\n}\n\n/// A buffer for the text contents of the framebuffer.\n#[derive(Default)]\nstruct LineBuffer {\n lines: Vec,\n size: Size,\n}\n\nimpl LineBuffer {\n fn new(size: Size) -> Self {\n Self { lines: vec![String::new(); size.height as usize], size }\n }\n\n fn fill_whitespace(&mut self) {\n let width = self.size.width as usize;\n for l in &mut self.lines {\n l.clear();\n l.reserve(width + width / 2);\n\n let buf = unsafe { l.as_mut_vec() };\n // Compiles down to `memset()`.\n buf.extend(std::iter::repeat_n(b' ', width));\n }\n }\n\n /// Replaces text contents in a single line of the framebuffer.\n /// All coordinates are in viewport coordinates.\n /// Assumes that control characters have been replaced or escaped.\n fn replace_text(\n &mut self,\n y: CoordType,\n origin_x: CoordType,\n clip_right: CoordType,\n text: &str,\n ) {\n let Some(line) = self.lines.get_mut(y as usize) else {\n return;\n };\n\n let bytes = text.as_bytes();\n let clip_right = clip_right.clamp(0, self.size.width);\n let layout_width = clip_right - origin_x;\n\n // Can't insert text that can't fit or is empty.\n if layout_width <= 0 || bytes.is_empty() {\n return;\n }\n\n let mut cfg = MeasurementConfig::new(&bytes);\n\n // Check if the text intersects with the left edge of the framebuffer\n // and figure out the parts that are inside.\n let mut left = origin_x;\n if left < 0 {\n let mut cursor = cfg.goto_visual(Point { x: -left, y: 0 });\n\n if left + cursor.visual_pos.x < 0 && cursor.offset < text.len() {\n // `-left` must've intersected a wide glyph and since goto_visual stops _before_ reaching the target,\n // we stopped before the wide glyph and thus must step forward to the next glyph.\n cursor = cfg.goto_logical(Point { x: cursor.logical_pos.x + 1, y: 0 });\n }\n\n left += cursor.visual_pos.x;\n }\n\n // If the text still starts outside the framebuffer, we must've ran out of text above.\n // Otherwise, if it starts outside the right edge to begin with, we can't insert it anyway.\n if left < 0 || left >= clip_right {\n return;\n }\n\n // Measure the width of the new text (= `res_new.visual_target.x`).\n let beg_off = cfg.cursor().offset;\n let end = cfg.goto_visual(Point { x: layout_width, y: 0 });\n\n // Figure out at which byte offset the new text gets inserted.\n let right = left + end.visual_pos.x;\n let line_bytes = line.as_bytes();\n let mut cfg_old = MeasurementConfig::new(&line_bytes);\n let res_old_beg = cfg_old.goto_visual(Point { x: left, y: 0 });\n let mut res_old_end = cfg_old.goto_visual(Point { x: right, y: 0 });\n\n // Since the goto functions will always stop short of the target position,\n // we need to manually step beyond it if we intersect with a wide glyph.\n if res_old_end.visual_pos.x < right {\n res_old_end = cfg_old.goto_logical(Point { x: res_old_end.logical_pos.x + 1, y: 0 });\n }\n\n // If we intersect a wide glyph, we need to pad the new text with spaces.\n let src = &text[beg_off..end.offset];\n let overlap_beg = (left - res_old_beg.visual_pos.x).max(0) as usize;\n let overlap_end = (res_old_end.visual_pos.x - right).max(0) as usize;\n let total_add = src.len() + overlap_beg + overlap_end;\n let total_del = res_old_end.offset - res_old_beg.offset;\n\n // This is basically a hand-written version of `Vec::splice()`,\n // but for strings under the assumption that all inputs are valid.\n // It also takes care of `overlap_beg` and `overlap_end` by inserting spaces.\n unsafe {\n // SAFETY: Our ucd code only returns valid UTF-8 offsets.\n // If it didn't that'd be a priority -9000 bug for any text editor.\n // And apart from that, all inputs are &str (= UTF8).\n let dst = line.as_mut_vec();\n\n let dst_len = dst.len();\n let src_len = src.len();\n\n // Make room for the new elements. NOTE that this must be done before\n // we call as_mut_ptr, or else we risk accessing a stale pointer.\n // We only need to reserve as much as the string actually grows by.\n dst.reserve(total_add.saturating_sub(total_del));\n\n // Move the pointer to the start of the insert.\n let mut ptr = dst.as_mut_ptr().add(res_old_beg.offset);\n\n // Move the tail end of the string by `total_add - total_del`-many bytes.\n // This both effectively deletes the old text and makes room for the new text.\n if total_add != total_del {\n // Move the tail of the vector to make room for the new elements.\n ptr::copy(\n ptr.add(total_del),\n ptr.add(total_add),\n dst_len - total_del - res_old_beg.offset,\n );\n }\n\n // Pad left.\n for _ in 0..overlap_beg {\n ptr.write(b' ');\n ptr = ptr.add(1);\n }\n\n // Copy the new elements into the vector.\n ptr::copy_nonoverlapping(src.as_ptr(), ptr, src_len);\n ptr = ptr.add(src_len);\n\n // Pad right.\n for _ in 0..overlap_end {\n ptr.write(b' ');\n ptr = ptr.add(1);\n }\n\n // Update the length of the vector.\n dst.set_len(dst_len - total_del + total_add);\n }\n }\n}\n\n/// An sRGB bitmap.\n#[derive(Default)]\nstruct Bitmap {\n data: Vec,\n size: Size,\n}\n\nimpl Bitmap {\n fn new(size: Size) -> Self {\n Self { data: vec![0; (size.width * size.height) as usize], size }\n }\n\n fn fill(&mut self, color: u32) {\n memset(&mut self.data, color);\n }\n\n /// Blends the given sRGB color onto the bitmap.\n ///\n /// This uses the `oklab` color space for blending so the\n /// resulting colors may look different from what you'd expect.\n fn blend(&mut self, target: Rect, color: u32) {\n if (color & 0xff000000) == 0x00000000 {\n return;\n }\n\n let target = target.intersect(self.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = self.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let data = &mut self.data[beg..end];\n\n if (color & 0xff000000) == 0xff000000 {\n memset(data, color);\n } else {\n let end = data.len();\n let mut off = 0;\n\n while {\n let c = data[off];\n\n // Chunk into runs of the same color, so that we only call alpha_blend once per run.\n let chunk_beg = off;\n while {\n off += 1;\n off < end && data[off] == c\n } {}\n let chunk_end = off;\n\n let c = oklab_blend(c, color);\n memset(&mut data[chunk_beg..chunk_end], c);\n\n off < end\n } {}\n }\n }\n }\n\n /// Iterates over each row in the bitmap.\n fn iter(&self) -> ChunksExact<'_, u32> {\n self.data.chunks_exact(self.size.width as usize)\n }\n}\n\n/// A bitfield for VT text attributes.\n///\n/// It being a bitfield allows for simple diffing.\n#[repr(transparent)]\n#[derive(Default, Clone, Copy, PartialEq, Eq)]\npub struct Attributes(u8);\n\n#[allow(non_upper_case_globals)]\nimpl Attributes {\n pub const None: Self = Self(0);\n pub const Italic: Self = Self(0b1);\n pub const Underlined: Self = Self(0b10);\n pub const All: Self = Self(0b11);\n\n pub const fn is(self, attr: Self) -> bool {\n (self.0 & attr.0) == attr.0\n }\n}\n\nunsafe impl MemsetSafe for Attributes {}\n\nimpl BitOr for Attributes {\n type Output = Self;\n\n fn bitor(self, rhs: Self) -> Self::Output {\n Self(self.0 | rhs.0)\n }\n}\n\nimpl BitXor for Attributes {\n type Output = Self;\n\n fn bitxor(self, rhs: Self) -> Self::Output {\n Self(self.0 ^ rhs.0)\n }\n}\n\n/// Stores VT attributes for the framebuffer.\n#[derive(Default)]\nstruct AttributeBuffer {\n data: Vec,\n size: Size,\n}\n\nimpl AttributeBuffer {\n fn new(size: Size) -> Self {\n Self { data: vec![Default::default(); (size.width * size.height) as usize], size }\n }\n\n fn reset(&mut self) {\n memset(&mut self.data, Default::default());\n }\n\n fn replace(&mut self, target: Rect, mask: Attributes, attr: Attributes) {\n let target = target.intersect(self.size.as_rect());\n if target.is_empty() {\n return;\n }\n\n let top = target.top as usize;\n let bottom = target.bottom as usize;\n let left = target.left as usize;\n let right = target.right as usize;\n let stride = self.size.width as usize;\n\n for y in top..bottom {\n let beg = y * stride + left;\n let end = y * stride + right;\n let dst = &mut self.data[beg..end];\n\n if mask == Attributes::All {\n memset(dst, attr);\n } else {\n for a in dst {\n *a = Attributes(a.0 & !mask.0 | attr.0);\n }\n }\n }\n }\n\n /// Iterates over each row in the bitmap.\n fn iter(&self) -> ChunksExact<'_, Attributes> {\n self.data.chunks_exact(self.size.width as usize)\n }\n}\n\n/// Stores cursor position and type for the framebuffer.\n#[derive(Default, PartialEq, Eq)]\nstruct Cursor {\n pos: Point,\n overtype: bool,\n}\n\nimpl Cursor {\n const fn new_invalid() -> Self {\n Self { pos: Point::MIN, overtype: false }\n }\n\n const fn new_disabled() -> Self {\n Self { pos: Point { x: -1, y: -1 }, overtype: false }\n }\n}\n"], ["/edit/src/bin/edit/main.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![feature(allocator_api, linked_list_cursors, string_from_utf8_lossy_owned)]\n\nmod documents;\nmod draw_editor;\nmod draw_filepicker;\nmod draw_menubar;\nmod draw_statusbar;\nmod localization;\nmod state;\n\nuse std::borrow::Cow;\n#[cfg(feature = \"debug-latency\")]\nuse std::fmt::Write;\nuse std::path::{Path, PathBuf};\nuse std::time::Duration;\nuse std::{env, process};\n\nuse draw_editor::*;\nuse draw_filepicker::*;\nuse draw_menubar::*;\nuse draw_statusbar::*;\nuse edit::arena::{self, Arena, ArenaString, scratch_arena};\nuse edit::framebuffer::{self, IndexedColor};\nuse edit::helpers::{CoordType, KIBI, MEBI, MetricFormatter, Rect, Size};\nuse edit::input::{self, kbmod, vk};\nuse edit::oklab::oklab_blend;\nuse edit::tui::*;\nuse edit::vt::{self, Token};\nuse edit::{apperr, arena_format, base64, path, sys, unicode};\nuse localization::*;\nuse state::*;\n\n#[cfg(target_pointer_width = \"32\")]\nconst SCRATCH_ARENA_CAPACITY: usize = 128 * MEBI;\n#[cfg(target_pointer_width = \"64\")]\nconst SCRATCH_ARENA_CAPACITY: usize = 512 * MEBI;\n\nfn main() -> process::ExitCode {\n if cfg!(debug_assertions) {\n let hook = std::panic::take_hook();\n std::panic::set_hook(Box::new(move |info| {\n drop(RestoreModes);\n drop(sys::Deinit);\n hook(info);\n }));\n }\n\n match run() {\n Ok(()) => process::ExitCode::SUCCESS,\n Err(err) => {\n sys::write_stdout(&format!(\"{}\\n\", FormatApperr::from(err)));\n process::ExitCode::FAILURE\n }\n }\n}\n\nfn run() -> apperr::Result<()> {\n // Init `sys` first, as everything else may depend on its functionality (IO, function pointers, etc.).\n let _sys_deinit = sys::init();\n // Next init `arena`, so that `scratch_arena` works. `loc` depends on it.\n arena::init(SCRATCH_ARENA_CAPACITY)?;\n // Init the `loc` module, so that error messages are localized.\n localization::init();\n\n let mut state = State::new()?;\n if handle_args(&mut state)? {\n return Ok(());\n }\n\n // This will reopen stdin if it's redirected (which may fail) and switch\n // the terminal to raw mode which prevents the user from pressing Ctrl+C.\n // `handle_args` may want to print a help message (must not fail),\n // and reads files (may hang; should be cancelable with Ctrl+C).\n // As such, we call this after `handle_args`.\n sys::switch_modes()?;\n\n let mut vt_parser = vt::Parser::new();\n let mut input_parser = input::Parser::new();\n let mut tui = Tui::new()?;\n\n let _restore = setup_terminal(&mut tui, &mut state, &mut vt_parser);\n\n state.menubar_color_bg = oklab_blend(\n tui.indexed(IndexedColor::Background),\n tui.indexed_alpha(IndexedColor::BrightBlue, 1, 2),\n );\n state.menubar_color_fg = tui.contrasted(state.menubar_color_bg);\n let floater_bg = oklab_blend(\n tui.indexed_alpha(IndexedColor::Background, 2, 3),\n tui.indexed_alpha(IndexedColor::Foreground, 1, 3),\n );\n let floater_fg = tui.contrasted(floater_bg);\n tui.setup_modifier_translations(ModifierTranslations {\n ctrl: loc(LocId::Ctrl),\n alt: loc(LocId::Alt),\n shift: loc(LocId::Shift),\n });\n tui.set_floater_default_bg(floater_bg);\n tui.set_floater_default_fg(floater_fg);\n tui.set_modal_default_bg(floater_bg);\n tui.set_modal_default_fg(floater_fg);\n\n sys::inject_window_size_into_stdin();\n\n #[cfg(feature = \"debug-latency\")]\n let mut last_latency_width = 0;\n\n loop {\n #[cfg(feature = \"debug-latency\")]\n let time_beg;\n #[cfg(feature = \"debug-latency\")]\n let mut passes;\n\n // Process a batch of input.\n {\n let scratch = scratch_arena(None);\n let read_timeout = vt_parser.read_timeout().min(tui.read_timeout());\n let Some(input) = sys::read_stdin(&scratch, read_timeout) else {\n break;\n };\n\n #[cfg(feature = \"debug-latency\")]\n {\n time_beg = std::time::Instant::now();\n passes = 0usize;\n }\n\n let vt_iter = vt_parser.parse(&input);\n let mut input_iter = input_parser.parse(vt_iter);\n\n while {\n let input = input_iter.next();\n let more = input.is_some();\n let mut ctx = tui.create_context(input);\n\n draw(&mut ctx, &mut state);\n\n #[cfg(feature = \"debug-latency\")]\n {\n passes += 1;\n }\n\n more\n } {}\n }\n\n // Continue rendering until the layout has settled.\n // This can take >1 frame, if the input focus is tossed between different controls.\n while tui.needs_settling() {\n let mut ctx = tui.create_context(None);\n\n draw(&mut ctx, &mut state);\n\n #[cfg(feature = \"debug-latency\")]\n {\n passes += 1;\n }\n }\n\n if state.exit {\n break;\n }\n\n // Render the UI and write it to the terminal.\n {\n let scratch = scratch_arena(None);\n let mut output = tui.render(&scratch);\n\n write_terminal_title(&mut output, &mut state);\n\n if state.osc_clipboard_sync {\n write_osc_clipboard(&mut tui, &mut state, &mut output);\n }\n\n #[cfg(feature = \"debug-latency\")]\n {\n // Print the number of passes and latency in the top right corner.\n let time_end = std::time::Instant::now();\n let status = time_end - time_beg;\n\n let scratch_alt = scratch_arena(Some(&scratch));\n let status = arena_format!(\n &scratch_alt,\n \"{}P {}B {:.3}μs\",\n passes,\n output.len(),\n status.as_nanos() as f64 / 1000.0\n );\n\n // \"μs\" is 3 bytes and 2 columns.\n let cols = status.len() as edit::helpers::CoordType - 3 + 2;\n\n // Since the status may shrink and grow, we may have to overwrite the previous one with whitespace.\n let padding = (last_latency_width - cols).max(0);\n\n // If the `output` is already very large,\n // Rust may double the size during the write below.\n // Let's avoid that by reserving the needed size in advance.\n output.reserve_exact(128);\n\n // To avoid moving the cursor, push and pop it onto the VT cursor stack.\n _ = write!(\n output,\n \"\\x1b7\\x1b[0;41;97m\\x1b[1;{0}H{1:2$}{3}\\x1b8\",\n tui.size().width - cols - padding + 1,\n \"\",\n padding as usize,\n status\n );\n\n last_latency_width = cols;\n }\n\n sys::write_stdout(&output);\n }\n }\n\n Ok(())\n}\n\n// Returns true if the application should exit early.\nfn handle_args(state: &mut State) -> apperr::Result {\n let scratch = scratch_arena(None);\n let mut paths: Vec = Vec::new_in(&*scratch);\n let mut cwd = env::current_dir()?;\n\n // The best CLI argument parser in the world.\n for arg in env::args_os().skip(1) {\n if arg == \"-h\" || arg == \"--help\" || (cfg!(windows) && arg == \"/?\") {\n print_help();\n return Ok(true);\n } else if arg == \"-v\" || arg == \"--version\" {\n print_version();\n return Ok(true);\n } else if arg == \"-\" {\n paths.clear();\n break;\n }\n let p = cwd.join(Path::new(&arg));\n let p = path::normalize(&p);\n if !p.is_dir() {\n paths.push(p);\n }\n }\n\n for p in &paths {\n state.documents.add_file_path(p)?;\n }\n if let Some(parent) = paths.first().and_then(|p| p.parent()) {\n cwd = parent.to_path_buf();\n }\n\n if let Some(mut file) = sys::open_stdin_if_redirected() {\n let doc = state.documents.add_untitled()?;\n let mut tb = doc.buffer.borrow_mut();\n tb.read_file(&mut file, None)?;\n tb.mark_as_dirty();\n } else if paths.is_empty() {\n // No files were passed, and stdin is not redirected.\n state.documents.add_untitled()?;\n }\n\n state.file_picker_pending_dir = DisplayablePathBuf::from_path(cwd);\n Ok(false)\n}\n\nfn print_help() {\n sys::write_stdout(concat!(\n \"Usage: edit [OPTIONS] [FILE[:LINE[:COLUMN]]]\\n\",\n \"Options:\\n\",\n \" -h, --help Print this help message\\n\",\n \" -v, --version Print the version number\\n\",\n \"\\n\",\n \"Arguments:\\n\",\n \" FILE[:LINE[:COLUMN]] The file to open, optionally with line and column (e.g., foo.txt:123:45)\\n\",\n ));\n}\n\nfn print_version() {\n sys::write_stdout(concat!(\"edit version \", env!(\"CARGO_PKG_VERSION\"), \"\\n\"));\n}\n\nfn draw(ctx: &mut Context, state: &mut State) {\n draw_menubar(ctx, state);\n draw_editor(ctx, state);\n draw_statusbar(ctx, state);\n\n if state.wants_close {\n draw_handle_wants_close(ctx, state);\n }\n if state.wants_exit {\n draw_handle_wants_exit(ctx, state);\n }\n if state.wants_goto {\n draw_goto_menu(ctx, state);\n }\n if state.wants_file_picker != StateFilePicker::None {\n draw_file_picker(ctx, state);\n }\n if state.wants_save {\n draw_handle_save(ctx, state);\n }\n if state.wants_encoding_change != StateEncodingChange::None {\n draw_dialog_encoding_change(ctx, state);\n }\n if state.wants_go_to_file {\n draw_go_to_file(ctx, state);\n }\n if state.wants_about {\n draw_dialog_about(ctx, state);\n }\n if ctx.clipboard_ref().wants_host_sync() {\n draw_handle_clipboard_change(ctx, state);\n }\n if state.error_log_count != 0 {\n draw_error_log(ctx, state);\n }\n\n if let Some(key) = ctx.keyboard_input() {\n // Shortcuts that are not handled as part of the textarea, etc.\n\n if key == kbmod::CTRL | vk::N {\n draw_add_untitled_document(ctx, state);\n } else if key == kbmod::CTRL | vk::O {\n state.wants_file_picker = StateFilePicker::Open;\n } else if key == kbmod::CTRL | vk::S {\n state.wants_save = true;\n } else if key == kbmod::CTRL_SHIFT | vk::S {\n state.wants_file_picker = StateFilePicker::SaveAs;\n } else if key == kbmod::CTRL | vk::W {\n state.wants_close = true;\n } else if key == kbmod::CTRL | vk::P {\n state.wants_go_to_file = true;\n } else if key == kbmod::CTRL | vk::Q {\n state.wants_exit = true;\n } else if key == kbmod::CTRL | vk::G {\n state.wants_goto = true;\n } else if key == kbmod::CTRL | vk::F && state.wants_search.kind != StateSearchKind::Disabled\n {\n state.wants_search.kind = StateSearchKind::Search;\n state.wants_search.focus = true;\n } else if key == kbmod::CTRL | vk::R && state.wants_search.kind != StateSearchKind::Disabled\n {\n state.wants_search.kind = StateSearchKind::Replace;\n state.wants_search.focus = true;\n } else if key == vk::F3 {\n search_execute(ctx, state, SearchAction::Search);\n } else {\n return;\n }\n\n // All of the above shortcuts happen to require a rerender.\n ctx.needs_rerender();\n ctx.set_input_consumed();\n }\n}\n\nfn draw_handle_wants_exit(_ctx: &mut Context, state: &mut State) {\n while let Some(doc) = state.documents.active() {\n if doc.buffer.borrow().is_dirty() {\n state.wants_close = true;\n return;\n }\n state.documents.remove_active();\n }\n\n if state.documents.len() == 0 {\n state.exit = true;\n }\n}\n\nfn write_terminal_title(output: &mut ArenaString, state: &mut State) {\n let (filename, dirty) = state\n .documents\n .active()\n .map_or((\"\", false), |d| (&d.filename, d.buffer.borrow().is_dirty()));\n\n if filename == state.osc_title_file_status.filename\n && dirty == state.osc_title_file_status.dirty\n {\n return;\n }\n\n output.push_str(\"\\x1b]0;\");\n if !filename.is_empty() {\n if dirty {\n output.push_str(\"● \");\n }\n output.push_str(&sanitize_control_chars(filename));\n output.push_str(\" - \");\n }\n output.push_str(\"edit\\x1b\\\\\");\n\n state.osc_title_file_status.filename = filename.to_string();\n state.osc_title_file_status.dirty = dirty;\n}\n\nconst LARGE_CLIPBOARD_THRESHOLD: usize = 128 * KIBI;\n\nfn draw_handle_clipboard_change(ctx: &mut Context, state: &mut State) {\n let data_len = ctx.clipboard_ref().read().len();\n\n if state.osc_clipboard_always_send || data_len < LARGE_CLIPBOARD_THRESHOLD {\n ctx.clipboard_mut().mark_as_synchronized();\n state.osc_clipboard_sync = true;\n return;\n }\n\n let over_limit = data_len >= SCRATCH_ARENA_CAPACITY / 4;\n let mut done = None;\n\n ctx.modal_begin(\"warning\", loc(LocId::WarningDialogTitle));\n {\n ctx.block_begin(\"description\");\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n if over_limit {\n ctx.label(\"line1\", loc(LocId::LargeClipboardWarningLine1));\n ctx.attr_position(Position::Center);\n ctx.label(\"line2\", loc(LocId::SuperLargeClipboardWarning));\n ctx.attr_position(Position::Center);\n } else {\n let label2 = {\n let template = loc(LocId::LargeClipboardWarningLine2);\n let size = arena_format!(ctx.arena(), \"{}\", MetricFormatter(data_len));\n\n let mut label =\n ArenaString::with_capacity_in(template.len() + size.len(), ctx.arena());\n label.push_str(template);\n label.replace_once_in_place(\"{size}\", &size);\n label\n };\n\n ctx.label(\"line1\", loc(LocId::LargeClipboardWarningLine1));\n ctx.attr_position(Position::Center);\n ctx.label(\"line2\", &label2);\n ctx.attr_position(Position::Center);\n ctx.label(\"line3\", loc(LocId::LargeClipboardWarningLine3));\n ctx.attr_position(Position::Center);\n }\n ctx.block_end();\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n if over_limit {\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n done = Some(true);\n }\n ctx.inherit_focus();\n } else {\n if ctx.button(\"always\", loc(LocId::Always), ButtonStyle::default()) {\n state.osc_clipboard_always_send = true;\n done = Some(true);\n }\n\n if ctx.button(\"yes\", loc(LocId::Yes), ButtonStyle::default()) {\n done = Some(true);\n }\n if data_len < 10 * LARGE_CLIPBOARD_THRESHOLD {\n ctx.inherit_focus();\n }\n\n if ctx.button(\"no\", loc(LocId::No), ButtonStyle::default()) {\n done = Some(false);\n }\n if data_len >= 10 * LARGE_CLIPBOARD_THRESHOLD {\n ctx.inherit_focus();\n }\n }\n }\n ctx.table_end();\n }\n if ctx.modal_end() {\n done = Some(false);\n }\n\n if let Some(sync) = done {\n state.osc_clipboard_sync = sync;\n ctx.clipboard_mut().mark_as_synchronized();\n ctx.needs_rerender();\n }\n}\n\n#[cold]\nfn write_osc_clipboard(tui: &mut Tui, state: &mut State, output: &mut ArenaString) {\n let clipboard = tui.clipboard_mut();\n let data = clipboard.read();\n\n if !data.is_empty() {\n // Rust doubles the size of a string when it needs to grow it.\n // If `data` is *really* large, this may then double\n // the size of the `output` from e.g. 100MB to 200MB. Not good.\n // We can avoid that by reserving the needed size in advance.\n output.reserve_exact(base64::encode_len(data.len()) + 16);\n output.push_str(\"\\x1b]52;c;\");\n base64::encode(output, data);\n output.push_str(\"\\x1b\\\\\");\n }\n\n state.osc_clipboard_sync = false;\n}\n\nstruct RestoreModes;\n\nimpl Drop for RestoreModes {\n fn drop(&mut self) {\n // Same as in the beginning but in the reverse order.\n // It also includes DECSCUSR 0 to reset the cursor style and DECTCEM to show the cursor.\n // We specifically don't reset mode 1036, because most applications expect it to be set nowadays.\n sys::write_stdout(\"\\x1b[0 q\\x1b[?25h\\x1b]0;\\x07\\x1b[?1002;1006;2004l\\x1b[?1049l\");\n }\n}\n\nfn setup_terminal(tui: &mut Tui, state: &mut State, vt_parser: &mut vt::Parser) -> RestoreModes {\n sys::write_stdout(concat!(\n // 1049: Alternative Screen Buffer\n // I put the ASB switch in the beginning, just in case the terminal performs\n // some additional state tracking beyond the modes we enable/disable.\n // 1002: Cell Motion Mouse Tracking\n // 1006: SGR Mouse Mode\n // 2004: Bracketed Paste Mode\n // 1036: Xterm: \"meta sends escape\" (Alt keypresses should be encoded with ESC + char)\n \"\\x1b[?1049h\\x1b[?1002;1006;2004h\\x1b[?1036h\",\n // OSC 4 color table requests for indices 0 through 15 (base colors).\n \"\\x1b]4;0;?;1;?;2;?;3;?;4;?;5;?;6;?;7;?\\x07\",\n \"\\x1b]4;8;?;9;?;10;?;11;?;12;?;13;?;14;?;15;?\\x07\",\n // OSC 10 and 11 queries for the current foreground and background colors.\n \"\\x1b]10;?\\x07\\x1b]11;?\\x07\",\n // Test whether ambiguous width characters are two columns wide.\n // We use \"…\", because it's the most common ambiguous width character we use,\n // and the old Windows conhost doesn't actually use wcwidth, it measures the\n // actual display width of the character and assigns it columns accordingly.\n // We detect it by writing the character and asking for the cursor position.\n \"\\r…\\x1b[6n\",\n // CSI c reports the terminal capabilities.\n // It also helps us to detect the end of the responses, because not all\n // terminals support the OSC queries, but all of them support CSI c.\n \"\\x1b[c\",\n ));\n\n let mut done = false;\n let mut osc_buffer = String::new();\n let mut indexed_colors = framebuffer::DEFAULT_THEME;\n let mut color_responses = 0;\n let mut ambiguous_width = 1;\n\n while !done {\n let scratch = scratch_arena(None);\n\n // We explicitly set a high read timeout, because we're not\n // waiting for user keyboard input. If we encounter a lone ESC,\n // it's unlikely to be from a ESC keypress, but rather from a VT sequence.\n let Some(input) = sys::read_stdin(&scratch, Duration::from_secs(3)) else {\n break;\n };\n\n let mut vt_stream = vt_parser.parse(&input);\n while let Some(token) = vt_stream.next() {\n match token {\n Token::Csi(csi) => match csi.final_byte {\n 'c' => done = true,\n // CPR (Cursor Position Report) response.\n 'R' => ambiguous_width = csi.params[1] as CoordType - 1,\n _ => {}\n },\n Token::Osc { mut data, partial } => {\n if partial {\n osc_buffer.push_str(data);\n continue;\n }\n if !osc_buffer.is_empty() {\n osc_buffer.push_str(data);\n data = &osc_buffer;\n }\n\n let mut splits = data.split_terminator(';');\n\n let color = match splits.next().unwrap_or(\"\") {\n // The response is `4;;rgb://`.\n \"4\" => match splits.next().unwrap_or(\"\").parse::() {\n Ok(val) if val < 16 => &mut indexed_colors[val],\n _ => continue,\n },\n // The response is `10;rgb://`.\n \"10\" => &mut indexed_colors[IndexedColor::Foreground as usize],\n // The response is `11;rgb://`.\n \"11\" => &mut indexed_colors[IndexedColor::Background as usize],\n _ => continue,\n };\n\n let color_param = splits.next().unwrap_or(\"\");\n if !color_param.starts_with(\"rgb:\") {\n continue;\n }\n\n let mut iter = color_param[4..].split_terminator('/');\n let rgb_parts = [(); 3].map(|_| iter.next().unwrap_or(\"0\"));\n let mut rgb = 0;\n\n for part in rgb_parts {\n if part.len() == 2 || part.len() == 4 {\n let Ok(mut val) = usize::from_str_radix(part, 16) else {\n continue;\n };\n if part.len() == 4 {\n // Round from 16 bits to 8 bits.\n val = (val * 0xff + 0x7fff) / 0xffff;\n }\n rgb = (rgb >> 8) | ((val as u32) << 16);\n }\n }\n\n *color = rgb | 0xff000000;\n color_responses += 1;\n osc_buffer.clear();\n }\n _ => {}\n }\n }\n }\n\n if ambiguous_width == 2 {\n unicode::setup_ambiguous_width(2);\n state.documents.reflow_all();\n }\n\n if color_responses == indexed_colors.len() {\n tui.setup_indexed_colors(indexed_colors);\n }\n\n RestoreModes\n}\n\n/// Strips all C0 control characters from the string and replaces them with \"_\".\n///\n/// Jury is still out on whether this should also strip C1 control characters.\n/// That requires parsing UTF8 codepoints, which is annoying.\nfn sanitize_control_chars(text: &str) -> Cow<'_, str> {\n if let Some(off) = text.bytes().position(|b| (..0x20).contains(&b)) {\n let mut sanitized = text.to_string();\n // SAFETY: We only search for ASCII and replace it with ASCII.\n let vec = unsafe { sanitized.as_bytes_mut() };\n\n for i in &mut vec[off..] {\n *i = if (..0x20).contains(i) { b'_' } else { *i }\n }\n\n Cow::Owned(sanitized)\n } else {\n Cow::Borrowed(text)\n }\n}\n"], ["/edit/src/arena/string.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::fmt;\nuse std::ops::{Bound, Deref, DerefMut, RangeBounds};\n\nuse super::Arena;\nuse crate::helpers::*;\n\n/// A custom string type, because `std` lacks allocator support for [`String`].\n///\n/// To keep things simple, this one is hardcoded to [`Arena`].\n#[derive(Clone)]\npub struct ArenaString<'a> {\n vec: Vec,\n}\n\nimpl<'a> ArenaString<'a> {\n /// Creates a new [`ArenaString`] in the given arena.\n #[must_use]\n pub const fn new_in(arena: &'a Arena) -> Self {\n Self { vec: Vec::new_in(arena) }\n }\n\n #[must_use]\n pub fn with_capacity_in(capacity: usize, arena: &'a Arena) -> Self {\n Self { vec: Vec::with_capacity_in(capacity, arena) }\n }\n\n /// Turns a [`str`] into an [`ArenaString`].\n #[must_use]\n pub fn from_str(arena: &'a Arena, s: &str) -> Self {\n let mut res = Self::new_in(arena);\n res.push_str(s);\n res\n }\n\n /// It says right here that you checked if `bytes` is valid UTF-8\n /// and you are sure it is. Presto! Here's an `ArenaString`!\n ///\n /// # Safety\n ///\n /// You fool! It says \"unchecked\" right there. Now the house is burning.\n #[inline]\n #[must_use]\n pub unsafe fn from_utf8_unchecked(bytes: Vec) -> Self {\n Self { vec: bytes }\n }\n\n /// Checks whether `text` contains only valid UTF-8.\n /// If the entire string is valid, it returns `Ok(text)`.\n /// Otherwise, it returns `Err(ArenaString)` with all invalid sequences replaced with U+FFFD.\n pub fn from_utf8_lossy<'s>(arena: &'a Arena, text: &'s [u8]) -> Result<&'s str, Self> {\n let mut iter = text.utf8_chunks();\n let Some(mut chunk) = iter.next() else {\n return Ok(\"\");\n };\n\n let valid = chunk.valid();\n if chunk.invalid().is_empty() {\n debug_assert_eq!(valid.len(), text.len());\n return Ok(unsafe { str::from_utf8_unchecked(text) });\n }\n\n const REPLACEMENT: &str = \"\\u{FFFD}\";\n\n let mut res = Self::new_in(arena);\n res.reserve(text.len());\n\n loop {\n res.push_str(chunk.valid());\n if !chunk.invalid().is_empty() {\n res.push_str(REPLACEMENT);\n }\n chunk = match iter.next() {\n Some(chunk) => chunk,\n None => break,\n };\n }\n\n Err(res)\n }\n\n /// Turns a [`Vec`] into an [`ArenaString`], replacing invalid UTF-8 sequences with U+FFFD.\n #[must_use]\n pub fn from_utf8_lossy_owned(v: Vec) -> Self {\n match Self::from_utf8_lossy(v.allocator(), &v) {\n Ok(..) => unsafe { Self::from_utf8_unchecked(v) },\n Err(s) => s,\n }\n }\n\n /// It's empty.\n pub fn is_empty(&self) -> bool {\n self.vec.is_empty()\n }\n\n /// It's lengthy.\n pub fn len(&self) -> usize {\n self.vec.len()\n }\n\n /// It's capacatity.\n pub fn capacity(&self) -> usize {\n self.vec.capacity()\n }\n\n /// It's a [`String`], now it's a [`str`]. Wow!\n pub fn as_str(&self) -> &str {\n unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }\n }\n\n /// It's a [`String`], now it's a [`str`]. And it's mutable! WOW!\n pub fn as_mut_str(&mut self) -> &mut str {\n unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }\n }\n\n /// Now it's bytes!\n pub fn as_bytes(&self) -> &[u8] {\n self.vec.as_slice()\n }\n\n /// Returns a mutable reference to the contents of this `String`.\n ///\n /// # Safety\n ///\n /// The underlying `&mut Vec` allows writing bytes which are not valid UTF-8.\n pub unsafe fn as_mut_vec(&mut self) -> &mut Vec {\n &mut self.vec\n }\n\n /// Reserves *additional* memory. For you old folks out there (totally not me),\n /// this is different from C++'s `reserve` which reserves a total size.\n pub fn reserve(&mut self, additional: usize) {\n self.vec.reserve(additional)\n }\n\n /// Just like [`ArenaString::reserve`], but it doesn't overallocate.\n pub fn reserve_exact(&mut self, additional: usize) {\n self.vec.reserve_exact(additional)\n }\n\n /// Now it's small! Alarming!\n ///\n /// *Do not* call this unless this string is the last thing on the arena.\n /// Arenas are stacks, they can't deallocate what's in the middle.\n pub fn shrink_to_fit(&mut self) {\n self.vec.shrink_to_fit()\n }\n\n /// To no surprise, this clears the string.\n pub fn clear(&mut self) {\n self.vec.clear()\n }\n\n /// Append some text.\n pub fn push_str(&mut self, string: &str) {\n self.vec.extend_from_slice(string.as_bytes())\n }\n\n /// Append a single character.\n #[inline]\n pub fn push(&mut self, ch: char) {\n match ch.len_utf8() {\n 1 => self.vec.push(ch as u8),\n _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),\n }\n }\n\n /// Same as `push(char)` but with a specified number of character copies.\n /// Shockingly absent from the standard library.\n pub fn push_repeat(&mut self, ch: char, total_copies: usize) {\n if total_copies == 0 {\n return;\n }\n\n let buf = unsafe { self.as_mut_vec() };\n\n if ch.is_ascii() {\n // Compiles down to `memset()`.\n buf.extend(std::iter::repeat_n(ch as u8, total_copies));\n } else {\n // Implements efficient string padding using quadratic duplication.\n let mut utf8_buf = [0; 4];\n let utf8 = ch.encode_utf8(&mut utf8_buf).as_bytes();\n let initial_len = buf.len();\n let added_len = utf8.len() * total_copies;\n let final_len = initial_len + added_len;\n\n buf.reserve(added_len);\n buf.extend_from_slice(utf8);\n\n while buf.len() != final_len {\n let end = (final_len - buf.len() + initial_len).min(buf.len());\n buf.extend_from_within(initial_len..end);\n }\n }\n }\n\n /// Replaces a range of characters with a new string.\n pub fn replace_range>(&mut self, range: R, replace_with: &str) {\n match range.start_bound() {\n Bound::Included(&n) => assert!(self.is_char_boundary(n)),\n Bound::Excluded(&n) => assert!(self.is_char_boundary(n + 1)),\n Bound::Unbounded => {}\n };\n match range.end_bound() {\n Bound::Included(&n) => assert!(self.is_char_boundary(n + 1)),\n Bound::Excluded(&n) => assert!(self.is_char_boundary(n)),\n Bound::Unbounded => {}\n };\n unsafe { self.as_mut_vec() }.replace_range(range, replace_with.as_bytes());\n }\n\n /// Finds `old` in the string and replaces it with `new`.\n /// Only performs one replacement.\n pub fn replace_once_in_place(&mut self, old: &str, new: &str) {\n if let Some(beg) = self.find(old) {\n unsafe { self.as_mut_vec() }.replace_range(beg..beg + old.len(), new.as_bytes());\n }\n }\n}\n\nimpl fmt::Debug for ArenaString<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n fmt::Debug::fmt(&**self, f)\n }\n}\n\nimpl PartialEq<&str> for ArenaString<'_> {\n fn eq(&self, other: &&str) -> bool {\n self.as_str() == *other\n }\n}\n\nimpl Deref for ArenaString<'_> {\n type Target = str;\n\n fn deref(&self) -> &Self::Target {\n self.as_str()\n }\n}\n\nimpl DerefMut for ArenaString<'_> {\n fn deref_mut(&mut self) -> &mut Self::Target {\n self.as_mut_str()\n }\n}\n\nimpl fmt::Display for ArenaString<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.write_str(self.as_str())\n }\n}\n\nimpl fmt::Write for ArenaString<'_> {\n #[inline]\n fn write_str(&mut self, s: &str) -> fmt::Result {\n self.push_str(s);\n Ok(())\n }\n\n #[inline]\n fn write_char(&mut self, c: char) -> fmt::Result {\n self.push(c);\n Ok(())\n }\n}\n\n#[macro_export]\nmacro_rules! arena_format {\n ($arena:expr, $($arg:tt)*) => {{\n use std::fmt::Write as _;\n let mut output = $crate::arena::ArenaString::new_in($arena);\n output.write_fmt(format_args!($($arg)*)).unwrap();\n output\n }}\n}\n"], ["/edit/src/unicode/measurement.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::hint::cold_path;\n\nuse super::Utf8Chars;\nuse super::tables::*;\nuse crate::document::ReadableDocument;\nuse crate::helpers::{CoordType, Point};\n\n// On one hand it's disgusting that I wrote this as a global variable, but on the\n// other hand, this isn't a public library API, and it makes the code a lot cleaner,\n// because we don't need to inject this once-per-process value everywhere.\nstatic mut AMBIGUOUS_WIDTH: usize = 1;\n\n/// Sets the width of \"ambiguous\" width characters as per \"UAX #11: East Asian Width\".\n///\n/// Defaults to 1.\npub fn setup_ambiguous_width(ambiguous_width: CoordType) {\n unsafe { AMBIGUOUS_WIDTH = ambiguous_width as usize };\n}\n\n#[inline]\nfn ambiguous_width() -> usize {\n // SAFETY: This is a global variable that is set once per process.\n // It is never changed after that, so this is safe to call.\n unsafe { AMBIGUOUS_WIDTH }\n}\n\n/// Stores a position inside a [`ReadableDocument`].\n///\n/// The cursor tracks both the absolute byte-offset,\n/// as well as the position in terminal-related coordinates.\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Cursor {\n /// Offset in bytes within the buffer.\n pub offset: usize,\n /// Position in the buffer in lines (.y) and grapheme clusters (.x).\n ///\n /// Line wrapping has NO influence on this.\n pub logical_pos: Point,\n /// Position in the buffer in laid out rows (.y) and columns (.x).\n ///\n /// Line wrapping has an influence on this.\n pub visual_pos: Point,\n /// Horizontal position in visual columns.\n ///\n /// Line wrapping has NO influence on this and if word wrap is disabled,\n /// it's identical to `visual_pos.x`. This is useful for calculating tab widths.\n pub column: CoordType,\n /// When `measure_forward` hits the `word_wrap_column`, the question is:\n /// Was there a wrap opportunity on this line? Because if there wasn't,\n /// a hard-wrap is required; otherwise, the word that is being laid-out is\n /// moved to the next line. This boolean carries this state between calls.\n pub wrap_opp: bool,\n}\n\n/// Your entrypoint to navigating inside a [`ReadableDocument`].\n#[derive(Clone)]\npub struct MeasurementConfig<'doc> {\n cursor: Cursor,\n tab_size: CoordType,\n word_wrap_column: CoordType,\n buffer: &'doc dyn ReadableDocument,\n}\n\nimpl<'doc> MeasurementConfig<'doc> {\n /// Creates a new [`MeasurementConfig`] for the given document.\n pub fn new(buffer: &'doc dyn ReadableDocument) -> Self {\n Self { cursor: Default::default(), tab_size: 8, word_wrap_column: 0, buffer }\n }\n\n /// Sets the initial cursor to the given position.\n ///\n /// WARNING: While the code doesn't panic if the cursor is invalid,\n /// the results will obviously be complete garbage.\n pub fn with_cursor(mut self, cursor: Cursor) -> Self {\n self.cursor = cursor;\n self\n }\n\n /// Sets the tab size.\n ///\n /// Defaults to 8, because that's what a tab in terminals evaluates to.\n pub fn with_tab_size(mut self, tab_size: CoordType) -> Self {\n self.tab_size = tab_size.max(1);\n self\n }\n\n /// You want word wrap? Set it here!\n ///\n /// Defaults to 0, which means no word wrap.\n pub fn with_word_wrap_column(mut self, word_wrap_column: CoordType) -> Self {\n self.word_wrap_column = word_wrap_column;\n self\n }\n\n /// Navigates **forward** to the given absolute offset.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_offset(&mut self, offset: usize) -> Cursor {\n self.measure_forward(offset, Point::MAX, Point::MAX)\n }\n\n /// Navigates **forward** to the given logical position.\n ///\n /// Logical positions are in lines and grapheme clusters.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_logical(&mut self, logical_target: Point) -> Cursor {\n self.measure_forward(usize::MAX, logical_target, Point::MAX)\n }\n\n /// Navigates **forward** to the given visual position.\n ///\n /// Visual positions are in laid out rows and columns.\n ///\n /// # Returns\n ///\n /// The cursor position after the navigation.\n pub fn goto_visual(&mut self, visual_target: Point) -> Cursor {\n self.measure_forward(usize::MAX, Point::MAX, visual_target)\n }\n\n /// Returns the current cursor position.\n pub fn cursor(&self) -> Cursor {\n self.cursor\n }\n\n // NOTE that going to a visual target can result in ambiguous results,\n // where going to an identical logical target will yield a different result.\n //\n // Imagine if you have a `word_wrap_column` of 6 and there's \"Hello World\" on the line:\n // `goto_logical` will return a `visual_pos` of {0,1}, while `goto_visual` returns {6,0}.\n // This is because from a logical POV, if the wrap location equals the wrap column,\n // the wrap exists on both lines and it'll default to wrapping. `goto_visual` however will always\n // try to return a Y position that matches the requested position, so that Home/End works properly.\n fn measure_forward(\n &mut self,\n offset_target: usize,\n logical_target: Point,\n visual_target: Point,\n ) -> Cursor {\n if self.cursor.offset >= offset_target\n || self.cursor.logical_pos >= logical_target\n || self.cursor.visual_pos >= visual_target\n {\n return self.cursor;\n }\n\n let mut offset = self.cursor.offset;\n let mut logical_pos_x = self.cursor.logical_pos.x;\n let mut logical_pos_y = self.cursor.logical_pos.y;\n let mut visual_pos_x = self.cursor.visual_pos.x;\n let mut visual_pos_y = self.cursor.visual_pos.y;\n let mut column = self.cursor.column;\n\n let mut logical_target_x = Self::calc_target_x(logical_target, logical_pos_y);\n let mut visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n\n // wrap_opp = Wrap Opportunity\n // These store the position and column of the last wrap opportunity. If `word_wrap_column` is\n // zero (word wrap disabled), all grapheme clusters are a wrap opportunity, because none are.\n let mut wrap_opp = self.cursor.wrap_opp;\n let mut wrap_opp_offset = offset;\n let mut wrap_opp_logical_pos_x = logical_pos_x;\n let mut wrap_opp_visual_pos_x = visual_pos_x;\n let mut wrap_opp_column = column;\n\n let mut chunk_iter = Utf8Chars::new(b\"\", 0);\n let mut chunk_range = offset..offset;\n let mut props_next_cluster = ucd_start_of_text_properties();\n\n loop {\n // Have we reached the target already? Stop.\n if offset >= offset_target\n || logical_pos_x >= logical_target_x\n || visual_pos_x >= visual_target_x\n {\n break;\n }\n\n let props_current_cluster = props_next_cluster;\n let mut props_last_char;\n let mut offset_next_cluster;\n let mut state = 0;\n let mut width = 0;\n\n // Since we want to measure the width of the current cluster,\n // by necessity we need to seek to the next cluster.\n // We'll then reuse the offset and properties of the next cluster in\n // the next iteration of the this (outer) loop (`props_next_cluster`).\n loop {\n if !chunk_iter.has_next() {\n cold_path();\n chunk_iter = Utf8Chars::new(self.buffer.read_forward(chunk_range.end), 0);\n chunk_range = chunk_range.end..chunk_range.end + chunk_iter.len();\n }\n\n // Since this loop seeks ahead to the next cluster, and since `chunk_iter`\n // records the offset of the next character after the returned one, we need\n // to save the offset of the previous `chunk_iter` before calling `next()`.\n // Similar applies to the width.\n props_last_char = props_next_cluster;\n offset_next_cluster = chunk_range.start + chunk_iter.offset();\n width += ucd_grapheme_cluster_character_width(props_next_cluster, ambiguous_width())\n as CoordType;\n\n // The `Document::read_forward` interface promises us that it will not split\n // grapheme clusters across chunks. Therefore, we can safely break here.\n let ch = match chunk_iter.next() {\n Some(ch) => ch,\n None => break,\n };\n\n // Get the properties of the next cluster.\n props_next_cluster = ucd_grapheme_cluster_lookup(ch);\n state = ucd_grapheme_cluster_joins(state, props_last_char, props_next_cluster);\n\n // Stop if the next character does not join.\n if ucd_grapheme_cluster_joins_done(state) {\n break;\n }\n }\n\n if offset_next_cluster == offset {\n // No advance and the iterator is empty? End of text reached.\n if chunk_iter.is_empty() {\n break;\n }\n // Ignore the first iteration when processing the start-of-text.\n continue;\n }\n\n // The max. width of a terminal cell is 2.\n width = width.min(2);\n\n // Tabs require special handling because they can have a variable width.\n if props_last_char == ucd_tab_properties() {\n // SAFETY: `self.tab_size` is clamped to >= 1 in `with_tab_size`.\n // This assert ensures that Rust doesn't insert panicking null checks.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1) };\n width = self.tab_size - (column % self.tab_size);\n }\n\n // Hard wrap: Both the logical and visual position advance by one line.\n if props_last_char == ucd_linefeed_properties() {\n cold_path();\n\n wrap_opp = false;\n\n // Don't cross the newline if the target is on this line but we haven't reached it.\n // E.g. if the callers asks for column 100 on a 10 column line,\n // we'll return with the cursor set to column 10.\n if logical_pos_y >= logical_target.y || visual_pos_y >= visual_target.y {\n break;\n }\n\n offset = offset_next_cluster;\n logical_pos_x = 0;\n logical_pos_y += 1;\n visual_pos_x = 0;\n visual_pos_y += 1;\n column = 0;\n\n logical_target_x = Self::calc_target_x(logical_target, logical_pos_y);\n visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n continue;\n }\n\n // Avoid advancing past the visual target, because `width` can be greater than 1.\n if visual_pos_x + width > visual_target_x {\n break;\n }\n\n // Since this code above may need to revert to a previous `wrap_opp_*`,\n // it must be done before advancing / checking for `ucd_line_break_joins`.\n if self.word_wrap_column > 0 && visual_pos_x + width > self.word_wrap_column {\n if !wrap_opp {\n // Otherwise, the lack of a wrap opportunity means that a single word\n // is wider than the word wrap column. We need to force-break the word.\n // This is similar to the above, but \"bar\" gets written at column 0.\n wrap_opp_offset = offset;\n wrap_opp_logical_pos_x = logical_pos_x;\n wrap_opp_visual_pos_x = visual_pos_x;\n wrap_opp_column = column;\n visual_pos_x = 0;\n } else {\n // If we had a wrap opportunity on this line, we can move all\n // characters since then to the next line without stopping this loop:\n // +---------+ +---------+ +---------+\n // | foo| -> | | -> | |\n // | | |foo | |foobar |\n // +---------+ +---------+ +---------+\n // We don't actually move \"foo\", but rather just change where \"bar\" goes.\n // Since this function doesn't copy text, the end result is the same.\n visual_pos_x -= wrap_opp_visual_pos_x;\n }\n\n wrap_opp = false;\n visual_pos_y += 1;\n visual_target_x = Self::calc_target_x(visual_target, visual_pos_y);\n\n if visual_pos_x == visual_target_x {\n break;\n }\n\n // Imagine the word is \"hello\" and on the \"o\" we notice it wraps.\n // If the target however was the \"e\", then we must revert back to \"h\" and search for it.\n if visual_pos_x > visual_target_x {\n cold_path();\n\n offset = wrap_opp_offset;\n logical_pos_x = wrap_opp_logical_pos_x;\n visual_pos_x = 0;\n column = wrap_opp_column;\n\n chunk_iter.seek(chunk_iter.len());\n chunk_range = offset..offset;\n props_next_cluster = ucd_start_of_text_properties();\n continue;\n }\n }\n\n offset = offset_next_cluster;\n logical_pos_x += 1;\n visual_pos_x += width;\n column += width;\n\n if self.word_wrap_column > 0\n && !ucd_line_break_joins(props_current_cluster, props_next_cluster)\n {\n wrap_opp = true;\n wrap_opp_offset = offset;\n wrap_opp_logical_pos_x = logical_pos_x;\n wrap_opp_visual_pos_x = visual_pos_x;\n wrap_opp_column = column;\n }\n }\n\n // If we're here, we hit our target. Now the only question is:\n // Is the word we're currently on so wide that it will be wrapped further down the document?\n if self.word_wrap_column > 0 {\n if !wrap_opp {\n // If the current laid-out line had no wrap opportunities, it means we had an input\n // such as \"fooooooooooooooooooooo\" at a `word_wrap_column` of e.g. 10. The word\n // didn't fit and the lack of a `wrap_opp` indicates we must force a hard wrap.\n // Thankfully, if we reach this point, that was already done by the code above.\n } else if wrap_opp_logical_pos_x != logical_pos_x && visual_pos_y <= visual_target.y {\n // Imagine the string \"foo bar\" with a word wrap column of 6. If I ask for the cursor at\n // `logical_pos={5,0}`, then the code above exited while reaching the target.\n // At this point, this function doesn't know yet that after the \"b\" there's \"ar\"\n // which causes a word wrap, and causes the final visual position to be {1,1}.\n // This code thus seeks ahead and checks if the current word will wrap or not.\n // Of course we only need to do this if the cursor isn't on a wrap opportunity already.\n\n // The loop below should not modify the target we already found.\n let mut visual_pos_x_lookahead = visual_pos_x;\n\n loop {\n let props_current_cluster = props_next_cluster;\n let mut props_last_char;\n let mut offset_next_cluster;\n let mut state = 0;\n let mut width = 0;\n\n // Since we want to measure the width of the current cluster,\n // by necessity we need to seek to the next cluster.\n // We'll then reuse the offset and properties of the next cluster in\n // the next iteration of the this (outer) loop (`props_next_cluster`).\n loop {\n if !chunk_iter.has_next() {\n cold_path();\n chunk_iter =\n Utf8Chars::new(self.buffer.read_forward(chunk_range.end), 0);\n chunk_range = chunk_range.end..chunk_range.end + chunk_iter.len();\n }\n\n // Since this loop seeks ahead to the next cluster, and since `chunk_iter`\n // records the offset of the next character after the returned one, we need\n // to save the offset of the previous `chunk_iter` before calling `next()`.\n // Similar applies to the width.\n props_last_char = props_next_cluster;\n offset_next_cluster = chunk_range.start + chunk_iter.offset();\n width += ucd_grapheme_cluster_character_width(\n props_next_cluster,\n ambiguous_width(),\n ) as CoordType;\n\n // The `Document::read_forward` interface promises us that it will not split\n // grapheme clusters across chunks. Therefore, we can safely break here.\n let ch = match chunk_iter.next() {\n Some(ch) => ch,\n None => break,\n };\n\n // Get the properties of the next cluster.\n props_next_cluster = ucd_grapheme_cluster_lookup(ch);\n state =\n ucd_grapheme_cluster_joins(state, props_last_char, props_next_cluster);\n\n // Stop if the next character does not join.\n if ucd_grapheme_cluster_joins_done(state) {\n break;\n }\n }\n\n if offset_next_cluster == offset {\n // No advance and the iterator is empty? End of text reached.\n if chunk_iter.is_empty() {\n break;\n }\n // Ignore the first iteration when processing the start-of-text.\n continue;\n }\n\n // The max. width of a terminal cell is 2.\n width = width.min(2);\n\n // Tabs require special handling because they can have a variable width.\n if props_last_char == ucd_tab_properties() {\n // SAFETY: `self.tab_size` is clamped to >= 1 in `with_tab_size`.\n // This assert ensures that Rust doesn't insert panicking null checks.\n unsafe { std::hint::assert_unchecked(self.tab_size >= 1) };\n width = self.tab_size - (column % self.tab_size);\n }\n\n // Hard wrap: Both the logical and visual position advance by one line.\n if props_last_char == ucd_linefeed_properties() {\n break;\n }\n\n visual_pos_x_lookahead += width;\n\n if visual_pos_x_lookahead > self.word_wrap_column {\n visual_pos_x -= wrap_opp_visual_pos_x;\n visual_pos_y += 1;\n break;\n } else if !ucd_line_break_joins(props_current_cluster, props_next_cluster) {\n break;\n }\n }\n }\n\n if visual_pos_y > visual_target.y {\n // Imagine the string \"foo bar\" with a word wrap column of 6. If I ask for the cursor at\n // `visual_pos={100,0}`, the code above exited early after wrapping without reaching the target.\n // Since I asked for the last character on the first line, we must wrap back up the last wrap\n offset = wrap_opp_offset;\n logical_pos_x = wrap_opp_logical_pos_x;\n visual_pos_x = wrap_opp_visual_pos_x;\n visual_pos_y = visual_target.y;\n column = wrap_opp_column;\n wrap_opp = true;\n }\n }\n\n self.cursor.offset = offset;\n self.cursor.logical_pos = Point { x: logical_pos_x, y: logical_pos_y };\n self.cursor.visual_pos = Point { x: visual_pos_x, y: visual_pos_y };\n self.cursor.column = column;\n self.cursor.wrap_opp = wrap_opp;\n self.cursor\n }\n\n #[inline]\n fn calc_target_x(target: Point, pos_y: CoordType) -> CoordType {\n match pos_y.cmp(&target.y) {\n std::cmp::Ordering::Less => CoordType::MAX,\n std::cmp::Ordering::Equal => target.x,\n std::cmp::Ordering::Greater => 0,\n }\n }\n}\n\n/// Returns an offset past a newline.\n///\n/// If `offset` is right in front of a newline,\n/// this will return the offset past said newline.\npub fn skip_newline(text: &[u8], mut offset: usize) -> usize {\n if offset >= text.len() {\n return offset;\n }\n if text[offset] == b'\\r' {\n offset += 1;\n }\n if offset >= text.len() {\n return offset;\n }\n if text[offset] == b'\\n' {\n offset += 1;\n }\n offset\n}\n\n/// Strips a trailing newline from the given text.\npub fn strip_newline(mut text: &[u8]) -> &[u8] {\n // Rust generates surprisingly tight assembly for this.\n if text.last() == Some(&b'\\n') {\n text = &text[..text.len() - 1];\n }\n if text.last() == Some(&b'\\r') {\n text = &text[..text.len() - 1];\n }\n text\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n struct ChunkedDoc<'a>(&'a [&'a [u8]]);\n\n impl ReadableDocument for ChunkedDoc<'_> {\n fn read_forward(&self, mut off: usize) -> &[u8] {\n for chunk in self.0 {\n if off < chunk.len() {\n return &chunk[off..];\n }\n off -= chunk.len();\n }\n &[]\n }\n\n fn read_backward(&self, mut off: usize) -> &[u8] {\n for chunk in self.0.iter().rev() {\n if off < chunk.len() {\n return &chunk[..chunk.len() - off];\n }\n off -= chunk.len();\n }\n &[]\n }\n }\n\n #[test]\n fn test_measure_forward_newline_start() {\n let cursor =\n MeasurementConfig::new(&\"foo\\nbar\".as_bytes()).goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 1 },\n column: 0,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_clipped_wide_char() {\n let cursor = MeasurementConfig::new(&\"a😶‍🌫️b\".as_bytes()).goto_visual(Point { x: 2, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 1,\n logical_pos: Point { x: 1, y: 0 },\n visual_pos: Point { x: 1, y: 0 },\n column: 1,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_word_wrap() {\n // |foo␣ |\n // |bar␣ |\n // |baz |\n let text = \"foo bar \\nbaz\".as_bytes();\n\n // Does hitting a logical target wrap the visual position along with the word?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6);\n let cursor = cfg.goto_logical(Point { x: 5, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 5,\n logical_pos: Point { x: 5, y: 0 },\n visual_pos: Point { x: 1, y: 1 },\n column: 5,\n wrap_opp: true,\n }\n );\n\n // Does hitting the visual target within a word reset the hit back to the end of the visual line?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6);\n let cursor = cfg.goto_visual(Point { x: CoordType::MAX, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n // Does hitting the same target but with a non-zero starting position result in the same outcome?\n let mut cfg = MeasurementConfig::new(&text).with_word_wrap_column(6).with_cursor(Cursor {\n offset: 1,\n logical_pos: Point { x: 1, y: 0 },\n visual_pos: Point { x: 1, y: 0 },\n column: 1,\n wrap_opp: false,\n });\n let cursor = cfg.goto_visual(Point { x: 5, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 5, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 4, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 0, y: 2 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 9,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 2 },\n column: 0,\n wrap_opp: false,\n }\n );\n\n let cursor = cfg.goto_visual(Point { x: 5, y: 2 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 12,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 2 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_tabs() {\n let text = \"a\\tb\\tc\".as_bytes();\n let cursor =\n MeasurementConfig::new(&text).with_tab_size(4).goto_visual(Point { x: 4, y: 0 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 2,\n logical_pos: Point { x: 2, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_measure_forward_chunk_boundaries() {\n let chunks = [\n \"Hello\".as_bytes(),\n \"\\u{1F469}\\u{1F3FB}\".as_bytes(), // 8 bytes, 2 columns\n \"World\".as_bytes(),\n ];\n let doc = ChunkedDoc(&chunks);\n let cursor = MeasurementConfig::new(&doc).goto_visual(Point { x: 5 + 2 + 3, y: 0 });\n assert_eq!(cursor.offset, 5 + 8 + 3);\n assert_eq!(cursor.logical_pos, Point { x: 5 + 1 + 3, y: 0 });\n }\n\n #[test]\n fn test_exact_wrap() {\n // |foo_ |\n // |bar. |\n // |abc |\n let chunks = [\"foo \".as_bytes(), \"bar\".as_bytes(), \".\\n\".as_bytes(), \"abc\".as_bytes()];\n let doc = ChunkedDoc(&chunks);\n let mut cfg = MeasurementConfig::new(&doc).with_word_wrap_column(7);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: 7, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n }\n );\n\n let beg1 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 4, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n\n let beg2 = cfg.goto_visual(Point { x: 0, y: 2 });\n assert_eq!(\n beg2,\n Cursor {\n offset: 9,\n logical_pos: Point { x: 0, y: 1 },\n visual_pos: Point { x: 0, y: 2 },\n column: 0,\n wrap_opp: false,\n }\n );\n\n let end2 = cfg.goto_visual(Point { x: max, y: 2 });\n assert_eq!(\n end2,\n Cursor {\n offset: 12,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 2 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_force_wrap() {\n // |//_ |\n // |aaaaaaaa|\n // |aaaa |\n let bytes = \"// aaaaaaaaaaaa\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n let max = CoordType::MAX;\n\n // At the end of \"// \" there should be a wrap.\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 3, y: 0 },\n column: 3,\n wrap_opp: true,\n }\n );\n\n // Test if the ambiguous visual position at the wrap location doesn't change the offset.\n let beg0 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 3,\n wrap_opp: false,\n }\n );\n\n // Test if navigating inside the wrapped line doesn't cause further wrapping.\n //\n // This step of the test is important, as it ensures that the following force-wrap works,\n // even if 1 of the 8 \"a\"s was already processed.\n let beg0_off1 = cfg.goto_logical(Point { x: 4, y: 0 });\n assert_eq!(\n beg0_off1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 1, y: 1 },\n column: 4,\n wrap_opp: false,\n }\n );\n\n // Test if the force-wrap applies at the end of the first 8 \"a\"s.\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 11,\n logical_pos: Point { x: 11, y: 0 },\n visual_pos: Point { x: 8, y: 1 },\n column: 11,\n wrap_opp: true,\n }\n );\n\n // Test if the remaining 4 \"a\"s are properly laid-out.\n let end2 = cfg.goto_visual(Point { x: max, y: 2 });\n assert_eq!(\n end2,\n Cursor {\n offset: 15,\n logical_pos: Point { x: 15, y: 0 },\n visual_pos: Point { x: 4, y: 2 },\n column: 15,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_force_wrap_wide() {\n // These Yijing Hexagram Symbols form no word wrap opportunities.\n let text = \"䷀䷁䷂䷃䷄䷅䷆䷇䷈䷉\";\n let expected = [\"䷀䷁\", \"䷂䷃\", \"䷄䷅\", \"䷆䷇\", \"䷈䷉\"];\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(5);\n\n for (y, &expected) in expected.iter().enumerate() {\n let y = y as CoordType;\n // In order for `goto_visual()` to hit column 0 after a word wrap,\n // it MUST be able to go back by 1 grapheme, which is what this tests.\n let beg = cfg.goto_visual(Point { x: 0, y });\n let end = cfg.goto_visual(Point { x: 5, y });\n let actual = &text[beg.offset..end.offset];\n assert_eq!(actual, expected);\n }\n }\n\n // Similar to the `test_force_wrap` test, but here we vertically descend\n // down the document without ever touching the first or last column.\n // I found that this finds curious bugs at times.\n #[test]\n fn test_force_wrap_column() {\n // |//_ |\n // |aaaaaaaa|\n // |aaaa |\n let bytes = \"// aaaaaaaaaaaa\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n\n // At the end of \"// \" there should be a wrap.\n let end0 = cfg.goto_visual(Point { x: CoordType::MAX, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 3,\n logical_pos: Point { x: 3, y: 0 },\n visual_pos: Point { x: 3, y: 0 },\n column: 3,\n wrap_opp: true,\n }\n );\n\n let mid1 = cfg.goto_visual(Point { x: end0.visual_pos.x, y: 1 });\n assert_eq!(\n mid1,\n Cursor {\n offset: 6,\n logical_pos: Point { x: 6, y: 0 },\n visual_pos: Point { x: 3, y: 1 },\n column: 6,\n wrap_opp: false,\n }\n );\n\n let mid2 = cfg.goto_visual(Point { x: end0.visual_pos.x, y: 2 });\n assert_eq!(\n mid2,\n Cursor {\n offset: 14,\n logical_pos: Point { x: 14, y: 0 },\n visual_pos: Point { x: 3, y: 2 },\n column: 14,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_any_wrap() {\n // |//_-----|\n // |------- |\n let bytes = \"// ------------\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 8, y: 0 },\n column: 8,\n wrap_opp: true,\n }\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 15,\n logical_pos: Point { x: 15, y: 0 },\n visual_pos: Point { x: 7, y: 1 },\n column: 15,\n wrap_opp: true,\n }\n );\n }\n\n #[test]\n fn test_any_wrap_wide() {\n // These Japanese characters form word wrap opportunity between each character.\n let text = \"零一二三四五六七八九\";\n let expected = [\"零一\", \"二三\", \"四五\", \"六七\", \"八九\"];\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(5);\n\n for (y, &expected) in expected.iter().enumerate() {\n let y = y as CoordType;\n // In order for `goto_visual()` to hit column 0 after a word wrap,\n // it MUST be able to go back by 1 grapheme, which is what this tests.\n let beg = cfg.goto_visual(Point { x: 0, y });\n let end = cfg.goto_visual(Point { x: 5, y });\n let actual = &text[beg.offset..end.offset];\n assert_eq!(actual, expected);\n }\n }\n\n #[test]\n fn test_wrap_tab() {\n // |foo_ | <- 1 space\n // |____b | <- 1 tab, 1 space\n let text = \"foo \\t b\";\n let bytes = text.as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(8).with_tab_size(4);\n let max = CoordType::MAX;\n\n let end0 = cfg.goto_visual(Point { x: max, y: 0 });\n assert_eq!(\n end0,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 4, y: 0 },\n column: 4,\n wrap_opp: true,\n },\n );\n\n let beg1 = cfg.goto_visual(Point { x: 0, y: 1 });\n assert_eq!(\n beg1,\n Cursor {\n offset: 4,\n logical_pos: Point { x: 4, y: 0 },\n visual_pos: Point { x: 0, y: 1 },\n column: 4,\n wrap_opp: false,\n },\n );\n\n let end1 = cfg.goto_visual(Point { x: max, y: 1 });\n assert_eq!(\n end1,\n Cursor {\n offset: 7,\n logical_pos: Point { x: 7, y: 0 },\n visual_pos: Point { x: 6, y: 1 },\n column: 10,\n wrap_opp: true,\n },\n );\n }\n\n #[test]\n fn test_crlf() {\n let text = \"a\\r\\nbcd\\r\\ne\".as_bytes();\n let cursor = MeasurementConfig::new(&text).goto_visual(Point { x: CoordType::MAX, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 6,\n logical_pos: Point { x: 3, y: 1 },\n visual_pos: Point { x: 3, y: 1 },\n column: 3,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_wrapped_cursor_can_seek_backward() {\n let bytes = \"hello world\".as_bytes();\n let mut cfg = MeasurementConfig::new(&bytes).with_word_wrap_column(10);\n\n // When the word wrap at column 10 hits, the cursor will be at the end of the word \"world\" (between l and d).\n // This tests if the algorithm is capable of going back to the start of the word and find the actual target.\n let cursor = cfg.goto_visual(Point { x: 2, y: 1 });\n assert_eq!(\n cursor,\n Cursor {\n offset: 8,\n logical_pos: Point { x: 8, y: 0 },\n visual_pos: Point { x: 2, y: 1 },\n column: 8,\n wrap_opp: false,\n }\n );\n }\n\n #[test]\n fn test_strip_newline() {\n assert_eq!(strip_newline(b\"hello\\n\"), b\"hello\");\n assert_eq!(strip_newline(b\"hello\\r\\n\"), b\"hello\");\n assert_eq!(strip_newline(b\"hello\"), b\"hello\");\n }\n}\n"], ["/edit/src/helpers.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Random assortment of helpers I didn't know where to put.\n\nuse std::alloc::Allocator;\nuse std::cmp::Ordering;\nuse std::io::Read;\nuse std::mem::{self, MaybeUninit};\nuse std::ops::{Bound, Range, RangeBounds};\nuse std::{fmt, ptr, slice, str};\n\nuse crate::apperr;\n\npub const KILO: usize = 1000;\npub const MEGA: usize = 1000 * 1000;\npub const GIGA: usize = 1000 * 1000 * 1000;\n\npub const KIBI: usize = 1024;\npub const MEBI: usize = 1024 * 1024;\npub const GIBI: usize = 1024 * 1024 * 1024;\n\npub struct MetricFormatter(pub T);\n\nimpl fmt::Display for MetricFormatter {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let mut value = self.0;\n let mut suffix = \"B\";\n if value >= GIGA {\n value /= GIGA;\n suffix = \"GB\";\n } else if value >= MEGA {\n value /= MEGA;\n suffix = \"MB\";\n } else if value >= KILO {\n value /= KILO;\n suffix = \"kB\";\n }\n write!(f, \"{value}{suffix}\")\n }\n}\n\n/// A viewport coordinate type used throughout the application.\npub type CoordType = isize;\n\n/// To avoid overflow issues because you're adding two [`CoordType::MAX`]\n/// values together, you can use [`COORD_TYPE_SAFE_MAX`] instead.\n///\n/// It equates to half the bits contained in [`CoordType`], which\n/// for instance is 32767 (0x7FFF) when [`CoordType`] is a [`i32`].\npub const COORD_TYPE_SAFE_MAX: CoordType = (1 << (CoordType::BITS / 2 - 1)) - 1;\n\n/// A 2D point. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Point {\n pub x: CoordType,\n pub y: CoordType,\n}\n\nimpl Point {\n pub const MIN: Self = Self { x: CoordType::MIN, y: CoordType::MIN };\n pub const MAX: Self = Self { x: CoordType::MAX, y: CoordType::MAX };\n}\n\nimpl PartialOrd for Point {\n fn partial_cmp(&self, other: &Self) -> Option {\n Some(self.cmp(other))\n }\n}\n\nimpl Ord for Point {\n fn cmp(&self, other: &Self) -> Ordering {\n self.y.cmp(&other.y).then(self.x.cmp(&other.x))\n }\n}\n\n/// A 2D size. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Size {\n pub width: CoordType,\n pub height: CoordType,\n}\n\nimpl Size {\n pub fn as_rect(&self) -> Rect {\n Rect { left: 0, top: 0, right: self.width, bottom: self.height }\n }\n}\n\n/// A 2D rectangle. Uses [`CoordType`].\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]\npub struct Rect {\n pub left: CoordType,\n pub top: CoordType,\n pub right: CoordType,\n pub bottom: CoordType,\n}\n\nimpl Rect {\n /// Mimics CSS's `padding` property where `padding: a` is `a a a a`.\n pub fn one(value: CoordType) -> Self {\n Self { left: value, top: value, right: value, bottom: value }\n }\n\n /// Mimics CSS's `padding` property where `padding: a b` is `a b a b`,\n /// and `a` is top/bottom and `b` is left/right.\n pub fn two(top_bottom: CoordType, left_right: CoordType) -> Self {\n Self { left: left_right, top: top_bottom, right: left_right, bottom: top_bottom }\n }\n\n /// Mimics CSS's `padding` property where `padding: a b c` is `a b c b`,\n /// and `a` is top, `b` is left/right, and `c` is bottom.\n pub fn three(top: CoordType, left_right: CoordType, bottom: CoordType) -> Self {\n Self { left: left_right, top, right: left_right, bottom }\n }\n\n /// Is the rectangle empty?\n pub fn is_empty(&self) -> bool {\n self.left >= self.right || self.top >= self.bottom\n }\n\n /// Width of the rectangle.\n pub fn width(&self) -> CoordType {\n self.right - self.left\n }\n\n /// Height of the rectangle.\n pub fn height(&self) -> CoordType {\n self.bottom - self.top\n }\n\n /// Check if it contains a point.\n pub fn contains(&self, point: Point) -> bool {\n point.x >= self.left && point.x < self.right && point.y >= self.top && point.y < self.bottom\n }\n\n /// Intersect two rectangles.\n pub fn intersect(&self, rhs: Self) -> Self {\n let l = self.left.max(rhs.left);\n let t = self.top.max(rhs.top);\n let r = self.right.min(rhs.right);\n let b = self.bottom.min(rhs.bottom);\n\n // Ensure that the size is non-negative. This avoids bugs,\n // because some height/width is negative all of a sudden.\n let r = l.max(r);\n let b = t.max(b);\n\n Self { left: l, top: t, right: r, bottom: b }\n }\n}\n\n/// [`std::cmp::minmax`] is unstable, as per usual.\npub fn minmax(v1: T, v2: T) -> [T; 2]\nwhere\n T: Ord,\n{\n if v2 < v1 { [v2, v1] } else { [v1, v2] }\n}\n\n#[inline(always)]\n#[allow(clippy::ptr_eq)]\nfn opt_ptr(a: Option<&T>) -> *const T {\n unsafe { mem::transmute(a) }\n}\n\n/// Surprisingly, there's no way in Rust to do a `ptr::eq` on `Option<&T>`.\n/// Uses `unsafe` so that the debug performance isn't too bad.\n#[inline(always)]\n#[allow(clippy::ptr_eq)]\npub fn opt_ptr_eq(a: Option<&T>, b: Option<&T>) -> bool {\n opt_ptr(a) == opt_ptr(b)\n}\n\n/// Creates a `&str` from a pointer and a length.\n/// Exists, because `std::str::from_raw_parts` is unstable, par for the course.\n///\n/// # Safety\n///\n/// The given data must be valid UTF-8.\n/// The given data must outlive the returned reference.\n#[inline]\n#[must_use]\npub const unsafe fn str_from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str {\n unsafe { str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) }\n}\n\n/// [`<[T]>::copy_from_slice`] panics if the two slices have different lengths.\n/// This one just returns the copied amount.\npub fn slice_copy_safe(dst: &mut [T], src: &[T]) -> usize {\n let len = src.len().min(dst.len());\n unsafe { ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len) };\n len\n}\n\n/// [`Vec::splice`] results in really bad assembly.\n/// This doesn't. Don't use [`Vec::splice`].\npub trait ReplaceRange {\n fn replace_range>(&mut self, range: R, src: &[T]);\n}\n\nimpl ReplaceRange for Vec {\n fn replace_range>(&mut self, range: R, src: &[T]) {\n let start = match range.start_bound() {\n Bound::Included(&start) => start,\n Bound::Excluded(start) => start + 1,\n Bound::Unbounded => 0,\n };\n let end = match range.end_bound() {\n Bound::Included(end) => end + 1,\n Bound::Excluded(&end) => end,\n Bound::Unbounded => usize::MAX,\n };\n vec_replace_impl(self, start..end, src);\n }\n}\n\nfn vec_replace_impl(dst: &mut Vec, range: Range, src: &[T]) {\n unsafe {\n let dst_len = dst.len();\n let src_len = src.len();\n let off = range.start.min(dst_len);\n let del_len = range.end.saturating_sub(off).min(dst_len - off);\n\n if del_len == 0 && src_len == 0 {\n return; // nothing to do\n }\n\n let tail_len = dst_len - off - del_len;\n let new_len = dst_len - del_len + src_len;\n\n if src_len > del_len {\n dst.reserve(src_len - del_len);\n }\n\n // NOTE: drop_in_place() is not needed here, because T is constrained to Copy.\n\n // SAFETY: as_mut_ptr() must called after reserve() to ensure that the pointer is valid.\n let ptr = dst.as_mut_ptr().add(off);\n\n // Shift the tail.\n if tail_len > 0 && src_len != del_len {\n ptr::copy(ptr.add(del_len), ptr.add(src_len), tail_len);\n }\n\n // Copy in the replacement.\n ptr::copy_nonoverlapping(src.as_ptr(), ptr, src_len);\n dst.set_len(new_len);\n }\n}\n\n/// [`Read`] but with [`MaybeUninit`] buffers.\npub fn file_read_uninit(\n file: &mut T,\n buf: &mut [MaybeUninit],\n) -> apperr::Result {\n unsafe {\n let buf_slice = slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, buf.len());\n let n = file.read(buf_slice)?;\n Ok(n)\n }\n}\n\n/// Turns a [`&[u8]`] into a [`&[MaybeUninit]`].\n#[inline(always)]\npub const fn slice_as_uninit_ref(slice: &[T]) -> &[MaybeUninit] {\n unsafe { slice::from_raw_parts(slice.as_ptr() as *const MaybeUninit, slice.len()) }\n}\n\n/// Turns a [`&mut [T]`] into a [`&mut [MaybeUninit]`].\n#[inline(always)]\npub const fn slice_as_uninit_mut(slice: &mut [T]) -> &mut [MaybeUninit] {\n unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut MaybeUninit, slice.len()) }\n}\n\n/// Helpers for ASCII string comparisons.\npub trait AsciiStringHelpers {\n /// Tests if a string starts with a given ASCII prefix.\n ///\n /// This function name really is a mouthful, but it's a combination\n /// of [`str::starts_with`] and [`str::eq_ignore_ascii_case`].\n fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool;\n}\n\nimpl AsciiStringHelpers for str {\n fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool {\n // Casting to bytes first ensures we skip any UTF8 boundary checks.\n // Since the comparison is ASCII, we don't need to worry about that.\n let s = self.as_bytes();\n let p = prefix.as_bytes();\n p.len() <= s.len() && s[..p.len()].eq_ignore_ascii_case(p)\n }\n}\n"], ["/edit/src/unicode/utf8.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::{hint, iter};\n\n/// An iterator over UTF-8 encoded characters.\n///\n/// This differs from [`std::str::Chars`] in that it works on unsanitized\n/// byte slices and transparently replaces invalid UTF-8 sequences with U+FFFD.\n///\n/// This follows ICU's bitmask approach for `U8_NEXT_OR_FFFD` relatively\n/// closely. This is important for compatibility, because it implements the\n/// WHATWG recommendation for UTF8 error recovery. It's also helpful, because\n/// the excellent folks at ICU have probably spent a lot of time optimizing it.\n#[derive(Clone, Copy)]\npub struct Utf8Chars<'a> {\n source: &'a [u8],\n offset: usize,\n}\n\nimpl<'a> Utf8Chars<'a> {\n /// Creates a new `Utf8Chars` iterator starting at the given `offset`.\n pub fn new(source: &'a [u8], offset: usize) -> Self {\n Self { source, offset }\n }\n\n /// Returns the byte slice this iterator was created with.\n pub fn source(&self) -> &'a [u8] {\n self.source\n }\n\n /// Checks if the source is empty.\n pub fn is_empty(&self) -> bool {\n self.source.is_empty()\n }\n\n /// Returns the length of the source.\n pub fn len(&self) -> usize {\n self.source.len()\n }\n\n /// Returns the current offset in the byte slice.\n ///\n /// This will be past the last returned character.\n pub fn offset(&self) -> usize {\n self.offset\n }\n\n /// Sets the offset to continue iterating from.\n pub fn seek(&mut self, offset: usize) {\n self.offset = offset;\n }\n\n /// Returns true if `next` will return another character.\n pub fn has_next(&self) -> bool {\n self.offset < self.source.len()\n }\n\n // I found that on mixed 50/50 English/Non-English text,\n // performance actually suffers when this gets inlined.\n #[cold]\n fn next_slow(&mut self, c: u8) -> char {\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n\n let mut cp = c as u32;\n\n if cp < 0xE0 {\n // UTF8-2 = %xC2-DF UTF8-tail\n\n if cp < 0xC2 {\n return Self::fffd();\n }\n\n // The lead byte is 110xxxxx\n // -> Strip off the 110 prefix\n cp &= !0xE0;\n } else if cp < 0xF0 {\n // UTF8-3 =\n // %xE0 %xA0-BF UTF8-tail\n // %xE1-EC UTF8-tail UTF8-tail\n // %xED %x80-9F UTF8-tail\n // %xEE-EF UTF8-tail UTF8-tail\n\n // This is a pretty neat approach seen in ICU4C, because it's a 1:1 translation of the RFC.\n // I don't understand why others don't do the same thing. It's rather performant.\n const BITS_80_9F: u8 = 1 << 0b100; // 0x80-9F, aka 0b100xxxxx\n const BITS_A0_BF: u8 = 1 << 0b101; // 0xA0-BF, aka 0b101xxxxx\n const BITS_BOTH: u8 = BITS_80_9F | BITS_A0_BF;\n const LEAD_TRAIL1_BITS: [u8; 16] = [\n // v-- lead byte\n BITS_A0_BF, // 0xE0\n BITS_BOTH, // 0xE1\n BITS_BOTH, // 0xE2\n BITS_BOTH, // 0xE3\n BITS_BOTH, // 0xE4\n BITS_BOTH, // 0xE5\n BITS_BOTH, // 0xE6\n BITS_BOTH, // 0xE7\n BITS_BOTH, // 0xE8\n BITS_BOTH, // 0xE9\n BITS_BOTH, // 0xEA\n BITS_BOTH, // 0xEB\n BITS_BOTH, // 0xEC\n BITS_80_9F, // 0xED\n BITS_BOTH, // 0xEE\n BITS_BOTH, // 0xEF\n ];\n\n // The lead byte is 1110xxxx\n // -> Strip off the 1110 prefix\n cp &= !0xF0;\n\n let t = self.source[self.offset] as u32;\n if LEAD_TRAIL1_BITS[cp as usize] & (1 << (t >> 5)) == 0 {\n return Self::fffd();\n }\n cp = (cp << 6) | (t & 0x3F);\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n } else {\n // UTF8-4 =\n // %xF0 %x90-BF UTF8-tail UTF8-tail\n // %xF1-F3 UTF8-tail UTF8-tail UTF8-tail\n // %xF4 %x80-8F UTF8-tail UTF8-tail\n\n // This is similar to the above, but with the indices flipped:\n // The trail byte is the index and the lead byte mask is the value.\n // This is because the split at 0x90 requires more bits than fit into an u8.\n const TRAIL1_LEAD_BITS: [u8; 16] = [\n // --------- 0xF4 lead\n // | ...\n // | +---- 0xF0 lead\n // v v\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, // trail bytes:\n 0b_00000, //\n 0b_11110, // 0x80-8F -> 0x80-8F can be preceded by 0xF1-F4\n 0b_01111, // 0x90-9F -v\n 0b_01111, // 0xA0-AF -> 0x90-BF can be preceded by 0xF0-F3\n 0b_01111, // 0xB0-BF -^\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n 0b_00000, //\n ];\n\n // The lead byte *may* be 11110xxx, but could also be e.g. 11111xxx.\n // -> Only strip off the 1111 prefix\n cp &= !0xF0;\n\n // Now we can verify if it's actually <= 0xF4.\n // Curiously, this if condition does a lot of heavy lifting for\n // performance (+13%). I think it's just a coincidence though.\n if cp > 4 {\n return Self::fffd();\n }\n\n let t = self.source[self.offset] as u32;\n if TRAIL1_LEAD_BITS[(t >> 4) as usize] & (1 << cp) == 0 {\n return Self::fffd();\n }\n cp = (cp << 6) | (t & 0x3F);\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n\n // UTF8-tail = %x80-BF\n let t = (self.source[self.offset] as u32).wrapping_sub(0x80);\n if t > 0x3F {\n return Self::fffd();\n }\n cp = (cp << 6) | t;\n\n self.offset += 1;\n if self.offset >= self.source.len() {\n return Self::fffd();\n }\n }\n\n // SAFETY: All branches above check for `if self.offset >= self.source.len()`\n // one way or another. This is here because the compiler doesn't get it otherwise.\n unsafe { hint::assert_unchecked(self.offset < self.source.len()) };\n\n // UTF8-tail = %x80-BF\n let t = (self.source[self.offset] as u32).wrapping_sub(0x80);\n if t > 0x3F {\n return Self::fffd();\n }\n cp = (cp << 6) | t;\n\n self.offset += 1;\n\n // SAFETY: If `cp` wasn't a valid codepoint, we already returned U+FFFD above.\n unsafe { char::from_u32_unchecked(cp) }\n }\n\n // This simultaneously serves as a `cold_path` marker.\n // It improves performance by ~5% and reduces code size.\n #[cold]\n #[inline(always)]\n fn fffd() -> char {\n '\\u{FFFD}'\n }\n}\n\nimpl Iterator for Utf8Chars<'_> {\n type Item = char;\n\n #[inline]\n fn next(&mut self) -> Option {\n if self.offset >= self.source.len() {\n return None;\n }\n\n let c = self.source[self.offset];\n self.offset += 1;\n\n // Fast-passing ASCII allows this function to be trivially inlined everywhere,\n // as the full decoder is a little too large for that.\n if (c & 0x80) == 0 {\n // UTF8-1 = %x00-7F\n Some(c as char)\n } else {\n // Weirdly enough, adding a hint here to assert that `next_slow`\n // only returns codepoints >= 0x80 makes `ucd` ~5% slower.\n Some(self.next_slow(c))\n }\n }\n\n #[inline]\n fn size_hint(&self) -> (usize, Option) {\n // Lower bound: All remaining bytes are 4-byte sequences.\n // Upper bound: All remaining bytes are ASCII.\n let remaining = self.source.len() - self.offset;\n (remaining / 4, Some(remaining))\n }\n}\n\nimpl iter::FusedIterator for Utf8Chars<'_> {}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_broken_utf8() {\n let source = [b'a', 0xED, 0xA0, 0x80, b'b'];\n let mut chars = Utf8Chars::new(&source, 0);\n let mut offset = 0;\n for chunk in source.utf8_chunks() {\n for ch in chunk.valid().chars() {\n offset += ch.len_utf8();\n assert_eq!(chars.next(), Some(ch));\n assert_eq!(chars.offset(), offset);\n }\n if !chunk.invalid().is_empty() {\n offset += chunk.invalid().len();\n assert_eq!(chars.next(), Some('\\u{FFFD}'));\n assert_eq!(chars.offset(), offset);\n }\n }\n }\n}\n"], ["/edit/src/buffer/gap_buffer.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Range;\nuse std::ptr::{self, NonNull};\nuse std::slice;\n\nuse crate::document::{ReadableDocument, WriteableDocument};\nuse crate::helpers::*;\nuse crate::{apperr, sys};\n\n#[cfg(target_pointer_width = \"32\")]\nconst LARGE_CAPACITY: usize = 128 * MEBI;\n#[cfg(target_pointer_width = \"64\")]\nconst LARGE_CAPACITY: usize = 4 * GIBI;\nconst LARGE_ALLOC_CHUNK: usize = 64 * KIBI;\nconst LARGE_GAP_CHUNK: usize = 4 * KIBI;\n\nconst SMALL_CAPACITY: usize = 128 * KIBI;\nconst SMALL_ALLOC_CHUNK: usize = 256;\nconst SMALL_GAP_CHUNK: usize = 16;\n\n// TODO: Instead of having a specialization for small buffers here,\n// tui.rs could also just keep a MRU set of large buffers around.\nenum BackingBuffer {\n VirtualMemory(NonNull, usize),\n Vec(Vec),\n}\n\nimpl Drop for BackingBuffer {\n fn drop(&mut self) {\n unsafe {\n if let Self::VirtualMemory(ptr, reserve) = *self {\n sys::virtual_release(ptr, reserve);\n }\n }\n }\n}\n\n/// Most people know how `Vec` works: It has some spare capacity at the end,\n/// so that pushing into it doesn't reallocate every single time. A gap buffer\n/// is the same thing, but the spare capacity can be anywhere in the buffer.\n/// This variant is optimized for large buffers and uses virtual memory.\npub struct GapBuffer {\n /// Pointer to the buffer.\n text: NonNull,\n /// Maximum size of the buffer, including gap.\n reserve: usize,\n /// Size of the buffer, including gap.\n commit: usize,\n /// Length of the stored text, NOT including gap.\n text_length: usize,\n /// Gap offset.\n gap_off: usize,\n /// Gap length.\n gap_len: usize,\n /// Increments every time the buffer is modified.\n generation: u32,\n /// If `Vec(..)`, the buffer is optimized for small amounts of text\n /// and uses the standard heap. Otherwise, it uses virtual memory.\n buffer: BackingBuffer,\n}\n\nimpl GapBuffer {\n pub fn new(small: bool) -> apperr::Result {\n let reserve;\n let buffer;\n let text;\n\n if small {\n reserve = SMALL_CAPACITY;\n text = NonNull::dangling();\n buffer = BackingBuffer::Vec(Vec::new());\n } else {\n reserve = LARGE_CAPACITY;\n text = unsafe { sys::virtual_reserve(reserve)? };\n buffer = BackingBuffer::VirtualMemory(text, reserve);\n }\n\n Ok(Self {\n text,\n reserve,\n commit: 0,\n text_length: 0,\n gap_off: 0,\n gap_len: 0,\n generation: 0,\n buffer,\n })\n }\n\n #[allow(clippy::len_without_is_empty)]\n pub fn len(&self) -> usize {\n self.text_length\n }\n\n pub fn generation(&self) -> u32 {\n self.generation\n }\n\n pub fn set_generation(&mut self, generation: u32) {\n self.generation = generation;\n }\n\n /// WARNING: The returned slice must not necessarily be the same length as `len` (due to OOM).\n pub fn allocate_gap(&mut self, off: usize, len: usize, delete: usize) -> &mut [u8] {\n // Sanitize parameters\n let off = off.min(self.text_length);\n let delete = delete.min(self.text_length - off);\n\n // Move the existing gap if it exists\n if off != self.gap_off {\n self.move_gap(off);\n }\n\n // Delete the text\n if delete > 0 {\n self.delete_text(delete);\n }\n\n // Enlarge the gap if needed\n if len > self.gap_len {\n self.enlarge_gap(len);\n }\n\n self.generation = self.generation.wrapping_add(1);\n unsafe { slice::from_raw_parts_mut(self.text.add(self.gap_off).as_ptr(), self.gap_len) }\n }\n\n fn move_gap(&mut self, off: usize) {\n if self.gap_len > 0 {\n //\n // v gap_off\n // left: |ABCDEFGHIJKLMN OPQRSTUVWXYZ|\n // |ABCDEFGHI JKLMNOPQRSTUVWXYZ|\n // ^ off\n // move: JKLMN\n //\n // v gap_off\n // !left: |ABCDEFGHIJKLMN OPQRSTUVWXYZ|\n // |ABCDEFGHIJKLMNOPQRS TUVWXYZ|\n // ^ off\n // move: OPQRS\n //\n let left = off < self.gap_off;\n let move_src = if left { off } else { self.gap_off + self.gap_len };\n let move_dst = if left { off + self.gap_len } else { self.gap_off };\n let move_len = if left { self.gap_off - off } else { off - self.gap_off };\n\n unsafe { self.text.add(move_src).copy_to(self.text.add(move_dst), move_len) };\n\n if cfg!(debug_assertions) {\n // Fill the moved-out bytes with 0xCD to make debugging easier.\n unsafe { self.text.add(off).write_bytes(0xCD, self.gap_len) };\n }\n }\n\n self.gap_off = off;\n }\n\n fn delete_text(&mut self, delete: usize) {\n if cfg!(debug_assertions) {\n // Fill the deleted bytes with 0xCD to make debugging easier.\n unsafe { self.text.add(self.gap_off + self.gap_len).write_bytes(0xCD, delete) };\n }\n\n self.gap_len += delete;\n self.text_length -= delete;\n }\n\n fn enlarge_gap(&mut self, len: usize) {\n let gap_chunk;\n let alloc_chunk;\n\n if matches!(self.buffer, BackingBuffer::VirtualMemory(..)) {\n gap_chunk = LARGE_GAP_CHUNK;\n alloc_chunk = LARGE_ALLOC_CHUNK;\n } else {\n gap_chunk = SMALL_GAP_CHUNK;\n alloc_chunk = SMALL_ALLOC_CHUNK;\n }\n\n let gap_len_old = self.gap_len;\n let gap_len_new = (len + gap_chunk + gap_chunk - 1) & !(gap_chunk - 1);\n\n let bytes_old = self.commit;\n let bytes_new = self.text_length + gap_len_new;\n\n if bytes_new > bytes_old {\n let bytes_new = (bytes_new + alloc_chunk - 1) & !(alloc_chunk - 1);\n\n if bytes_new > self.reserve {\n return;\n }\n\n match &mut self.buffer {\n BackingBuffer::VirtualMemory(ptr, _) => unsafe {\n if sys::virtual_commit(ptr.add(bytes_old), bytes_new - bytes_old).is_err() {\n return;\n }\n },\n BackingBuffer::Vec(v) => {\n v.resize(bytes_new, 0);\n self.text = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };\n }\n }\n\n self.commit = bytes_new;\n }\n\n let gap_beg = unsafe { self.text.add(self.gap_off) };\n unsafe {\n ptr::copy(\n gap_beg.add(gap_len_old).as_ptr(),\n gap_beg.add(gap_len_new).as_ptr(),\n self.text_length - self.gap_off,\n )\n };\n\n if cfg!(debug_assertions) {\n // Fill the moved-out bytes with 0xCD to make debugging easier.\n unsafe { gap_beg.add(gap_len_old).write_bytes(0xCD, gap_len_new - gap_len_old) };\n }\n\n self.gap_len = gap_len_new;\n }\n\n pub fn commit_gap(&mut self, len: usize) {\n assert!(len <= self.gap_len);\n self.text_length += len;\n self.gap_off += len;\n self.gap_len -= len;\n }\n\n pub fn replace(&mut self, range: Range, src: &[u8]) {\n let gap = self.allocate_gap(range.start, src.len(), range.end.saturating_sub(range.start));\n let len = slice_copy_safe(gap, src);\n self.commit_gap(len);\n }\n\n pub fn clear(&mut self) {\n self.gap_off = 0;\n self.gap_len += self.text_length;\n self.generation = self.generation.wrapping_add(1);\n self.text_length = 0;\n }\n\n pub fn extract_raw(&self, range: Range, out: &mut Vec, mut out_off: usize) {\n let end = range.end.min(self.text_length);\n let mut beg = range.start.min(end);\n out_off = out_off.min(out.len());\n\n if beg >= end {\n return;\n }\n\n out.reserve(end - beg);\n\n while beg < end {\n let chunk = self.read_forward(beg);\n let chunk = &chunk[..chunk.len().min(end - beg)];\n out.replace_range(out_off..out_off, chunk);\n beg += chunk.len();\n out_off += chunk.len();\n }\n }\n\n /// Replaces the entire buffer contents with the given `text`.\n /// The method is optimized for the case where the given `text` already matches\n /// the existing contents. Returns `true` if the buffer contents were changed.\n pub fn copy_from(&mut self, src: &dyn ReadableDocument) -> bool {\n let mut off = 0;\n\n // Find the position at which the contents change.\n loop {\n let dst_chunk = self.read_forward(off);\n let src_chunk = src.read_forward(off);\n\n let dst_len = dst_chunk.len();\n let src_len = src_chunk.len();\n let len = dst_len.min(src_len);\n let mismatch = dst_chunk[..len] != src_chunk[..len];\n\n if mismatch {\n break; // The contents differ.\n }\n if len == 0 {\n if dst_len == src_len {\n return false; // Both done simultaneously. -> Done.\n }\n break; // One of the two is shorter.\n }\n\n off += len;\n }\n\n // Update the buffer starting at `off`.\n loop {\n let chunk = src.read_forward(off);\n self.replace(off..usize::MAX, chunk);\n off += chunk.len();\n\n // No more data to copy -> Done. By checking this _after_ the replace()\n // call, we ensure that the initial `off..usize::MAX` range is deleted.\n // This fixes going from some buffer contents to being empty.\n if chunk.is_empty() {\n return true;\n }\n }\n }\n\n /// Copies the contents of the buffer into a string.\n pub fn copy_into(&self, dst: &mut dyn WriteableDocument) {\n let mut beg = 0;\n let mut off = 0;\n\n while {\n let chunk = self.read_forward(off);\n\n // The first write will be 0..usize::MAX and effectively clear() the destination.\n // Every subsequent write will be usize::MAX..usize::MAX and thus effectively append().\n dst.replace(beg..usize::MAX, chunk);\n beg = usize::MAX;\n\n off += chunk.len();\n off < self.text_length\n } {}\n }\n}\n\nimpl ReadableDocument for GapBuffer {\n fn read_forward(&self, off: usize) -> &[u8] {\n let off = off.min(self.text_length);\n let beg;\n let len;\n\n if off < self.gap_off {\n // Cursor is before the gap: We can read until the start of the gap.\n beg = off;\n len = self.gap_off - off;\n } else {\n // Cursor is after the gap: We can read until the end of the buffer.\n beg = off + self.gap_len;\n len = self.text_length - off;\n }\n\n unsafe { slice::from_raw_parts(self.text.add(beg).as_ptr(), len) }\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let off = off.min(self.text_length);\n let beg;\n let len;\n\n if off <= self.gap_off {\n // Cursor is before the gap: We can read until the beginning of the buffer.\n beg = 0;\n len = off;\n } else {\n // Cursor is after the gap: We can read until the end of the gap.\n beg = self.gap_off + self.gap_len;\n // The cursor_off doesn't account of the gap_len.\n // (This allows us to move the gap without recalculating the cursor position.)\n len = off - self.gap_off;\n }\n\n unsafe { slice::from_raw_parts(self.text.add(beg).as_ptr(), len) }\n }\n}\n"], ["/edit/src/input.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Parses VT sequences into input events.\n//!\n//! In the future this allows us to take apart the application and\n//! support input schemes that aren't VT, such as UEFI, or GUI.\n\nuse std::mem;\n\nuse crate::helpers::{CoordType, Point, Size};\nuse crate::vt;\n\n/// Represents a key/modifier combination.\n///\n/// TODO: Is this a good idea? I did it to allow typing `kbmod::CTRL | vk::A`.\n/// The reason it's an awkward u32 and not a struct is to hopefully make ABIs easier later.\n/// Of course you could just translate on the ABI boundary, but my hope is that this\n/// design lets me realize some restrictions early on that I can't foresee yet.\n#[repr(transparent)]\n#[derive(Clone, Copy, PartialEq, Eq)]\npub struct InputKey(u32);\n\nimpl InputKey {\n pub(crate) const fn new(v: u32) -> Self {\n Self(v)\n }\n\n pub(crate) const fn from_ascii(ch: char) -> Option {\n if ch == ' ' || (ch >= '0' && ch <= '9') {\n Some(Self(ch as u32))\n } else if ch >= 'a' && ch <= 'z' {\n Some(Self(ch as u32 & !0x20)) // Shift a-z to A-Z\n } else if ch >= 'A' && ch <= 'Z' {\n Some(Self(kbmod::SHIFT.0 | ch as u32))\n } else {\n None\n }\n }\n\n pub(crate) const fn value(&self) -> u32 {\n self.0\n }\n\n pub(crate) const fn key(&self) -> Self {\n Self(self.0 & 0x00FFFFFF)\n }\n\n pub(crate) const fn modifiers(&self) -> InputKeyMod {\n InputKeyMod(self.0 & 0xFF000000)\n }\n\n pub(crate) const fn modifiers_contains(&self, modifier: InputKeyMod) -> bool {\n (self.0 & modifier.0) != 0\n }\n\n pub(crate) const fn with_modifiers(&self, modifiers: InputKeyMod) -> Self {\n Self(self.0 | modifiers.0)\n }\n}\n\n/// A keyboard modifier. Ctrl/Alt/Shift.\n#[repr(transparent)]\n#[derive(Clone, Copy, PartialEq, Eq)]\npub struct InputKeyMod(u32);\n\nimpl InputKeyMod {\n const fn new(v: u32) -> Self {\n Self(v)\n }\n\n pub(crate) const fn contains(&self, modifier: Self) -> bool {\n (self.0 & modifier.0) != 0\n }\n}\n\nimpl std::ops::BitOr for InputKey {\n type Output = Self;\n\n fn bitor(self, rhs: InputKeyMod) -> Self {\n Self(self.0 | rhs.0)\n }\n}\n\nimpl std::ops::BitOr for InputKeyMod {\n type Output = InputKey;\n\n fn bitor(self, rhs: InputKey) -> InputKey {\n InputKey(self.0 | rhs.0)\n }\n}\n\nimpl std::ops::BitOrAssign for InputKeyMod {\n fn bitor_assign(&mut self, rhs: Self) {\n self.0 |= rhs.0;\n }\n}\n\n/// Keyboard keys.\n///\n/// The codes defined here match the VK_* constants on Windows.\n/// It's a convenient way to handle keyboard input, even on other platforms.\npub mod vk {\n use super::InputKey;\n\n pub const NULL: InputKey = InputKey::new('\\0' as u32);\n pub const BACK: InputKey = InputKey::new(0x08);\n pub const TAB: InputKey = InputKey::new('\\t' as u32);\n pub const RETURN: InputKey = InputKey::new('\\r' as u32);\n pub const ESCAPE: InputKey = InputKey::new(0x1B);\n pub const SPACE: InputKey = InputKey::new(' ' as u32);\n pub const PRIOR: InputKey = InputKey::new(0x21);\n pub const NEXT: InputKey = InputKey::new(0x22);\n\n pub const END: InputKey = InputKey::new(0x23);\n pub const HOME: InputKey = InputKey::new(0x24);\n\n pub const LEFT: InputKey = InputKey::new(0x25);\n pub const UP: InputKey = InputKey::new(0x26);\n pub const RIGHT: InputKey = InputKey::new(0x27);\n pub const DOWN: InputKey = InputKey::new(0x28);\n\n pub const INSERT: InputKey = InputKey::new(0x2D);\n pub const DELETE: InputKey = InputKey::new(0x2E);\n\n pub const N0: InputKey = InputKey::new('0' as u32);\n pub const N1: InputKey = InputKey::new('1' as u32);\n pub const N2: InputKey = InputKey::new('2' as u32);\n pub const N3: InputKey = InputKey::new('3' as u32);\n pub const N4: InputKey = InputKey::new('4' as u32);\n pub const N5: InputKey = InputKey::new('5' as u32);\n pub const N6: InputKey = InputKey::new('6' as u32);\n pub const N7: InputKey = InputKey::new('7' as u32);\n pub const N8: InputKey = InputKey::new('8' as u32);\n pub const N9: InputKey = InputKey::new('9' as u32);\n\n pub const A: InputKey = InputKey::new('A' as u32);\n pub const B: InputKey = InputKey::new('B' as u32);\n pub const C: InputKey = InputKey::new('C' as u32);\n pub const D: InputKey = InputKey::new('D' as u32);\n pub const E: InputKey = InputKey::new('E' as u32);\n pub const F: InputKey = InputKey::new('F' as u32);\n pub const G: InputKey = InputKey::new('G' as u32);\n pub const H: InputKey = InputKey::new('H' as u32);\n pub const I: InputKey = InputKey::new('I' as u32);\n pub const J: InputKey = InputKey::new('J' as u32);\n pub const K: InputKey = InputKey::new('K' as u32);\n pub const L: InputKey = InputKey::new('L' as u32);\n pub const M: InputKey = InputKey::new('M' as u32);\n pub const N: InputKey = InputKey::new('N' as u32);\n pub const O: InputKey = InputKey::new('O' as u32);\n pub const P: InputKey = InputKey::new('P' as u32);\n pub const Q: InputKey = InputKey::new('Q' as u32);\n pub const R: InputKey = InputKey::new('R' as u32);\n pub const S: InputKey = InputKey::new('S' as u32);\n pub const T: InputKey = InputKey::new('T' as u32);\n pub const U: InputKey = InputKey::new('U' as u32);\n pub const V: InputKey = InputKey::new('V' as u32);\n pub const W: InputKey = InputKey::new('W' as u32);\n pub const X: InputKey = InputKey::new('X' as u32);\n pub const Y: InputKey = InputKey::new('Y' as u32);\n pub const Z: InputKey = InputKey::new('Z' as u32);\n\n pub const NUMPAD0: InputKey = InputKey::new(0x60);\n pub const NUMPAD1: InputKey = InputKey::new(0x61);\n pub const NUMPAD2: InputKey = InputKey::new(0x62);\n pub const NUMPAD3: InputKey = InputKey::new(0x63);\n pub const NUMPAD4: InputKey = InputKey::new(0x64);\n pub const NUMPAD5: InputKey = InputKey::new(0x65);\n pub const NUMPAD6: InputKey = InputKey::new(0x66);\n pub const NUMPAD7: InputKey = InputKey::new(0x67);\n pub const NUMPAD8: InputKey = InputKey::new(0x68);\n pub const NUMPAD9: InputKey = InputKey::new(0x69);\n pub const MULTIPLY: InputKey = InputKey::new(0x6A);\n pub const ADD: InputKey = InputKey::new(0x6B);\n pub const SEPARATOR: InputKey = InputKey::new(0x6C);\n pub const SUBTRACT: InputKey = InputKey::new(0x6D);\n pub const DECIMAL: InputKey = InputKey::new(0x6E);\n pub const DIVIDE: InputKey = InputKey::new(0x6F);\n\n pub const F1: InputKey = InputKey::new(0x70);\n pub const F2: InputKey = InputKey::new(0x71);\n pub const F3: InputKey = InputKey::new(0x72);\n pub const F4: InputKey = InputKey::new(0x73);\n pub const F5: InputKey = InputKey::new(0x74);\n pub const F6: InputKey = InputKey::new(0x75);\n pub const F7: InputKey = InputKey::new(0x76);\n pub const F8: InputKey = InputKey::new(0x77);\n pub const F9: InputKey = InputKey::new(0x78);\n pub const F10: InputKey = InputKey::new(0x79);\n pub const F11: InputKey = InputKey::new(0x7A);\n pub const F12: InputKey = InputKey::new(0x7B);\n pub const F13: InputKey = InputKey::new(0x7C);\n pub const F14: InputKey = InputKey::new(0x7D);\n pub const F15: InputKey = InputKey::new(0x7E);\n pub const F16: InputKey = InputKey::new(0x7F);\n pub const F17: InputKey = InputKey::new(0x80);\n pub const F18: InputKey = InputKey::new(0x81);\n pub const F19: InputKey = InputKey::new(0x82);\n pub const F20: InputKey = InputKey::new(0x83);\n pub const F21: InputKey = InputKey::new(0x84);\n pub const F22: InputKey = InputKey::new(0x85);\n pub const F23: InputKey = InputKey::new(0x86);\n pub const F24: InputKey = InputKey::new(0x87);\n}\n\n/// Keyboard modifiers.\npub mod kbmod {\n use super::InputKeyMod;\n\n pub const NONE: InputKeyMod = InputKeyMod::new(0x00000000);\n pub const CTRL: InputKeyMod = InputKeyMod::new(0x01000000);\n pub const ALT: InputKeyMod = InputKeyMod::new(0x02000000);\n pub const SHIFT: InputKeyMod = InputKeyMod::new(0x04000000);\n\n pub const CTRL_ALT: InputKeyMod = InputKeyMod::new(0x03000000);\n pub const CTRL_SHIFT: InputKeyMod = InputKeyMod::new(0x05000000);\n pub const ALT_SHIFT: InputKeyMod = InputKeyMod::new(0x06000000);\n pub const CTRL_ALT_SHIFT: InputKeyMod = InputKeyMod::new(0x07000000);\n}\n\n/// Mouse input state. Up/Down, Left/Right, etc.\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]\npub enum InputMouseState {\n #[default]\n None,\n\n // These 3 carry their state between frames.\n Left,\n Middle,\n Right,\n\n // These 2 get reset to None on the next frame.\n Release,\n Scroll,\n}\n\n/// Mouse input.\n#[derive(Clone, Copy)]\npub struct InputMouse {\n /// The state of the mouse.Up/Down, Left/Right, etc.\n pub state: InputMouseState,\n /// Any keyboard modifiers that are held down.\n pub modifiers: InputKeyMod,\n /// Position of the mouse in the viewport.\n pub position: Point,\n /// Scroll delta.\n pub scroll: Point,\n}\n\n/// Primary result type of the parser.\npub enum Input<'input> {\n /// Window resize event.\n Resize(Size),\n /// Text input.\n /// Note that [`Input::Keyboard`] events can also be text.\n Text(&'input str),\n /// A clipboard paste.\n Paste(Vec),\n /// Keyboard input.\n Keyboard(InputKey),\n /// Mouse input.\n Mouse(InputMouse),\n}\n\n/// Parses VT sequences into input events.\npub struct Parser {\n bracketed_paste: bool,\n bracketed_paste_buf: Vec,\n x10_mouse_want: bool,\n x10_mouse_buf: [u8; 3],\n x10_mouse_len: usize,\n}\n\nimpl Parser {\n /// Creates a new parser that turns VT sequences into input events.\n ///\n /// Keep the instance alive for the lifetime of the input stream.\n pub fn new() -> Self {\n Self {\n bracketed_paste: false,\n bracketed_paste_buf: Vec::new(),\n x10_mouse_want: false,\n x10_mouse_buf: [0; 3],\n x10_mouse_len: 0,\n }\n }\n\n /// Takes an [`vt::Stream`] and returns a [`Stream`]\n /// that turns VT sequences into input events.\n pub fn parse<'parser, 'vt, 'input>(\n &'parser mut self,\n stream: vt::Stream<'vt, 'input>,\n ) -> Stream<'parser, 'vt, 'input> {\n Stream { parser: self, stream }\n }\n}\n\n/// An iterator that parses VT sequences into input events.\npub struct Stream<'parser, 'vt, 'input> {\n parser: &'parser mut Parser,\n stream: vt::Stream<'vt, 'input>,\n}\n\nimpl<'input> Iterator for Stream<'_, '_, 'input> {\n type Item = Input<'input>;\n\n fn next(&mut self) -> Option> {\n loop {\n if self.parser.bracketed_paste {\n return self.handle_bracketed_paste();\n }\n\n if self.parser.x10_mouse_want {\n return self.parse_x10_mouse_coordinates();\n }\n\n const KEYPAD_LUT: [u8; 8] = [\n vk::UP.value() as u8, // A\n vk::DOWN.value() as u8, // B\n vk::RIGHT.value() as u8, // C\n vk::LEFT.value() as u8, // D\n 0, // E\n vk::END.value() as u8, // F\n 0, // G\n vk::HOME.value() as u8, // H\n ];\n\n match self.stream.next()? {\n vt::Token::Text(text) => {\n return Some(Input::Text(text));\n }\n vt::Token::Ctrl(ch) => match ch {\n '\\0' | '\\t' | '\\r' => return Some(Input::Keyboard(InputKey::new(ch as u32))),\n '\\n' => return Some(Input::Keyboard(kbmod::CTRL | vk::RETURN)),\n ..='\\x1a' => {\n // Shift control code to A-Z\n let key = ch as u32 | 0x40;\n return Some(Input::Keyboard(kbmod::CTRL | InputKey::new(key)));\n }\n '\\x7f' => return Some(Input::Keyboard(vk::BACK)),\n _ => {}\n },\n vt::Token::Esc(ch) => {\n match ch {\n '\\0' => return Some(Input::Keyboard(vk::ESCAPE)),\n '\\n' => return Some(Input::Keyboard(kbmod::CTRL_ALT | vk::RETURN)),\n ' '..='~' => {\n let ch = ch as u32;\n let key = ch & !0x20; // Shift a-z to A-Z\n let modifiers =\n if (ch & 0x20) != 0 { kbmod::ALT } else { kbmod::ALT_SHIFT };\n return Some(Input::Keyboard(modifiers | InputKey::new(key)));\n }\n _ => {}\n }\n }\n vt::Token::SS3(ch) => match ch {\n 'A'..='H' => {\n let vk = KEYPAD_LUT[ch as usize - 'A' as usize];\n if vk != 0 {\n return Some(Input::Keyboard(InputKey::new(vk as u32)));\n }\n }\n 'P'..='S' => {\n let key = vk::F1.value() + ch as u32 - 'P' as u32;\n return Some(Input::Keyboard(InputKey::new(key)));\n }\n _ => {}\n },\n vt::Token::Csi(csi) => {\n match csi.final_byte {\n 'A'..='H' => {\n let vk = KEYPAD_LUT[csi.final_byte as usize - 'A' as usize];\n if vk != 0 {\n return Some(Input::Keyboard(\n InputKey::new(vk as u32) | Self::parse_modifiers(csi),\n ));\n }\n }\n 'Z' => return Some(Input::Keyboard(kbmod::SHIFT | vk::TAB)),\n '~' => {\n const LUT: [u8; 35] = [\n 0,\n vk::HOME.value() as u8, // 1\n vk::INSERT.value() as u8, // 2\n vk::DELETE.value() as u8, // 3\n vk::END.value() as u8, // 4\n vk::PRIOR.value() as u8, // 5\n vk::NEXT.value() as u8, // 6\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n vk::F5.value() as u8, // 15\n 0,\n vk::F6.value() as u8, // 17\n vk::F7.value() as u8, // 18\n vk::F8.value() as u8, // 19\n vk::F9.value() as u8, // 20\n vk::F10.value() as u8, // 21\n 0,\n vk::F11.value() as u8, // 23\n vk::F12.value() as u8, // 24\n vk::F13.value() as u8, // 25\n vk::F14.value() as u8, // 26\n 0,\n vk::F15.value() as u8, // 28\n vk::F16.value() as u8, // 29\n 0,\n vk::F17.value() as u8, // 31\n vk::F18.value() as u8, // 32\n vk::F19.value() as u8, // 33\n vk::F20.value() as u8, // 34\n ];\n const LUT_LEN: u16 = LUT.len() as u16;\n\n match csi.params[0] {\n 0..LUT_LEN => {\n let vk = LUT[csi.params[0] as usize];\n if vk != 0 {\n return Some(Input::Keyboard(\n InputKey::new(vk as u32) | Self::parse_modifiers(csi),\n ));\n }\n }\n 200 => self.parser.bracketed_paste = true,\n _ => {}\n }\n }\n 'm' | 'M' if csi.private_byte == '<' => {\n let btn = csi.params[0];\n let mut mouse = InputMouse {\n state: InputMouseState::None,\n modifiers: kbmod::NONE,\n position: Default::default(),\n scroll: Default::default(),\n };\n\n mouse.state = InputMouseState::None;\n if (btn & 0x40) != 0 {\n mouse.state = InputMouseState::Scroll;\n mouse.scroll.y += if (btn & 0x01) != 0 { 3 } else { -3 };\n } else if csi.final_byte == 'M' {\n const STATES: [InputMouseState; 4] = [\n InputMouseState::Left,\n InputMouseState::Middle,\n InputMouseState::Right,\n InputMouseState::None,\n ];\n mouse.state = STATES[(btn as usize) & 0x03];\n }\n\n mouse.modifiers = kbmod::NONE;\n mouse.modifiers |=\n if (btn & 0x04) != 0 { kbmod::SHIFT } else { kbmod::NONE };\n mouse.modifiers |=\n if (btn & 0x08) != 0 { kbmod::ALT } else { kbmod::NONE };\n mouse.modifiers |=\n if (btn & 0x10f) != 0 { kbmod::CTRL } else { kbmod::NONE };\n\n mouse.position.x = csi.params[1] as CoordType - 1;\n mouse.position.y = csi.params[2] as CoordType - 1;\n return Some(Input::Mouse(mouse));\n }\n 'M' if csi.param_count == 0 => {\n self.parser.x10_mouse_want = true;\n }\n 't' if csi.params[0] == 8 => {\n // Window Size\n let width = (csi.params[2] as CoordType).clamp(1, 32767);\n let height = (csi.params[1] as CoordType).clamp(1, 32767);\n return Some(Input::Resize(Size { width, height }));\n }\n _ => {}\n }\n }\n _ => {}\n }\n }\n }\n}\n\nimpl<'input> Stream<'_, '_, 'input> {\n /// Once we encounter the start of a bracketed paste\n /// we seek to the end of the paste in this function.\n ///\n /// A bracketed paste is basically:\n /// ```text\n /// [201~ lots of text [201~\n /// ```\n ///\n /// That in between text is then expected to be taken literally.\n /// It can be in between anything though, including other escape sequences.\n /// This is the reason why this is a separate method.\n #[cold]\n fn handle_bracketed_paste(&mut self) -> Option> {\n let beg = self.stream.offset();\n let mut end = beg;\n\n while let Some(token) = self.stream.next() {\n if let vt::Token::Csi(csi) = token\n && csi.final_byte == '~'\n && csi.params[0] == 201\n {\n self.parser.bracketed_paste = false;\n break;\n }\n end = self.stream.offset();\n }\n\n if end != beg {\n self.parser\n .bracketed_paste_buf\n .extend_from_slice(&self.stream.input().as_bytes()[beg..end]);\n }\n\n if !self.parser.bracketed_paste {\n Some(Input::Paste(mem::take(&mut self.parser.bracketed_paste_buf)))\n } else {\n None\n }\n }\n\n /// Implements the X10 mouse protocol via `CSI M CbCxCy`.\n ///\n /// You want to send numeric mouse coordinates.\n /// You have CSI sequences with numeric parameters.\n /// So, of course you put the coordinates as shifted ASCII characters after\n /// the end of the sequence. Limited coordinate range and complicated parsing!\n /// This is so puzzling to me. The existence of this function makes me unhappy.\n #[cold]\n fn parse_x10_mouse_coordinates(&mut self) -> Option> {\n self.parser.x10_mouse_len +=\n self.stream.read(&mut self.parser.x10_mouse_buf[self.parser.x10_mouse_len..]);\n if self.parser.x10_mouse_len < 3 {\n return None;\n }\n\n let button = self.parser.x10_mouse_buf[0] & 0b11;\n let modifier = self.parser.x10_mouse_buf[0] & 0b11100;\n let x = self.parser.x10_mouse_buf[1] as CoordType - 0x21;\n let y = self.parser.x10_mouse_buf[2] as CoordType - 0x21;\n let action = match button {\n 0 => InputMouseState::Left,\n 1 => InputMouseState::Middle,\n 2 => InputMouseState::Right,\n _ => InputMouseState::None,\n };\n let modifiers = match modifier {\n 4 => kbmod::SHIFT,\n 8 => kbmod::ALT,\n 16 => kbmod::CTRL,\n _ => kbmod::NONE,\n };\n\n self.parser.x10_mouse_want = false;\n self.parser.x10_mouse_len = 0;\n\n Some(Input::Mouse(InputMouse {\n state: action,\n modifiers,\n position: Point { x, y },\n scroll: Default::default(),\n }))\n }\n\n fn parse_modifiers(csi: &vt::Csi) -> InputKeyMod {\n let mut modifiers = kbmod::NONE;\n let p1 = csi.params[1].saturating_sub(1);\n if (p1 & 0x01) != 0 {\n modifiers |= kbmod::SHIFT;\n }\n if (p1 & 0x02) != 0 {\n modifiers |= kbmod::ALT;\n }\n if (p1 & 0x04) != 0 {\n modifiers |= kbmod::CTRL;\n }\n modifiers\n }\n}\n"], ["/edit/src/vt.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Our VT parser.\n\nuse std::time;\n\nuse crate::simd::memchr2;\nuse crate::unicode::Utf8Chars;\n\n/// The parser produces these tokens.\npub enum Token<'parser, 'input> {\n /// A bunch of text. Doesn't contain any control characters.\n Text(&'input str),\n /// A single control character, like backspace or return.\n Ctrl(char),\n /// We encountered `ESC x` and this contains `x`.\n Esc(char),\n /// We encountered `ESC O x` and this contains `x`.\n SS3(char),\n /// A CSI sequence started with `ESC [`.\n ///\n /// They are the most common escape sequences. See [`Csi`].\n Csi(&'parser Csi),\n /// An OSC sequence started with `ESC ]`.\n ///\n /// The sequence may be split up into multiple tokens if the input\n /// is given in chunks. This is indicated by the `partial` field.\n Osc { data: &'input str, partial: bool },\n /// An DCS sequence started with `ESC P`.\n ///\n /// The sequence may be split up into multiple tokens if the input\n /// is given in chunks. This is indicated by the `partial` field.\n Dcs { data: &'input str, partial: bool },\n}\n\n/// Stores the state of the parser.\n#[derive(Clone, Copy)]\nenum State {\n Ground,\n Esc,\n Ss3,\n Csi,\n Osc,\n Dcs,\n OscEsc,\n DcsEsc,\n}\n\n/// A single CSI sequence, parsed for your convenience.\npub struct Csi {\n /// The parameters of the CSI sequence.\n pub params: [u16; 32],\n /// The number of parameters stored in [`Csi::params`].\n pub param_count: usize,\n /// The private byte, if any. `0` if none.\n ///\n /// The private byte is the first character right after the\n /// `ESC [` sequence. It is usually a `?` or `<`.\n pub private_byte: char,\n /// The final byte of the CSI sequence.\n ///\n /// This is the last character of the sequence, e.g. `m` or `H`.\n pub final_byte: char,\n}\n\npub struct Parser {\n state: State,\n // Csi is not part of State, because it allows us\n // to more quickly erase and reuse the struct.\n csi: Csi,\n}\n\nimpl Parser {\n pub fn new() -> Self {\n Self {\n state: State::Ground,\n csi: Csi { params: [0; 32], param_count: 0, private_byte: '\\0', final_byte: '\\0' },\n }\n }\n\n /// Suggests a timeout for the next call to `read()`.\n ///\n /// We need this because of the ambiguity of whether a trailing\n /// escape character in an input is starting another escape sequence or\n /// is just the result of the user literally pressing the Escape key.\n pub fn read_timeout(&mut self) -> std::time::Duration {\n match self.state {\n // 100ms is a upper ceiling for a responsive feel.\n // Realistically though, this could be much lower.\n //\n // However, there seems to be issues with OpenSSH on Windows.\n // See: https://github.com/PowerShell/Win32-OpenSSH/issues/2275\n State::Esc => time::Duration::from_millis(100),\n _ => time::Duration::MAX,\n }\n }\n\n /// Parses the given input into VT sequences.\n ///\n /// You should call this function even if your `read()`\n /// had a timeout (pass an empty string in that case).\n pub fn parse<'parser, 'input>(\n &'parser mut self,\n input: &'input str,\n ) -> Stream<'parser, 'input> {\n Stream { parser: self, input, off: 0 }\n }\n}\n\n/// An iterator that parses VT sequences into [`Token`]s.\n///\n/// Can't implement [`Iterator`], because this is a \"lending iterator\".\npub struct Stream<'parser, 'input> {\n parser: &'parser mut Parser,\n input: &'input str,\n off: usize,\n}\n\nimpl<'input> Stream<'_, 'input> {\n /// Returns the input that is being parsed.\n pub fn input(&self) -> &'input str {\n self.input\n }\n\n /// Returns the current parser offset.\n pub fn offset(&self) -> usize {\n self.off\n }\n\n /// Reads and consumes raw bytes from the input.\n pub fn read(&mut self, dst: &mut [u8]) -> usize {\n let bytes = self.input.as_bytes();\n let off = self.off.min(bytes.len());\n let len = dst.len().min(bytes.len() - off);\n dst[..len].copy_from_slice(&bytes[off..off + len]);\n self.off += len;\n len\n }\n\n fn decode_next(&mut self) -> char {\n let mut iter = Utf8Chars::new(self.input.as_bytes(), self.off);\n let c = iter.next().unwrap_or('\\0');\n self.off = iter.offset();\n c\n }\n\n /// Parses the next VT sequence from the previously given input.\n #[allow(\n clippy::should_implement_trait,\n reason = \"can't implement Iterator because this is a lending iterator\"\n )]\n pub fn next(&mut self) -> Option> {\n let input = self.input;\n let bytes = input.as_bytes();\n\n // If the previous input ended with an escape character, `read_timeout()`\n // returned `Some(..)` timeout, and if the caller did everything correctly\n // and there was indeed a timeout, we should be called with an empty\n // input. In that case we'll return the escape as its own token.\n if input.is_empty() && matches!(self.parser.state, State::Esc) {\n self.parser.state = State::Ground;\n return Some(Token::Esc('\\0'));\n }\n\n while self.off < bytes.len() {\n // TODO: The state machine can be roughly broken up into two parts:\n // * Wants to parse 1 `char` at a time: Ground, Esc, Ss3\n // These could all be unified to a single call to `decode_next()`.\n // * Wants to bulk-process bytes: Csi, Osc, Dcs\n // We should do that so the UTF8 handling is a bit more \"unified\".\n match self.parser.state {\n State::Ground => match bytes[self.off] {\n 0x1b => {\n self.parser.state = State::Esc;\n self.off += 1;\n }\n c @ (0x00..0x20 | 0x7f) => {\n self.off += 1;\n return Some(Token::Ctrl(c as char));\n }\n _ => {\n let beg = self.off;\n while {\n self.off += 1;\n self.off < bytes.len()\n && bytes[self.off] >= 0x20\n && bytes[self.off] != 0x7f\n } {}\n return Some(Token::Text(&input[beg..self.off]));\n }\n },\n State::Esc => match self.decode_next() {\n '[' => {\n self.parser.state = State::Csi;\n self.parser.csi.private_byte = '\\0';\n self.parser.csi.final_byte = '\\0';\n while self.parser.csi.param_count > 0 {\n self.parser.csi.param_count -= 1;\n self.parser.csi.params[self.parser.csi.param_count] = 0;\n }\n }\n ']' => {\n self.parser.state = State::Osc;\n }\n 'O' => {\n self.parser.state = State::Ss3;\n }\n 'P' => {\n self.parser.state = State::Dcs;\n }\n c => {\n self.parser.state = State::Ground;\n return Some(Token::Esc(c));\n }\n },\n State::Ss3 => {\n self.parser.state = State::Ground;\n return Some(Token::SS3(self.decode_next()));\n }\n State::Csi => {\n loop {\n // If we still have slots left, parse the parameter.\n if self.parser.csi.param_count < self.parser.csi.params.len() {\n let dst = &mut self.parser.csi.params[self.parser.csi.param_count];\n while self.off < bytes.len() && bytes[self.off].is_ascii_digit() {\n let add = bytes[self.off] as u32 - b'0' as u32;\n let value = *dst as u32 * 10 + add;\n *dst = value.min(u16::MAX as u32) as u16;\n self.off += 1;\n }\n } else {\n // ...otherwise, skip the parameters until we find the final byte.\n while self.off < bytes.len() && bytes[self.off].is_ascii_digit() {\n self.off += 1;\n }\n }\n\n // Encountered the end of the input before finding the final byte.\n if self.off >= bytes.len() {\n return None;\n }\n\n let c = bytes[self.off];\n self.off += 1;\n\n match c {\n 0x40..=0x7e => {\n self.parser.state = State::Ground;\n self.parser.csi.final_byte = c as char;\n if self.parser.csi.param_count != 0\n || self.parser.csi.params[0] != 0\n {\n self.parser.csi.param_count += 1;\n }\n return Some(Token::Csi(&self.parser.csi));\n }\n b';' => self.parser.csi.param_count += 1,\n b'<'..=b'?' => self.parser.csi.private_byte = c as char,\n _ => {}\n }\n }\n }\n State::Osc | State::Dcs => {\n let beg = self.off;\n let mut data;\n let mut partial;\n\n loop {\n // Find any indication for the end of the OSC/DCS sequence.\n self.off = memchr2(b'\\x07', b'\\x1b', bytes, self.off);\n\n data = &input[beg..self.off];\n partial = self.off >= bytes.len();\n\n // Encountered the end of the input before finding the terminator.\n if partial {\n break;\n }\n\n let c = bytes[self.off];\n self.off += 1;\n\n if c == 0x1b {\n // It's only a string terminator if it's followed by \\.\n // We're at the end so we're saving the state and will continue next time.\n if self.off >= bytes.len() {\n self.parser.state = match self.parser.state {\n State::Osc => State::OscEsc,\n _ => State::DcsEsc,\n };\n partial = true;\n break;\n }\n\n // False alarm: Not a string terminator.\n if bytes[self.off] != b'\\\\' {\n continue;\n }\n\n self.off += 1;\n }\n\n break;\n }\n\n let state = self.parser.state;\n if !partial {\n self.parser.state = State::Ground;\n }\n return match state {\n State::Osc => Some(Token::Osc { data, partial }),\n _ => Some(Token::Dcs { data, partial }),\n };\n }\n State::OscEsc | State::DcsEsc => {\n // We were processing an OSC/DCS sequence and the last byte was an escape character.\n // It's only a string terminator if it's followed by \\ (= \"\\x1b\\\\\").\n if bytes[self.off] == b'\\\\' {\n // It was indeed a string terminator and we can now tell the caller about it.\n let state = self.parser.state;\n\n // Consume the terminator (one byte in the previous input and this byte).\n self.parser.state = State::Ground;\n self.off += 1;\n\n return match state {\n State::OscEsc => Some(Token::Osc { data: \"\", partial: false }),\n _ => Some(Token::Dcs { data: \"\", partial: false }),\n };\n } else {\n // False alarm: Not a string terminator.\n // We'll return the escape character as a separate token.\n // Processing will continue from the current state (`bytes[self.off]`).\n self.parser.state = match self.parser.state {\n State::OscEsc => State::Osc,\n _ => State::Dcs,\n };\n return match self.parser.state {\n State::Osc => Some(Token::Osc { data: \"\\x1b\", partial: true }),\n _ => Some(Token::Dcs { data: \"\\x1b\", partial: true }),\n };\n }\n }\n }\n }\n\n None\n }\n}\n"], ["/edit/src/bin/edit/state.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::borrow::Cow;\nuse std::ffi::{OsStr, OsString};\nuse std::mem;\nuse std::path::{Path, PathBuf};\n\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::tui::*;\nuse edit::{apperr, buffer, icu, sys};\n\nuse crate::documents::DocumentManager;\nuse crate::localization::*;\n\n#[repr(transparent)]\npub struct FormatApperr(apperr::Error);\n\nimpl From for FormatApperr {\n fn from(err: apperr::Error) -> Self {\n Self(err)\n }\n}\n\nimpl std::fmt::Display for FormatApperr {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self.0 {\n apperr::APP_ICU_MISSING => f.write_str(loc(LocId::ErrorIcuMissing)),\n apperr::Error::App(code) => write!(f, \"Unknown app error code: {code}\"),\n apperr::Error::Icu(code) => icu::apperr_format(f, code),\n apperr::Error::Sys(code) => sys::apperr_format(f, code),\n }\n }\n}\n\npub struct DisplayablePathBuf {\n value: PathBuf,\n str: Cow<'static, str>,\n}\n\nimpl DisplayablePathBuf {\n #[allow(dead_code, reason = \"only used on Windows\")]\n pub fn from_string(string: String) -> Self {\n let str = Cow::Borrowed(string.as_str());\n let str = unsafe { mem::transmute::, Cow<'_, str>>(str) };\n let value = PathBuf::from(string);\n Self { value, str }\n }\n\n pub fn from_path(value: PathBuf) -> Self {\n let str = value.to_string_lossy();\n let str = unsafe { mem::transmute::, Cow<'_, str>>(str) };\n Self { value, str }\n }\n\n pub fn as_path(&self) -> &Path {\n &self.value\n }\n\n pub fn as_str(&self) -> &str {\n &self.str\n }\n\n pub fn as_bytes(&self) -> &[u8] {\n self.value.as_os_str().as_encoded_bytes()\n }\n}\n\nimpl Default for DisplayablePathBuf {\n fn default() -> Self {\n Self { value: Default::default(), str: Cow::Borrowed(\"\") }\n }\n}\n\nimpl Clone for DisplayablePathBuf {\n fn clone(&self) -> Self {\n Self::from_path(self.value.clone())\n }\n}\n\nimpl From for DisplayablePathBuf {\n fn from(s: OsString) -> Self {\n Self::from_path(PathBuf::from(s))\n }\n}\n\nimpl> From<&T> for DisplayablePathBuf {\n fn from(s: &T) -> Self {\n Self::from_path(PathBuf::from(s))\n }\n}\n\npub struct StateSearch {\n pub kind: StateSearchKind,\n pub focus: bool,\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateSearchKind {\n Hidden,\n Disabled,\n Search,\n Replace,\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateFilePicker {\n None,\n Open,\n SaveAs,\n\n SaveAsShown, // Transitioned from SaveAs\n}\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum StateEncodingChange {\n None,\n Convert,\n Reopen,\n}\n\n#[derive(Default)]\npub struct OscTitleFileStatus {\n pub filename: String,\n pub dirty: bool,\n}\n\npub struct State {\n pub menubar_color_bg: u32,\n pub menubar_color_fg: u32,\n\n pub documents: DocumentManager,\n\n // A ring buffer of the last 10 errors.\n pub error_log: [String; 10],\n pub error_log_index: usize,\n pub error_log_count: usize,\n\n pub wants_file_picker: StateFilePicker,\n pub file_picker_pending_dir: DisplayablePathBuf,\n pub file_picker_pending_dir_revision: u64, // Bumped every time `file_picker_pending_dir` changes.\n pub file_picker_pending_name: PathBuf,\n pub file_picker_entries: Option<[Vec; 3]>, // [\"..\", directories, files]\n pub file_picker_overwrite_warning: Option, // The path the warning is about.\n pub file_picker_autocomplete: Vec,\n\n pub wants_search: StateSearch,\n pub search_needle: String,\n pub search_replacement: String,\n pub search_options: buffer::SearchOptions,\n pub search_success: bool,\n\n pub wants_encoding_picker: bool,\n pub wants_encoding_change: StateEncodingChange,\n pub encoding_picker_needle: String,\n pub encoding_picker_results: Option>,\n\n pub wants_save: bool,\n pub wants_statusbar_focus: bool,\n pub wants_indentation_picker: bool,\n pub wants_go_to_file: bool,\n pub wants_about: bool,\n pub wants_close: bool,\n pub wants_exit: bool,\n pub wants_goto: bool,\n pub goto_target: String,\n pub goto_invalid: bool,\n\n pub osc_title_file_status: OscTitleFileStatus,\n pub osc_clipboard_sync: bool,\n pub osc_clipboard_always_send: bool,\n pub exit: bool,\n}\n\nimpl State {\n pub fn new() -> apperr::Result {\n Ok(Self {\n menubar_color_bg: 0,\n menubar_color_fg: 0,\n\n documents: Default::default(),\n\n error_log: [const { String::new() }; 10],\n error_log_index: 0,\n error_log_count: 0,\n\n wants_file_picker: StateFilePicker::None,\n file_picker_pending_dir: Default::default(),\n file_picker_pending_dir_revision: 0,\n file_picker_pending_name: Default::default(),\n file_picker_entries: None,\n file_picker_overwrite_warning: None,\n file_picker_autocomplete: Vec::new(),\n\n wants_search: StateSearch { kind: StateSearchKind::Hidden, focus: false },\n search_needle: Default::default(),\n search_replacement: Default::default(),\n search_options: Default::default(),\n search_success: true,\n\n wants_encoding_picker: false,\n encoding_picker_needle: Default::default(),\n encoding_picker_results: Default::default(),\n\n wants_save: false,\n wants_statusbar_focus: false,\n wants_encoding_change: StateEncodingChange::None,\n wants_indentation_picker: false,\n wants_go_to_file: false,\n wants_about: false,\n wants_close: false,\n wants_exit: false,\n wants_goto: false,\n goto_target: Default::default(),\n goto_invalid: false,\n\n osc_title_file_status: Default::default(),\n osc_clipboard_sync: false,\n osc_clipboard_always_send: false,\n exit: false,\n })\n }\n}\n\npub fn draw_add_untitled_document(ctx: &mut Context, state: &mut State) {\n if let Err(err) = state.documents.add_untitled() {\n error_log_add(ctx, state, err);\n }\n}\n\npub fn error_log_add(ctx: &mut Context, state: &mut State, err: apperr::Error) {\n let msg = format!(\"{}\", FormatApperr::from(err));\n if !msg.is_empty() {\n state.error_log[state.error_log_index] = msg;\n state.error_log_index = (state.error_log_index + 1) % state.error_log.len();\n state.error_log_count = state.error_log.len().min(state.error_log_count + 1);\n ctx.needs_rerender();\n }\n}\n\npub fn draw_error_log(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"error\", loc(LocId::ErrorDialogTitle));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n ctx.block_begin(\"content\");\n ctx.attr_padding(Rect::three(0, 2, 1));\n {\n let off = state.error_log_index + state.error_log.len() - state.error_log_count;\n\n for i in 0..state.error_log_count {\n let idx = (off + i) % state.error_log.len();\n let msg = &state.error_log[idx][..];\n\n if !msg.is_empty() {\n ctx.next_block_id_mixin(i as u64);\n ctx.label(\"error\", msg);\n ctx.attr_overflow(Overflow::TruncateTail);\n }\n }\n }\n ctx.block_end();\n\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n state.error_log_count = 0;\n }\n ctx.attr_position(Position::Center);\n ctx.inherit_focus();\n }\n if ctx.modal_end() {\n state.error_log_count = 0;\n }\n}\n"], ["/edit/src/bin/edit/draw_filepicker.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::cmp::Ordering;\nuse std::fs;\nuse std::path::{Path, PathBuf};\n\nuse edit::arena::scratch_arena;\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\nuse edit::{icu, path};\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_file_picker(ctx: &mut Context, state: &mut State) {\n // The save dialog is pre-filled with the current document filename.\n if state.wants_file_picker == StateFilePicker::SaveAs {\n state.wants_file_picker = StateFilePicker::SaveAsShown;\n\n if state.file_picker_pending_name.as_os_str().is_empty() {\n state.file_picker_pending_name =\n state.documents.active().map_or(\"Untitled.txt\", |doc| doc.filename.as_str()).into();\n }\n }\n\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n let mut doit = None;\n let mut done = false;\n\n ctx.modal_begin(\n \"file-picker\",\n if state.wants_file_picker == StateFilePicker::Open {\n loc(LocId::FileOpen)\n } else {\n loc(LocId::FileSaveAs)\n },\n );\n ctx.attr_intrinsic_size(Size { width, height });\n {\n let contains_focus = ctx.contains_focus();\n let mut activated = false;\n\n ctx.table_begin(\"path\");\n ctx.table_set_columns(&[0, COORD_TYPE_SAFE_MAX]);\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n ctx.attr_padding(Rect::two(1, 1));\n ctx.inherit_focus();\n {\n ctx.table_next_row();\n\n ctx.label(\"dir-label\", loc(LocId::SaveAsDialogPathLabel));\n ctx.label(\"dir\", state.file_picker_pending_dir.as_str());\n ctx.attr_overflow(Overflow::TruncateMiddle);\n\n ctx.table_next_row();\n ctx.inherit_focus();\n\n ctx.label(\"name-label\", loc(LocId::SaveAsDialogNameLabel));\n\n let name_changed = ctx.editline(\"name\", &mut state.file_picker_pending_name);\n ctx.inherit_focus();\n\n if ctx.contains_focus() {\n if name_changed && ctx.is_focused() {\n update_autocomplete_suggestions(state);\n }\n } else if !state.file_picker_autocomplete.is_empty() {\n state.file_picker_autocomplete.clear();\n }\n\n if !state.file_picker_autocomplete.is_empty() {\n let bg = ctx.indexed_alpha(IndexedColor::Background, 3, 4);\n let fg = ctx.contrasted(bg);\n let focus_list_beg = ctx.is_focused() && ctx.consume_shortcut(vk::DOWN);\n let focus_list_end = ctx.is_focused() && ctx.consume_shortcut(vk::UP);\n let mut autocomplete_done = ctx.consume_shortcut(vk::ESCAPE);\n\n ctx.list_begin(\"suggestions\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 0.0,\n offset_x: 0.0,\n offset_y: 1.0,\n });\n ctx.attr_border();\n ctx.attr_background_rgba(bg);\n ctx.attr_foreground_rgba(fg);\n {\n for (idx, suggestion) in state.file_picker_autocomplete.iter().enumerate() {\n let sel = ctx.list_item(false, suggestion.as_str());\n if sel != ListSelection::Unchanged {\n state.file_picker_pending_name = suggestion.as_path().into();\n }\n if sel == ListSelection::Activated {\n autocomplete_done = true;\n }\n\n let is_first = idx == 0;\n let is_last = idx == state.file_picker_autocomplete.len() - 1;\n if (is_first && focus_list_beg) || (is_last && focus_list_end) {\n ctx.list_item_steal_focus();\n } else if ctx.is_focused()\n && ((is_first && ctx.consume_shortcut(vk::UP))\n || (is_last && ctx.consume_shortcut(vk::DOWN)))\n {\n ctx.toss_focus_up();\n }\n }\n }\n ctx.list_end();\n\n // If the user typed something, we want to put focus back into the editline.\n // TODO: The input should be processed by the editline and not simply get swallowed.\n if ctx.keyboard_input().is_some() {\n ctx.set_input_consumed();\n autocomplete_done = true;\n }\n\n if autocomplete_done {\n state.file_picker_autocomplete.clear();\n }\n }\n\n if ctx.is_focused() && ctx.consume_shortcut(vk::RETURN) {\n activated = true;\n }\n }\n ctx.table_end();\n\n if state.file_picker_entries.is_none() {\n draw_dialog_saveas_refresh_files(state);\n }\n\n ctx.scrollarea_begin(\n \"directory\",\n Size {\n width: 0,\n // -1 for the label (top)\n // -1 for the label (bottom)\n // -1 for the editline (bottom)\n height: height - 3,\n },\n );\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n {\n ctx.next_block_id_mixin(state.file_picker_pending_dir_revision);\n ctx.list_begin(\"files\");\n ctx.inherit_focus();\n\n for entries in state.file_picker_entries.as_ref().unwrap() {\n for entry in entries {\n match ctx.list_item(false, entry.as_str()) {\n ListSelection::Unchanged => {}\n ListSelection::Selected => {\n state.file_picker_pending_name = entry.as_path().into()\n }\n ListSelection::Activated => activated = true,\n }\n ctx.attr_overflow(Overflow::TruncateMiddle);\n }\n }\n\n ctx.list_end();\n }\n ctx.scrollarea_end();\n\n if contains_focus\n && (ctx.consume_shortcut(vk::BACK) || ctx.consume_shortcut(kbmod::ALT | vk::UP))\n {\n state.file_picker_pending_name = \"..\".into();\n activated = true;\n }\n\n if activated {\n doit = draw_file_picker_update_path(state);\n\n // Check if the file already exists and show an overwrite warning in that case.\n if state.wants_file_picker != StateFilePicker::Open\n && let Some(path) = doit.as_deref()\n && path.exists()\n {\n state.file_picker_overwrite_warning = doit.take();\n }\n }\n }\n if ctx.modal_end() {\n done = true;\n }\n\n if state.file_picker_overwrite_warning.is_some() {\n let mut save;\n\n ctx.modal_begin(\"overwrite\", loc(LocId::FileOverwriteWarning));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n let contains_focus = ctx.contains_focus();\n\n ctx.label(\"description\", loc(LocId::FileOverwriteWarningDescription));\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n save = ctx.button(\"yes\", loc(LocId::Yes), ButtonStyle::default());\n ctx.inherit_focus();\n\n if ctx.button(\"no\", loc(LocId::No), ButtonStyle::default()) {\n state.file_picker_overwrite_warning = None;\n }\n }\n ctx.table_end();\n\n if contains_focus {\n save |= ctx.consume_shortcut(vk::Y);\n if ctx.consume_shortcut(vk::N) {\n state.file_picker_overwrite_warning = None;\n }\n }\n }\n if ctx.modal_end() {\n state.file_picker_overwrite_warning = None;\n }\n\n if save {\n doit = state.file_picker_overwrite_warning.take();\n }\n }\n\n if let Some(path) = doit {\n let res = if state.wants_file_picker == StateFilePicker::Open {\n state.documents.add_file_path(&path).map(|_| ())\n } else if let Some(doc) = state.documents.active_mut() {\n doc.save(Some(path))\n } else {\n Ok(())\n };\n match res {\n Ok(..) => {\n ctx.needs_rerender();\n done = true;\n }\n Err(err) => error_log_add(ctx, state, err),\n }\n }\n\n if done {\n state.wants_file_picker = StateFilePicker::None;\n state.file_picker_pending_name = Default::default();\n state.file_picker_entries = Default::default();\n state.file_picker_overwrite_warning = Default::default();\n state.file_picker_autocomplete = Default::default();\n }\n}\n\n// Returns Some(path) if the path refers to a file.\nfn draw_file_picker_update_path(state: &mut State) -> Option {\n let old_path = state.file_picker_pending_dir.as_path();\n let path = old_path.join(&state.file_picker_pending_name);\n let path = path::normalize(&path);\n\n let (dir, name) = if path.is_dir() {\n // If the current path is C:\\ and the user selects \"..\", we want to\n // navigate to the drive picker. Since `path::normalize` will turn C:\\.. into C:\\,\n // we can detect this by checking if the length of the path didn't change.\n let dir = if cfg!(windows)\n && state.file_picker_pending_name == Path::new(\"..\")\n // It's unnecessary to check the contents of the paths.\n && old_path.as_os_str().len() == path.as_os_str().len()\n {\n Path::new(\"\")\n } else {\n path.as_path()\n };\n (dir, PathBuf::new())\n } else {\n let dir = path.parent().unwrap_or(&path);\n let name = path.file_name().map_or(Default::default(), |s| s.into());\n (dir, name)\n };\n if dir != state.file_picker_pending_dir.as_path() {\n state.file_picker_pending_dir = DisplayablePathBuf::from_path(dir.to_path_buf());\n state.file_picker_pending_dir_revision =\n state.file_picker_pending_dir_revision.wrapping_add(1);\n state.file_picker_entries = None;\n }\n\n state.file_picker_pending_name = name;\n if state.file_picker_pending_name.as_os_str().is_empty() { None } else { Some(path) }\n}\n\nfn draw_dialog_saveas_refresh_files(state: &mut State) {\n let dir = state.file_picker_pending_dir.as_path();\n // [\"..\", directories, files]\n let mut dirs_files = [Vec::new(), Vec::new(), Vec::new()];\n\n #[cfg(windows)]\n if dir.as_os_str().is_empty() {\n // If the path is empty, we are at the drive picker.\n // Add all drives as entries.\n for drive in edit::sys::drives() {\n dirs_files[1].push(DisplayablePathBuf::from_string(format!(\"{drive}:\\\\\")));\n }\n\n state.file_picker_entries = Some(dirs_files);\n return;\n }\n\n if cfg!(windows) || dir.parent().is_some() {\n dirs_files[0].push(DisplayablePathBuf::from(\"..\"));\n }\n\n if let Ok(iter) = fs::read_dir(dir) {\n for entry in iter.flatten() {\n if let Ok(metadata) = entry.metadata() {\n let mut name = entry.file_name();\n let dir = metadata.is_dir()\n || (metadata.is_symlink()\n && fs::metadata(entry.path()).is_ok_and(|m| m.is_dir()));\n let idx = if dir { 1 } else { 2 };\n\n if dir {\n name.push(\"/\");\n }\n\n dirs_files[idx].push(DisplayablePathBuf::from(name));\n }\n }\n }\n\n for entries in &mut dirs_files[1..] {\n entries.sort_by(|a, b| {\n let a = a.as_bytes();\n let b = b.as_bytes();\n\n let a_is_dir = a.last() == Some(&b'/');\n let b_is_dir = b.last() == Some(&b'/');\n\n match b_is_dir.cmp(&a_is_dir) {\n Ordering::Equal => icu::compare_strings(a, b),\n other => other,\n }\n });\n }\n\n state.file_picker_entries = Some(dirs_files);\n}\n\n#[inline(never)]\nfn update_autocomplete_suggestions(state: &mut State) {\n state.file_picker_autocomplete.clear();\n\n if state.file_picker_pending_name.as_os_str().is_empty() {\n return;\n }\n\n let scratch = scratch_arena(None);\n let needle = state.file_picker_pending_name.as_os_str().as_encoded_bytes();\n let mut matches = Vec::new();\n\n // Using binary search below we'll quickly find the lower bound\n // of items that match the needle (= share a common prefix).\n //\n // The problem is finding the upper bound. Here I'm using a trick:\n // By appending U+10FFFF (the highest possible Unicode code point)\n // we create a needle that naturally yields an upper bound.\n let mut needle_upper_bound = Vec::with_capacity_in(needle.len() + 4, &*scratch);\n needle_upper_bound.extend_from_slice(needle);\n needle_upper_bound.extend_from_slice(b\"\\xf4\\x8f\\xbf\\xbf\");\n\n if let Some(dirs_files) = &state.file_picker_entries {\n 'outer: for entries in &dirs_files[1..] {\n let lower = entries\n .binary_search_by(|entry| icu::compare_strings(entry.as_bytes(), needle))\n .unwrap_or_else(|i| i);\n\n for entry in &entries[lower..] {\n let haystack = entry.as_bytes();\n match icu::compare_strings(haystack, &needle_upper_bound) {\n Ordering::Less => {\n matches.push(entry.clone());\n if matches.len() >= 5 {\n break 'outer; // Limit to 5 suggestions\n }\n }\n // We're looking for suggestions, not for matches.\n Ordering::Equal => {}\n // No more matches possible.\n Ordering::Greater => break,\n }\n }\n }\n }\n\n state.file_picker_autocomplete = matches;\n}\n"], ["/edit/src/bin/edit/documents.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::collections::LinkedList;\nuse std::ffi::OsStr;\nuse std::fs::File;\nuse std::path::{Path, PathBuf};\n\nuse edit::buffer::{RcTextBuffer, TextBuffer};\nuse edit::helpers::{CoordType, Point};\nuse edit::{apperr, path, sys};\n\nuse crate::state::DisplayablePathBuf;\n\npub struct Document {\n pub buffer: RcTextBuffer,\n pub path: Option,\n pub dir: Option,\n pub filename: String,\n pub file_id: Option,\n pub new_file_counter: usize,\n}\n\nimpl Document {\n pub fn save(&mut self, new_path: Option) -> apperr::Result<()> {\n let path = new_path.as_deref().unwrap_or_else(|| self.path.as_ref().unwrap().as_path());\n let mut file = DocumentManager::open_for_writing(path)?;\n\n {\n let mut tb = self.buffer.borrow_mut();\n tb.write_file(&mut file)?;\n }\n\n if let Ok(id) = sys::file_id(None, path) {\n self.file_id = Some(id);\n }\n\n if let Some(path) = new_path {\n self.set_path(path);\n }\n\n Ok(())\n }\n\n pub fn reread(&mut self, encoding: Option<&'static str>) -> apperr::Result<()> {\n let path = self.path.as_ref().unwrap().as_path();\n let mut file = DocumentManager::open_for_reading(path)?;\n\n {\n let mut tb = self.buffer.borrow_mut();\n tb.read_file(&mut file, encoding)?;\n }\n\n if let Ok(id) = sys::file_id(None, path) {\n self.file_id = Some(id);\n }\n\n Ok(())\n }\n\n fn set_path(&mut self, path: PathBuf) {\n let filename = path.file_name().unwrap_or_default().to_string_lossy().into_owned();\n let dir = path.parent().map(ToOwned::to_owned).unwrap_or_default();\n self.filename = filename;\n self.dir = Some(DisplayablePathBuf::from_path(dir));\n self.path = Some(path);\n self.update_file_mode();\n }\n\n fn update_file_mode(&mut self) {\n let mut tb = self.buffer.borrow_mut();\n tb.set_ruler(if self.filename == \"COMMIT_EDITMSG\" { 72 } else { 0 });\n }\n}\n\n#[derive(Default)]\npub struct DocumentManager {\n list: LinkedList,\n}\n\nimpl DocumentManager {\n #[inline]\n pub fn len(&self) -> usize {\n self.list.len()\n }\n\n #[inline]\n pub fn active(&self) -> Option<&Document> {\n self.list.front()\n }\n\n #[inline]\n pub fn active_mut(&mut self) -> Option<&mut Document> {\n self.list.front_mut()\n }\n\n #[inline]\n pub fn update_active bool>(&mut self, mut func: F) -> bool {\n let mut cursor = self.list.cursor_front_mut();\n while let Some(doc) = cursor.current() {\n if func(doc) {\n let list = cursor.remove_current_as_list().unwrap();\n self.list.cursor_front_mut().splice_before(list);\n return true;\n }\n cursor.move_next();\n }\n false\n }\n\n pub fn remove_active(&mut self) {\n self.list.pop_front();\n }\n\n pub fn add_untitled(&mut self) -> apperr::Result<&mut Document> {\n let buffer = Self::create_buffer()?;\n let mut doc = Document {\n buffer,\n path: None,\n dir: Default::default(),\n filename: Default::default(),\n file_id: None,\n new_file_counter: 0,\n };\n self.gen_untitled_name(&mut doc);\n\n self.list.push_front(doc);\n Ok(self.list.front_mut().unwrap())\n }\n\n pub fn gen_untitled_name(&self, doc: &mut Document) {\n let mut new_file_counter = 0;\n for doc in &self.list {\n new_file_counter = new_file_counter.max(doc.new_file_counter);\n }\n new_file_counter += 1;\n\n doc.filename = format!(\"Untitled-{new_file_counter}.txt\");\n doc.new_file_counter = new_file_counter;\n }\n\n pub fn add_file_path(&mut self, path: &Path) -> apperr::Result<&mut Document> {\n let (path, goto) = Self::parse_filename_goto(path);\n let path = path::normalize(path);\n\n let mut file = match Self::open_for_reading(&path) {\n Ok(file) => Some(file),\n Err(err) if sys::apperr_is_not_found(err) => None,\n Err(err) => return Err(err),\n };\n\n let file_id = if file.is_some() { Some(sys::file_id(file.as_ref(), &path)?) } else { None };\n\n // Check if the file is already open.\n if file_id.is_some() && self.update_active(|doc| doc.file_id == file_id) {\n let doc = self.active_mut().unwrap();\n if let Some(goto) = goto {\n doc.buffer.borrow_mut().cursor_move_to_logical(goto);\n }\n return Ok(doc);\n }\n\n let buffer = Self::create_buffer()?;\n {\n if let Some(file) = &mut file {\n let mut tb = buffer.borrow_mut();\n tb.read_file(file, None)?;\n\n if let Some(goto) = goto\n && goto != Default::default()\n {\n tb.cursor_move_to_logical(goto);\n }\n }\n }\n\n let mut doc = Document {\n buffer,\n path: None,\n dir: None,\n filename: Default::default(),\n file_id,\n new_file_counter: 0,\n };\n doc.set_path(path);\n\n if let Some(active) = self.active()\n && active.path.is_none()\n && active.file_id.is_none()\n && !active.buffer.borrow().is_dirty()\n {\n // If the current document is a pristine Untitled document with no\n // name and no ID, replace it with the new document.\n self.remove_active();\n }\n\n self.list.push_front(doc);\n Ok(self.list.front_mut().unwrap())\n }\n\n pub fn reflow_all(&self) {\n for doc in &self.list {\n let mut tb = doc.buffer.borrow_mut();\n tb.reflow();\n }\n }\n\n pub fn open_for_reading(path: &Path) -> apperr::Result {\n File::open(path).map_err(apperr::Error::from)\n }\n\n pub fn open_for_writing(path: &Path) -> apperr::Result {\n File::create(path).map_err(apperr::Error::from)\n }\n\n fn create_buffer() -> apperr::Result {\n let buffer = TextBuffer::new_rc(false)?;\n {\n let mut tb = buffer.borrow_mut();\n tb.set_insert_final_newline(!cfg!(windows)); // As mandated by POSIX.\n tb.set_margin_enabled(true);\n tb.set_line_highlight_enabled(true);\n }\n Ok(buffer)\n }\n\n // Parse a filename in the form of \"filename:line:char\".\n // Returns the position of the first colon and the line/char coordinates.\n fn parse_filename_goto(path: &Path) -> (&Path, Option) {\n fn parse(s: &[u8]) -> Option {\n if s.is_empty() {\n return None;\n }\n\n let mut num: CoordType = 0;\n for &b in s {\n if !b.is_ascii_digit() {\n return None;\n }\n let digit = (b - b'0') as CoordType;\n num = num.checked_mul(10)?.checked_add(digit)?;\n }\n Some(num)\n }\n\n fn find_colon_rev(bytes: &[u8], offset: usize) -> Option {\n (0..offset.min(bytes.len())).rev().find(|&i| bytes[i] == b':')\n }\n\n let bytes = path.as_os_str().as_encoded_bytes();\n let colend = match find_colon_rev(bytes, bytes.len()) {\n // Reject filenames that would result in an empty filename after stripping off the :line:char suffix.\n // For instance, a filename like \":123:456\" will not be processed by this function.\n Some(colend) if colend > 0 => colend,\n _ => return (path, None),\n };\n\n let last = match parse(&bytes[colend + 1..]) {\n Some(last) => last,\n None => return (path, None),\n };\n let last = (last - 1).max(0);\n let mut len = colend;\n let mut goto = Point { x: 0, y: last };\n\n if let Some(colbeg) = find_colon_rev(bytes, colend) {\n // Same here: Don't allow empty filenames.\n if colbeg != 0\n && let Some(first) = parse(&bytes[colbeg + 1..colend])\n {\n let first = (first - 1).max(0);\n len = colbeg;\n goto = Point { x: last, y: first };\n }\n }\n\n // Strip off the :line:char suffix.\n let path = &bytes[..len];\n let path = unsafe { OsStr::from_encoded_bytes_unchecked(path) };\n let path = Path::new(path);\n (path, Some(goto))\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_parse_last_numbers() {\n fn parse(s: &str) -> (&str, Option) {\n let (p, g) = DocumentManager::parse_filename_goto(Path::new(s));\n (p.to_str().unwrap(), g)\n }\n\n assert_eq!(parse(\"123\"), (\"123\", None));\n assert_eq!(parse(\"abc\"), (\"abc\", None));\n assert_eq!(parse(\":123\"), (\":123\", None));\n assert_eq!(parse(\"abc:123\"), (\"abc\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"45:123\"), (\"45\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\":45:123\"), (\":45\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"abc:45:123\"), (\"abc\", Some(Point { x: 122, y: 44 })));\n assert_eq!(parse(\"abc:def:123\"), (\"abc:def\", Some(Point { x: 0, y: 122 })));\n assert_eq!(parse(\"1:2:3\"), (\"1\", Some(Point { x: 2, y: 1 })));\n assert_eq!(parse(\"::3\"), (\":\", Some(Point { x: 0, y: 2 })));\n assert_eq!(parse(\"1::3\"), (\"1:\", Some(Point { x: 0, y: 2 })));\n assert_eq!(parse(\"\"), (\"\", None));\n assert_eq!(parse(\":\"), (\":\", None));\n assert_eq!(parse(\"::\"), (\"::\", None));\n assert_eq!(parse(\"a:1\"), (\"a\", Some(Point { x: 0, y: 0 })));\n assert_eq!(parse(\"1:a\"), (\"1:a\", None));\n assert_eq!(parse(\"file.txt:10\"), (\"file.txt\", Some(Point { x: 0, y: 9 })));\n assert_eq!(parse(\"file.txt:10:5\"), (\"file.txt\", Some(Point { x: 4, y: 9 })));\n }\n}\n"], ["/edit/src/fuzzy.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Fuzzy search algorithm based on the one used in VS Code (`/src/vs/base/common/fuzzyScorer.ts`).\n//! Other algorithms exist, such as Sublime Text's, or the one used in `fzf`,\n//! but I figured that this one is what lots of people may be familiar with.\n\nuse std::vec;\n\nuse crate::arena::{Arena, scratch_arena};\nuse crate::icu;\n\nconst NO_MATCH: i32 = 0;\n\npub fn score_fuzzy<'a>(\n arena: &'a Arena,\n haystack: &str,\n needle: &str,\n allow_non_contiguous_matches: bool,\n) -> (i32, Vec) {\n if haystack.is_empty() || needle.is_empty() {\n // return early if target or query are empty\n return (NO_MATCH, Vec::new_in(arena));\n }\n\n let scratch = scratch_arena(Some(arena));\n let target = map_chars(&scratch, haystack);\n let query = map_chars(&scratch, needle);\n\n if target.len() < query.len() {\n // impossible for query to be contained in target\n return (NO_MATCH, Vec::new_in(arena));\n }\n\n let target_lower = icu::fold_case(&scratch, haystack);\n let query_lower = icu::fold_case(&scratch, needle);\n let target_lower = map_chars(&scratch, &target_lower);\n let query_lower = map_chars(&scratch, &query_lower);\n\n let area = query.len() * target.len();\n let mut scores = vec::from_elem_in(0, area, &*scratch);\n let mut matches = vec::from_elem_in(0, area, &*scratch);\n\n //\n // Build Scorer Matrix:\n //\n // The matrix is composed of query q and target t. For each index we score\n // q[i] with t[i] and compare that with the previous score. If the score is\n // equal or larger, we keep the match. In addition to the score, we also keep\n // the length of the consecutive matches to use as boost for the score.\n //\n // t a r g e t\n // q\n // u\n // e\n // r\n // y\n //\n for query_index in 0..query.len() {\n let query_index_offset = query_index * target.len();\n let query_index_previous_offset =\n if query_index > 0 { (query_index - 1) * target.len() } else { 0 };\n\n for target_index in 0..target.len() {\n let current_index = query_index_offset + target_index;\n let diag_index = if query_index > 0 && target_index > 0 {\n query_index_previous_offset + target_index - 1\n } else {\n 0\n };\n let left_score = if target_index > 0 { scores[current_index - 1] } else { 0 };\n let diag_score =\n if query_index > 0 && target_index > 0 { scores[diag_index] } else { 0 };\n let matches_sequence_len =\n if query_index > 0 && target_index > 0 { matches[diag_index] } else { 0 };\n\n // If we are not matching on the first query character anymore, we only produce a\n // score if we had a score previously for the last query index (by looking at the diagScore).\n // This makes sure that the query always matches in sequence on the target. For example\n // given a target of \"ede\" and a query of \"de\", we would otherwise produce a wrong high score\n // for query[1] (\"e\") matching on target[0] (\"e\") because of the \"beginning of word\" boost.\n let score = if diag_score == 0 && query_index != 0 {\n 0\n } else {\n compute_char_score(\n query[query_index],\n query_lower[query_index],\n if target_index != 0 { Some(target[target_index - 1]) } else { None },\n target[target_index],\n target_lower[target_index],\n matches_sequence_len,\n )\n };\n\n // We have a score and its equal or larger than the left score\n // Match: sequence continues growing from previous diag value\n // Score: increases by diag score value\n let is_valid_score = score != 0 && diag_score + score >= left_score;\n if is_valid_score\n && (\n // We don't need to check if it's contiguous if we allow non-contiguous matches\n allow_non_contiguous_matches ||\n // We must be looking for a contiguous match.\n // Looking at an index above 0 in the query means we must have already\n // found out this is contiguous otherwise there wouldn't have been a score\n query_index > 0 ||\n // lastly check if the query is completely contiguous at this index in the target\n target_lower[target_index..].starts_with(&query_lower)\n )\n {\n matches[current_index] = matches_sequence_len + 1;\n scores[current_index] = diag_score + score;\n } else {\n // We either have no score or the score is lower than the left score\n // Match: reset to 0\n // Score: pick up from left hand side\n matches[current_index] = NO_MATCH;\n scores[current_index] = left_score;\n }\n }\n }\n\n // Restore Positions (starting from bottom right of matrix)\n let mut positions = Vec::new_in(arena);\n\n if !query.is_empty() && !target.is_empty() {\n let mut query_index = query.len() - 1;\n let mut target_index = target.len() - 1;\n\n loop {\n let current_index = query_index * target.len() + target_index;\n if matches[current_index] == NO_MATCH {\n if target_index == 0 {\n break;\n }\n target_index -= 1; // go left\n } else {\n positions.push(target_index);\n\n // go up and left\n if query_index == 0 || target_index == 0 {\n break;\n }\n query_index -= 1;\n target_index -= 1;\n }\n }\n\n positions.reverse();\n }\n\n (scores[area - 1], positions)\n}\n\nfn compute_char_score(\n query: char,\n query_lower: char,\n target_prev: Option,\n target_curr: char,\n target_curr_lower: char,\n matches_sequence_len: i32,\n) -> i32 {\n let mut score = 0;\n\n if !consider_as_equal(query_lower, target_curr_lower) {\n return score; // no match of characters\n }\n\n // Character match bonus\n score += 1;\n\n // Consecutive match bonus\n if matches_sequence_len > 0 {\n score += matches_sequence_len * 5;\n }\n\n // Same case bonus\n if query == target_curr {\n score += 1;\n }\n\n if let Some(target_prev) = target_prev {\n // After separator bonus\n let separator_bonus = score_separator_at_pos(target_prev);\n if separator_bonus > 0 {\n score += separator_bonus;\n }\n // Inside word upper case bonus (camel case). We only give this bonus if we're not in a contiguous sequence.\n // For example:\n // NPE => NullPointerException = boost\n // HTTP => HTTP = not boost\n else if target_curr != target_curr_lower && matches_sequence_len == 0 {\n score += 2;\n }\n } else {\n // Start of word bonus\n score += 8;\n }\n\n score\n}\n\nfn consider_as_equal(a: char, b: char) -> bool {\n // Special case path separators: ignore platform differences\n a == b || (a == '/' && b == '\\\\') || (a == '\\\\' && b == '/')\n}\n\nfn score_separator_at_pos(ch: char) -> i32 {\n match ch {\n '/' | '\\\\' => 5, // prefer path separators...\n '_' | '-' | '.' | ' ' | '\\'' | '\"' | ':' => 4, // ...over other separators\n _ => 0,\n }\n}\n\nfn map_chars<'a>(arena: &'a Arena, s: &str) -> Vec {\n let mut chars = Vec::with_capacity_in(s.len(), arena);\n chars.extend(s.chars());\n chars.shrink_to_fit();\n chars\n}\n"], ["/edit/src/arena/release.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![allow(clippy::mut_from_ref)]\n\nuse std::alloc::{AllocError, Allocator, Layout};\nuse std::cell::Cell;\nuse std::hint::cold_path;\nuse std::mem::MaybeUninit;\nuse std::ptr::{self, NonNull};\nuse std::{mem, slice};\n\nuse crate::helpers::*;\nuse crate::{apperr, sys};\n\nconst ALLOC_CHUNK_SIZE: usize = 64 * KIBI;\n\n/// An arena allocator.\n///\n/// If you have never used an arena allocator before, think of it as\n/// allocating objects on the stack, but the stack is *really* big.\n/// Each time you allocate, memory gets pushed at the end of the stack,\n/// each time you deallocate, memory gets popped from the end of the stack.\n///\n/// One reason you'd want to use this is obviously performance: It's very simple\n/// and so it's also very fast, >10x faster than your system allocator.\n///\n/// However, modern allocators such as `mimalloc` are just as fast, so why not use them?\n/// Because their performance comes at the cost of binary size and we can't have that.\n///\n/// The biggest benefit though is that it sometimes massively simplifies lifetime\n/// and memory management. This can best be seen by this project's UI code, which\n/// uses an arena to allocate a tree of UI nodes. This is infamously difficult\n/// to do in Rust, but not so when you got an arena allocator:\n/// All nodes have the same lifetime, so you can just use references.\n///\n///
\n///\n/// **Do not** push objects into the arena that require destructors.\n/// Destructors are not executed. Use a pool allocator for that.\n///\n///
\npub struct Arena {\n base: NonNull,\n capacity: usize,\n commit: Cell,\n offset: Cell,\n\n /// See [`super::debug`], which uses this for borrow tracking.\n #[cfg(debug_assertions)]\n pub(super) borrows: Cell,\n}\n\nimpl Arena {\n pub const fn empty() -> Self {\n Self {\n base: NonNull::dangling(),\n capacity: 0,\n commit: Cell::new(0),\n offset: Cell::new(0),\n\n #[cfg(debug_assertions)]\n borrows: Cell::new(0),\n }\n }\n\n pub fn new(capacity: usize) -> apperr::Result {\n let capacity = (capacity.max(1) + ALLOC_CHUNK_SIZE - 1) & !(ALLOC_CHUNK_SIZE - 1);\n let base = unsafe { sys::virtual_reserve(capacity)? };\n\n Ok(Self {\n base,\n capacity,\n commit: Cell::new(0),\n offset: Cell::new(0),\n\n #[cfg(debug_assertions)]\n borrows: Cell::new(0),\n })\n }\n\n pub fn is_empty(&self) -> bool {\n self.base == NonNull::dangling()\n }\n\n pub fn offset(&self) -> usize {\n self.offset.get()\n }\n\n /// \"Deallocates\" the memory in the arena down to the given offset.\n ///\n /// # Safety\n ///\n /// Obviously, this is GIGA UNSAFE. It runs no destructors and does not check\n /// whether the offset is valid. You better take care when using this function.\n pub unsafe fn reset(&self, to: usize) {\n // Fill the deallocated memory with 0xDD to aid debugging.\n if cfg!(debug_assertions) && self.offset.get() > to {\n let commit = self.commit.get();\n let len = (self.offset.get() + 128).min(commit) - to;\n unsafe { slice::from_raw_parts_mut(self.base.add(to).as_ptr(), len).fill(0xDD) };\n }\n\n self.offset.replace(to);\n }\n\n #[inline]\n pub(super) fn alloc_raw(\n &self,\n bytes: usize,\n alignment: usize,\n ) -> Result, AllocError> {\n let commit = self.commit.get();\n let offset = self.offset.get();\n\n let beg = (offset + alignment - 1) & !(alignment - 1);\n let end = beg + bytes;\n\n if end > commit {\n return self.alloc_raw_bump(beg, end);\n }\n\n if cfg!(debug_assertions) {\n let ptr = unsafe { self.base.add(offset) };\n let len = (end + 128).min(self.commit.get()) - offset;\n unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len).fill(0xCD) };\n }\n\n self.offset.replace(end);\n Ok(unsafe { NonNull::slice_from_raw_parts(self.base.add(beg), bytes) })\n }\n\n // With the code in `alloc_raw_bump()` out of the way, `alloc_raw()` compiles down to some super tight assembly.\n #[cold]\n fn alloc_raw_bump(&self, beg: usize, end: usize) -> Result, AllocError> {\n let offset = self.offset.get();\n let commit_old = self.commit.get();\n let commit_new = (end + ALLOC_CHUNK_SIZE - 1) & !(ALLOC_CHUNK_SIZE - 1);\n\n if commit_new > self.capacity\n || unsafe {\n sys::virtual_commit(self.base.add(commit_old), commit_new - commit_old).is_err()\n }\n {\n return Err(AllocError);\n }\n\n if cfg!(debug_assertions) {\n let ptr = unsafe { self.base.add(offset) };\n let len = (end + 128).min(self.commit.get()) - offset;\n unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len).fill(0xCD) };\n }\n\n self.commit.replace(commit_new);\n self.offset.replace(end);\n Ok(unsafe { NonNull::slice_from_raw_parts(self.base.add(beg), end - beg) })\n }\n\n #[allow(clippy::mut_from_ref)]\n pub fn alloc_uninit(&self) -> &mut MaybeUninit {\n let bytes = mem::size_of::();\n let alignment = mem::align_of::();\n let ptr = self.alloc_raw(bytes, alignment).unwrap();\n unsafe { ptr.cast().as_mut() }\n }\n\n #[allow(clippy::mut_from_ref)]\n pub fn alloc_uninit_slice(&self, count: usize) -> &mut [MaybeUninit] {\n let bytes = mem::size_of::() * count;\n let alignment = mem::align_of::();\n let ptr = self.alloc_raw(bytes, alignment).unwrap();\n unsafe { slice::from_raw_parts_mut(ptr.cast().as_ptr(), count) }\n }\n}\n\nimpl Drop for Arena {\n fn drop(&mut self) {\n if !self.is_empty() {\n unsafe { sys::virtual_release(self.base, self.capacity) };\n }\n }\n}\n\nimpl Default for Arena {\n fn default() -> Self {\n Self::empty()\n }\n}\n\nunsafe impl Allocator for Arena {\n fn allocate(&self, layout: Layout) -> Result, AllocError> {\n self.alloc_raw(layout.size(), layout.align())\n }\n\n fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> {\n let p = self.alloc_raw(layout.size(), layout.align())?;\n unsafe { p.cast::().as_ptr().write_bytes(0, p.len()) }\n Ok(p)\n }\n\n // While it is possible to shrink the tail end of the arena, it is\n // not very useful given the existence of scoped scratch arenas.\n unsafe fn deallocate(&self, _: NonNull, _: Layout) {}\n\n unsafe fn grow(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n debug_assert!(new_layout.size() >= old_layout.size());\n debug_assert!(new_layout.align() <= old_layout.align());\n\n let new_ptr;\n\n // Growing the given area is possible if it is at the end of the arena.\n if unsafe { ptr.add(old_layout.size()) == self.base.add(self.offset.get()) } {\n new_ptr = ptr;\n let delta = new_layout.size() - old_layout.size();\n // Assuming that the given ptr/length area is at the end of the arena,\n // we can just push more memory to the end of the arena to grow it.\n self.alloc_raw(delta, 1)?;\n } else {\n cold_path();\n\n new_ptr = self.allocate(new_layout)?.cast();\n\n // SAFETY: It's weird to me that this doesn't assert new_layout.size() >= old_layout.size(),\n // but neither does the stdlib code at the time of writing.\n // So, assuming that is not needed, this code is safe since it just copies the old data over.\n unsafe {\n ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), old_layout.size());\n self.deallocate(ptr, old_layout);\n }\n }\n\n Ok(NonNull::slice_from_raw_parts(new_ptr, new_layout.size()))\n }\n\n unsafe fn grow_zeroed(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe {\n // SAFETY: Same as grow().\n let ptr = self.grow(ptr, old_layout, new_layout)?;\n\n // SAFETY: At this point, `ptr` must be valid for `new_layout.size()` bytes,\n // allowing us to safely zero out the delta since `old_layout.size()`.\n ptr.cast::()\n .add(old_layout.size())\n .write_bytes(0, new_layout.size() - old_layout.size());\n\n Ok(ptr)\n }\n }\n\n unsafe fn shrink(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n debug_assert!(new_layout.size() <= old_layout.size());\n debug_assert!(new_layout.align() <= old_layout.align());\n\n let mut len = old_layout.size();\n\n // Shrinking the given area is possible if it is at the end of the arena.\n if unsafe { ptr.add(len) == self.base.add(self.offset.get()) } {\n self.offset.set(self.offset.get() - len + new_layout.size());\n len = new_layout.size();\n } else {\n debug_assert!(\n false,\n \"Did you call shrink_to_fit()? Only the last allocation can be shrunk!\"\n );\n }\n\n Ok(NonNull::slice_from_raw_parts(ptr, len))\n }\n}\n"], ["/edit/src/simd/memchr2.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! `memchr`, but with two needles.\n\nuse std::ptr;\n\n/// `memchr`, but with two needles.\n///\n/// Returns the index of the first occurrence of either needle in the\n/// `haystack`. If no needle is found, `haystack.len()` is returned.\n/// `offset` specifies the index to start searching from.\npub fn memchr2(needle1: u8, needle2: u8, haystack: &[u8], offset: usize) -> usize {\n unsafe {\n let beg = haystack.as_ptr();\n let end = beg.add(haystack.len());\n let it = beg.add(offset.min(haystack.len()));\n let it = memchr2_raw(needle1, needle2, it, end);\n it.offset_from_unsigned(beg)\n }\n}\n\nunsafe fn memchr2_raw(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { MEMCHR2_DISPATCH(needle1, needle2, beg, end) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { memchr2_neon(needle1, needle2, beg, end) };\n\n #[allow(unreachable_code)]\n return unsafe { memchr2_fallback(needle1, needle2, beg, end) };\n}\n\nunsafe fn memchr2_fallback(\n needle1: u8,\n needle2: u8,\n mut beg: *const u8,\n end: *const u8,\n) -> *const u8 {\n unsafe {\n while !ptr::eq(beg, end) {\n let ch = *beg;\n if ch == needle1 || ch == needle2 {\n break;\n }\n beg = beg.add(1);\n }\n beg\n }\n}\n\n// In order to make `memchr2_raw` slim and fast, we use a function pointer that updates\n// itself to the correct implementation on the first call. This reduces binary size.\n// It would also reduce branches if we had >2 implementations (a jump still needs to be predicted).\n// NOTE that this ONLY works if Control Flow Guard is disabled on Windows.\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut MEMCHR2_DISPATCH: unsafe fn(\n needle1: u8,\n needle2: u8,\n beg: *const u8,\n end: *const u8,\n) -> *const u8 = memchr2_dispatch;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nunsafe fn memchr2_dispatch(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n let func = if is_x86_feature_detected!(\"avx2\") { memchr2_avx2 } else { memchr2_fallback };\n unsafe { MEMCHR2_DISPATCH = func };\n unsafe { func(needle1, needle2, beg, end) }\n}\n\n// FWIW, I found that adding support for AVX512 was not useful at the time,\n// as it only marginally improved file load performance by <5%.\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"avx2\")]\nunsafe fn memchr2_avx2(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n\n let n1 = _mm256_set1_epi8(needle1 as i8);\n let n2 = _mm256_set1_epi8(needle2 as i8);\n let mut remaining = end.offset_from_unsigned(beg);\n\n while remaining >= 32 {\n let v = _mm256_loadu_si256(beg as *const _);\n let a = _mm256_cmpeq_epi8(v, n1);\n let b = _mm256_cmpeq_epi8(v, n2);\n let c = _mm256_or_si256(a, b);\n let m = _mm256_movemask_epi8(c) as u32;\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(32);\n remaining -= 32;\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn memchr2_dispatch(needle1: u8, needle2: u8, beg: *const u8, end: *const u8) -> *const u8 {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n memchr2_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n memchr2_lsx\n } else {\n memchr2_fallback\n };\n unsafe { MEMCHR2_DISPATCH = func };\n unsafe { func(needle1, needle2, beg, end) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn memchr2_lasx(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let n1 = lasx_xvreplgr2vr_b(needle1 as i32);\n let n2 = lasx_xvreplgr2vr_b(needle2 as i32);\n\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n beg = memchr2_lsx(needle1, needle2, beg, beg.add(off));\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = lasx_xvld::<0>(beg as *const _);\n let a = lasx_xvseq_b(v, n1);\n let b = lasx_xvseq_b(v, n2);\n let c = lasx_xvor_v(T(a), T(b));\n let m = lasx_xvmskltz_b(T(c));\n let l = lasx_xvpickve2gr_wu::<0>(T(m));\n let h = lasx_xvpickve2gr_wu::<4>(T(m));\n let m = (h << 16) | l;\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(32);\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn memchr2_lsx(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let n1 = lsx_vreplgr2vr_b(needle1 as i32);\n let n2 = lsx_vreplgr2vr_b(needle2 as i32);\n\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n beg = memchr2_fallback(needle1, needle2, beg, beg.add(off));\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = lsx_vld::<0>(beg as *const _);\n let a = lsx_vseq_b(v, n1);\n let b = lsx_vseq_b(v, n2);\n let c = lsx_vor_v(T(a), T(b));\n let m = lsx_vmskltz_b(T(c));\n let m = lsx_vpickve2gr_wu::<0>(T(m));\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize);\n }\n\n beg = beg.add(16);\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn memchr2_neon(needle1: u8, needle2: u8, mut beg: *const u8, end: *const u8) -> *const u8 {\n unsafe {\n use std::arch::aarch64::*;\n\n if end.offset_from_unsigned(beg) >= 16 {\n let n1 = vdupq_n_u8(needle1);\n let n2 = vdupq_n_u8(needle2);\n\n loop {\n let v = vld1q_u8(beg as *const _);\n let a = vceqq_u8(v, n1);\n let b = vceqq_u8(v, n2);\n let c = vorrq_u8(a, b);\n\n // https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon\n let m = vreinterpretq_u16_u8(c);\n let m = vshrn_n_u16(m, 4);\n let m = vreinterpret_u64_u8(m);\n let m = vget_lane_u64(m, 0);\n\n if m != 0 {\n return beg.add(m.trailing_zeros() as usize >> 2);\n }\n\n beg = beg.add(16);\n if end.offset_from_unsigned(beg) < 16 {\n break;\n }\n }\n }\n\n memchr2_fallback(needle1, needle2, beg, end)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::slice;\n\n use super::*;\n use crate::sys;\n\n #[test]\n fn test_empty() {\n assert_eq!(memchr2(b'a', b'b', b\"\", 0), 0);\n }\n\n #[test]\n fn test_basic() {\n let haystack = b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n let haystack = &haystack[..43];\n\n assert_eq!(memchr2(b'a', b'z', haystack, 0), 0);\n assert_eq!(memchr2(b'p', b'q', haystack, 0), 15);\n assert_eq!(memchr2(b'Q', b'Z', haystack, 0), 42);\n assert_eq!(memchr2(b'0', b'9', haystack, 0), haystack.len());\n }\n\n // Test that it doesn't match before/after the start offset respectively.\n #[test]\n fn test_with_offset() {\n let haystack = b\"abcdefghabcdefghabcdefghabcdefghabcdefgh\";\n\n assert_eq!(memchr2(b'a', b'b', haystack, 0), 0);\n assert_eq!(memchr2(b'a', b'b', haystack, 1), 1);\n assert_eq!(memchr2(b'a', b'b', haystack, 2), 8);\n assert_eq!(memchr2(b'a', b'b', haystack, 9), 9);\n assert_eq!(memchr2(b'a', b'b', haystack, 16), 16);\n assert_eq!(memchr2(b'a', b'b', haystack, 41), 40);\n }\n\n // Test memory access safety at page boundaries.\n // The test is a success if it doesn't segfault.\n #[test]\n fn test_page_boundary() {\n let page = unsafe {\n const PAGE_SIZE: usize = 64 * 1024; // 64 KiB to cover many architectures.\n\n // 3 pages: uncommitted, committed, uncommitted\n let ptr = sys::virtual_reserve(PAGE_SIZE * 3).unwrap();\n sys::virtual_commit(ptr.add(PAGE_SIZE), PAGE_SIZE).unwrap();\n slice::from_raw_parts_mut(ptr.add(PAGE_SIZE).as_ptr(), PAGE_SIZE)\n };\n\n page.fill(b'a');\n\n // Test if it seeks beyond the page boundary.\n assert_eq!(memchr2(b'\\0', b'\\0', &page[page.len() - 40..], 0), 40);\n // Test if it seeks before the page boundary for the masked/partial load.\n assert_eq!(memchr2(b'\\0', b'\\0', &page[..10], 0), 10);\n }\n}\n"], ["/edit/src/simd/memset.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! `memchr` for arbitrary sizes (1/2/4/8 bytes).\n//!\n//! Clang calls the C `memset` function only for byte-sized types (or 0 fills).\n//! We however need to fill other types as well. For that, clang generates\n//! SIMD loops under higher optimization levels. With `-Os` however, it only\n//! generates a trivial loop which is too slow for our needs.\n//!\n//! This implementation uses SWAR to only have a single implementation for all\n//! 4 sizes: By duplicating smaller types into a larger `u64` register we can\n//! treat all sizes as if they were `u64`. The only thing we need to take care\n//! of is the tail end of the array, which needs to write 0-7 additional bytes.\n\nuse std::mem;\n\n/// A marker trait for types that are safe to `memset`.\n///\n/// # Safety\n///\n/// Just like with C's `memset`, bad things happen\n/// if you use this with non-trivial types.\npub unsafe trait MemsetSafe: Copy {}\n\nunsafe impl MemsetSafe for u8 {}\nunsafe impl MemsetSafe for u16 {}\nunsafe impl MemsetSafe for u32 {}\nunsafe impl MemsetSafe for u64 {}\nunsafe impl MemsetSafe for usize {}\n\nunsafe impl MemsetSafe for i8 {}\nunsafe impl MemsetSafe for i16 {}\nunsafe impl MemsetSafe for i32 {}\nunsafe impl MemsetSafe for i64 {}\nunsafe impl MemsetSafe for isize {}\n\n/// Fills a slice with the given value.\n#[inline]\npub fn memset(dst: &mut [T], val: T) {\n unsafe {\n match mem::size_of::() {\n 1 => {\n // LLVM will compile this to a call to `memset`,\n // which hopefully should be better optimized than my code.\n let beg = dst.as_mut_ptr();\n let val = mem::transmute_copy::<_, u8>(&val);\n beg.write_bytes(val, dst.len());\n }\n 2 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u16>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val as u64 * 0x0001000100010001);\n }\n 4 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u32>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val as u64 * 0x0000000100000001);\n }\n 8 => {\n let beg = dst.as_mut_ptr();\n let end = beg.add(dst.len());\n let val = mem::transmute_copy::<_, u64>(&val);\n memset_raw(beg as *mut u8, end as *mut u8, val);\n }\n _ => unreachable!(),\n }\n }\n}\n\n#[inline]\nfn memset_raw(beg: *mut u8, end: *mut u8, val: u64) {\n #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { MEMSET_DISPATCH(beg, end, val) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { memset_neon(beg, end, val) };\n\n #[allow(unreachable_code)]\n return unsafe { memset_fallback(beg, end, val) };\n}\n\n#[inline(never)]\nunsafe fn memset_fallback(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n let mut remaining = end.offset_from_unsigned(beg);\n\n while remaining >= 8 {\n (beg as *mut u64).write_unaligned(val);\n beg = beg.add(8);\n remaining -= 8;\n }\n\n if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut MEMSET_DISPATCH: unsafe fn(beg: *mut u8, end: *mut u8, val: u64) = memset_dispatch;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn memset_dispatch(beg: *mut u8, end: *mut u8, val: u64) {\n let func = if is_x86_feature_detected!(\"avx2\") { memset_avx2 } else { memset_sse2 };\n unsafe { MEMSET_DISPATCH = func };\n unsafe { func(beg, end, val) }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"sse2\")]\nunsafe fn memset_sse2(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 16 {\n let fill = _mm_set1_epi64x(val as i64);\n\n while remaining >= 32 {\n _mm_storeu_si128(beg as *mut _, fill);\n _mm_storeu_si128(beg.add(16) as *mut _, fill);\n\n beg = beg.add(32);\n remaining -= 32;\n }\n\n if remaining >= 16 {\n // 16-31 bytes remaining\n _mm_storeu_si128(beg as *mut _, fill);\n _mm_storeu_si128(end.sub(16) as *mut _, fill);\n return;\n }\n }\n\n if remaining >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n#[target_feature(enable = \"avx2\")]\nfn memset_avx2(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n #[cfg(target_arch = \"x86\")]\n use std::arch::x86::*;\n #[cfg(target_arch = \"x86_64\")]\n use std::arch::x86_64::*;\n use std::hint::black_box;\n\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 128 {\n let fill = _mm256_set1_epi64x(val as i64);\n\n loop {\n _mm256_storeu_si256(beg as *mut _, fill);\n _mm256_storeu_si256(beg.add(32) as *mut _, fill);\n _mm256_storeu_si256(beg.add(64) as *mut _, fill);\n _mm256_storeu_si256(beg.add(96) as *mut _, fill);\n\n beg = beg.add(128);\n remaining -= 128;\n if remaining < 128 {\n break;\n }\n }\n }\n\n if remaining >= 16 {\n let fill = _mm_set1_epi64x(val as i64);\n\n loop {\n // LLVM is _very_ eager to unroll loops. In the absence of an unroll attribute, black_box does the job.\n // Note that this must not be applied to the intrinsic parameters, as they're otherwise misoptimized.\n #[allow(clippy::unit_arg)]\n black_box(_mm_storeu_si128(beg as *mut _, fill));\n\n beg = beg.add(16);\n remaining -= 16;\n if remaining < 16 {\n break;\n }\n }\n }\n\n // `remaining` is between 0 and 15 at this point.\n // By overlapping the stores we can write all of them in at most 2 stores. This approach\n // can be seen in various libraries, such as wyhash which uses it for loading data in `wyr3`.\n if remaining >= 8 {\n // 8-15 bytes\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nfn memset_dispatch(beg: *mut u8, end: *mut u8, val: u64) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n memset_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n memset_lsx\n } else {\n memset_fallback\n };\n unsafe { MEMSET_DISPATCH = func };\n unsafe { func(beg, end, val) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nfn memset_lasx(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n let fill: v32i8 = T(lasx_xvreplgr2vr_d(val as i64));\n\n if end.offset_from_unsigned(beg) >= 32 {\n lasx_xvst::<0>(fill, beg as *mut _);\n let off = beg.align_offset(32);\n beg = beg.add(off);\n }\n\n if end.offset_from_unsigned(beg) >= 128 {\n loop {\n lasx_xvst::<0>(fill, beg as *mut _);\n lasx_xvst::<32>(fill, beg as *mut _);\n lasx_xvst::<64>(fill, beg as *mut _);\n lasx_xvst::<96>(fill, beg as *mut _);\n\n beg = beg.add(128);\n if end.offset_from_unsigned(beg) < 128 {\n break;\n }\n }\n }\n\n if end.offset_from_unsigned(beg) >= 16 {\n let fill: v16i8 = T(lsx_vreplgr2vr_d(val as i64));\n\n loop {\n lsx_vst::<0>(fill, beg as *mut _);\n\n beg = beg.add(16);\n if end.offset_from_unsigned(beg) < 16 {\n break;\n }\n }\n }\n\n if end.offset_from_unsigned(beg) >= 8 {\n // 8-15 bytes\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if end.offset_from_unsigned(beg) >= 4 {\n // 4-7 bytes\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if end.offset_from_unsigned(beg) >= 2 {\n // 2-3 bytes\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if end.offset_from_unsigned(beg) >= 1 {\n // 1 byte\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn memset_lsx(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n if end.offset_from_unsigned(beg) >= 16 {\n let fill: v16i8 = T(lsx_vreplgr2vr_d(val as i64));\n\n lsx_vst::<0>(fill, beg as *mut _);\n let off = beg.align_offset(16);\n beg = beg.add(off);\n\n while end.offset_from_unsigned(beg) >= 32 {\n lsx_vst::<0>(fill, beg as *mut _);\n lsx_vst::<16>(fill, beg as *mut _);\n\n beg = beg.add(32);\n }\n\n if end.offset_from_unsigned(beg) >= 16 {\n // 16-31 bytes remaining\n lsx_vst::<0>(fill, beg as *mut _);\n lsx_vst::<-16>(fill, end as *mut _);\n return;\n }\n }\n\n if end.offset_from_unsigned(beg) >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if end.offset_from_unsigned(beg) >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if end.offset_from_unsigned(beg) >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if end.offset_from_unsigned(beg) >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn memset_neon(mut beg: *mut u8, end: *mut u8, val: u64) {\n unsafe {\n use std::arch::aarch64::*;\n let mut remaining = end.offset_from_unsigned(beg);\n\n if remaining >= 32 {\n let fill = vdupq_n_u64(val);\n\n loop {\n // Compiles to a single `stp` instruction.\n vst1q_u64(beg as *mut _, fill);\n vst1q_u64(beg.add(16) as *mut _, fill);\n\n beg = beg.add(32);\n remaining -= 32;\n if remaining < 32 {\n break;\n }\n }\n }\n\n if remaining >= 16 {\n // 16-31 bytes remaining\n let fill = vdupq_n_u64(val);\n vst1q_u64(beg as *mut _, fill);\n vst1q_u64(end.sub(16) as *mut _, fill);\n } else if remaining >= 8 {\n // 8-15 bytes remaining\n (beg as *mut u64).write_unaligned(val);\n (end.sub(8) as *mut u64).write_unaligned(val);\n } else if remaining >= 4 {\n // 4-7 bytes remaining\n (beg as *mut u32).write_unaligned(val as u32);\n (end.sub(4) as *mut u32).write_unaligned(val as u32);\n } else if remaining >= 2 {\n // 2-3 bytes remaining\n (beg as *mut u16).write_unaligned(val as u16);\n (end.sub(2) as *mut u16).write_unaligned(val as u16);\n } else if remaining >= 1 {\n // 1 byte remaining\n beg.write(val as u8);\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::fmt;\n use std::ops::Not;\n\n use super::*;\n\n fn check_memset(val: T, len: usize)\n where\n T: MemsetSafe + Not + PartialEq + fmt::Debug,\n {\n let mut buf = vec![!val; len];\n memset(&mut buf, val);\n assert!(buf.iter().all(|&x| x == val));\n }\n\n #[test]\n fn test_memset_empty() {\n check_memset(0u8, 0);\n check_memset(0u16, 0);\n check_memset(0u32, 0);\n check_memset(0u64, 0);\n }\n\n #[test]\n fn test_memset_single() {\n check_memset(0u8, 1);\n check_memset(0xFFu8, 1);\n check_memset(0xABu16, 1);\n check_memset(0x12345678u32, 1);\n check_memset(0xDEADBEEFu64, 1);\n }\n\n #[test]\n fn test_memset_small() {\n for &len in &[2, 3, 4, 5, 7, 8, 9] {\n check_memset(0xAAu8, len);\n check_memset(0xBEEFu16, len);\n check_memset(0xCAFEBABEu32, len);\n check_memset(0x1234567890ABCDEFu64, len);\n }\n }\n\n #[test]\n fn test_memset_large() {\n check_memset(0u8, 1000);\n check_memset(0xFFu8, 1024);\n check_memset(0xBEEFu16, 512);\n check_memset(0xCAFEBABEu32, 256);\n check_memset(0x1234567890ABCDEFu64, 128);\n }\n\n #[test]\n fn test_memset_various_values() {\n check_memset(0u8, 17);\n check_memset(0x7Fu8, 17);\n check_memset(0x8001u16, 17);\n check_memset(0xFFFFFFFFu32, 17);\n check_memset(0x8000000000000001u64, 17);\n }\n\n #[test]\n fn test_memset_signed_types() {\n check_memset(-1i8, 8);\n check_memset(-2i16, 8);\n check_memset(-3i32, 8);\n check_memset(-4i64, 8);\n check_memset(-5isize, 8);\n }\n\n #[test]\n fn test_memset_usize_isize() {\n check_memset(0usize, 4);\n check_memset(usize::MAX, 4);\n check_memset(0isize, 4);\n check_memset(isize::MIN, 4);\n }\n\n #[test]\n fn test_memset_alignment() {\n // Check that memset works for slices not aligned to 8 bytes\n let mut buf = [0u8; 15];\n for offset in 0..8 {\n let slice = &mut buf[offset..(offset + 7)];\n memset(slice, 0x5A);\n assert!(slice.iter().all(|&x| x == 0x5A));\n }\n }\n}\n"], ["/edit/src/simd/lines_bwd.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ptr;\n\nuse crate::helpers::CoordType;\n\n/// Starting from the `offset` in `haystack` with a current line index of\n/// `line`, this seeks backwards to the `line_stop`-nth line and returns the\n/// new offset and the line index at that point.\n///\n/// Note that this function differs from `lines_fwd` in that it\n/// seeks backwards even if the `line` is already at `line_stop`.\n/// This allows you to ensure (or test) whether `offset` is at a line start.\n///\n/// It returns an offset *past* a newline and thus at the start of a line.\npub fn lines_bwd(\n haystack: &[u8],\n offset: usize,\n line: CoordType,\n line_stop: CoordType,\n) -> (usize, CoordType) {\n unsafe {\n let beg = haystack.as_ptr();\n let it = beg.add(offset.min(haystack.len()));\n let (it, line) = lines_bwd_raw(beg, it, line, line_stop);\n (it.offset_from_unsigned(beg), line)\n }\n}\n\nunsafe fn lines_bwd_raw(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n #[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { LINES_BWD_DISPATCH(beg, end, line, line_stop) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { lines_bwd_neon(beg, end, line, line_stop) };\n\n #[allow(unreachable_code)]\n return unsafe { lines_bwd_fallback(beg, end, line, line_stop) };\n}\n\nunsafe fn lines_bwd_fallback(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n while !ptr::eq(end, beg) {\n let n = end.sub(1);\n if *n == b'\\n' {\n if line <= line_stop {\n break;\n }\n line -= 1;\n }\n end = n;\n }\n (end, line)\n }\n}\n\n#[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut LINES_BWD_DISPATCH: unsafe fn(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) = lines_bwd_dispatch;\n\n#[cfg(target_arch = \"x86_64\")]\nunsafe fn lines_bwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n let func = if is_x86_feature_detected!(\"avx2\") { lines_bwd_avx2 } else { lines_bwd_fallback };\n unsafe { LINES_BWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"x86_64\")]\n#[target_feature(enable = \"avx2\")]\nunsafe fn lines_bwd_avx2(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::x86_64::*;\n\n #[inline(always)]\n unsafe fn horizontal_sum_i64(v: __m256i) -> i64 {\n unsafe {\n let hi = _mm256_extracti128_si256::<1>(v);\n let lo = _mm256_castsi256_si128(v);\n let sum = _mm_add_epi64(lo, hi);\n let shuf = _mm_shuffle_epi32::<0b11_10_11_10>(sum);\n let sum = _mm_add_epi64(sum, shuf);\n _mm_cvtsi128_si64(sum)\n }\n }\n\n let lf = _mm256_set1_epi8(b'\\n' as i8);\n let off = end.addr() & 31;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 128 {\n let chunk_start = end.sub(128);\n\n let v1 = _mm256_loadu_si256(chunk_start.add(0) as *const _);\n let v2 = _mm256_loadu_si256(chunk_start.add(32) as *const _);\n let v3 = _mm256_loadu_si256(chunk_start.add(64) as *const _);\n let v4 = _mm256_loadu_si256(chunk_start.add(96) as *const _);\n\n let mut sum = _mm256_setzero_si256();\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v1, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v2, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v3, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v4, lf));\n\n let sum = _mm256_sad_epu8(sum, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let chunk_start = end.sub(32);\n let v = _mm256_loadu_si256(chunk_start as *const _);\n let c = _mm256_cmpeq_epi8(v, lf);\n\n let ones = _mm256_and_si256(c, _mm256_set1_epi8(0x01));\n let sum = _mm256_sad_epu8(ones, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn lines_bwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n lines_bwd_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n lines_bwd_lsx\n } else {\n lines_bwd_fallback\n };\n unsafe { LINES_BWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn lines_bwd_lasx(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v32i8) -> u32 {\n unsafe {\n let sum = lasx_xvhaddw_h_b(sum, sum);\n let sum = lasx_xvhaddw_w_h(sum, sum);\n let sum = lasx_xvhaddw_d_w(sum, sum);\n let sum = lasx_xvhaddw_q_d(sum, sum);\n let tmp = lasx_xvpermi_q::<1>(T(sum), T(sum));\n let sum = lasx_xvadd_w(T(sum), T(tmp));\n lasx_xvpickve2gr_wu::<0>(sum)\n }\n }\n\n let lf = lasx_xvrepli_b(b'\\n' as i32);\n let line_stop = line_stop.min(line);\n let off = end.addr() & 31;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 128 {\n let chunk_start = end.sub(128);\n\n let v1 = lasx_xvld::<0>(chunk_start as *const _);\n let v2 = lasx_xvld::<32>(chunk_start as *const _);\n let v3 = lasx_xvld::<64>(chunk_start as *const _);\n let v4 = lasx_xvld::<96>(chunk_start as *const _);\n\n let mut sum = lasx_xvrepli_b(0);\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v1, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v2, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v3, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let chunk_start = end.sub(32);\n let v = lasx_xvld::<0>(chunk_start as *const _);\n let c = lasx_xvseq_b(v, lf);\n\n let ones = lasx_xvand_v(T(c), T(lasx_xvrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn lines_bwd_lsx(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v16i8) -> u32 {\n unsafe {\n let sum = lsx_vhaddw_h_b(sum, sum);\n let sum = lsx_vhaddw_w_h(sum, sum);\n let sum = lsx_vhaddw_d_w(sum, sum);\n let sum = lsx_vhaddw_q_d(sum, sum);\n lsx_vpickve2gr_wu::<0>(T(sum))\n }\n }\n\n let lf = lsx_vrepli_b(b'\\n' as i32);\n let line_stop = line_stop.min(line);\n let off = end.addr() & 15;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 64 {\n let chunk_start = end.sub(64);\n\n let v1 = lsx_vld::<0>(chunk_start as *const _);\n let v2 = lsx_vld::<16>(chunk_start as *const _);\n let v3 = lsx_vld::<32>(chunk_start as *const _);\n let v4 = lsx_vld::<48>(chunk_start as *const _);\n\n let mut sum = lsx_vrepli_b(0);\n sum = lsx_vsub_b(sum, lsx_vseq_b(v1, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v2, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v3, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let chunk_start = end.sub(16);\n let v = lsx_vld::<0>(chunk_start as *const _);\n let c = lsx_vseq_b(v, lf);\n\n let ones = lsx_vand_v(T(c), T(lsx_vrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn lines_bwd_neon(\n beg: *const u8,\n mut end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::aarch64::*;\n\n let lf = vdupq_n_u8(b'\\n');\n let line_stop = line_stop.min(line);\n let off = end.addr() & 15;\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (end, line) = lines_bwd_fallback(end.sub(off), end, line, line_stop);\n }\n\n while end.offset_from_unsigned(beg) >= 64 {\n let chunk_start = end.sub(64);\n\n let v1 = vld1q_u8(chunk_start.add(0));\n let v2 = vld1q_u8(chunk_start.add(16));\n let v3 = vld1q_u8(chunk_start.add(32));\n let v4 = vld1q_u8(chunk_start.add(48));\n\n let mut sum = vdupq_n_u8(0);\n sum = vsubq_u8(sum, vceqq_u8(v1, lf));\n sum = vsubq_u8(sum, vceqq_u8(v2, lf));\n sum = vsubq_u8(sum, vceqq_u8(v3, lf));\n sum = vsubq_u8(sum, vceqq_u8(v4, lf));\n\n let sum = vaddvq_u8(sum);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let chunk_start = end.sub(16);\n let v = vld1q_u8(chunk_start);\n let c = vceqq_u8(v, lf);\n let c = vandq_u8(c, vdupq_n_u8(0x01));\n let sum = vaddvq_u8(c);\n\n let line_next = line - sum as CoordType;\n if line_next <= line_stop {\n break;\n }\n\n end = chunk_start;\n line = line_next;\n }\n\n lines_bwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n use crate::helpers::CoordType;\n use crate::simd::test::*;\n\n #[test]\n fn pseudo_fuzz() {\n let text = generate_random_text(1024);\n let lines = count_lines(&text);\n let mut offset_rng = make_rng();\n let mut line_rng = make_rng();\n let mut line_distance_rng = make_rng();\n\n for _ in 0..1000 {\n let offset = offset_rng() % (text.len() + 1);\n let line_stop = line_distance_rng() % (lines + 1);\n let line = (line_stop + line_rng() % 100).saturating_sub(5);\n\n let line = line as CoordType;\n let line_stop = line_stop as CoordType;\n\n let expected = reference_lines_bwd(text.as_bytes(), offset, line, line_stop);\n let actual = lines_bwd(text.as_bytes(), offset, line, line_stop);\n\n assert_eq!(expected, actual);\n }\n }\n\n fn reference_lines_bwd(\n haystack: &[u8],\n mut offset: usize,\n mut line: CoordType,\n line_stop: CoordType,\n ) -> (usize, CoordType) {\n while offset > 0 {\n let c = haystack[offset - 1];\n if c == b'\\n' {\n if line <= line_stop {\n break;\n }\n line -= 1;\n }\n offset -= 1;\n }\n (offset, line)\n }\n\n #[test]\n fn seeks_to_start() {\n for i in 6..=11 {\n let (off, line) = lines_bwd(b\"Hello\\nWorld\\n\", i, 123, 456);\n assert_eq!(off, 6); // After \"Hello\\n\"\n assert_eq!(line, 123); // Still on the same line\n }\n }\n}\n"], ["/edit/src/base64.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Base64 facilities.\n\nuse crate::arena::ArenaString;\n\nconst CHARSET: [u8; 64] = *b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/// One aspect of base64 is that the encoded length can be\n/// calculated accurately in advance, which is what this returns.\n#[inline]\npub fn encode_len(src_len: usize) -> usize {\n src_len.div_ceil(3) * 4\n}\n\n/// Encodes the given bytes as base64 and appends them to the destination string.\npub fn encode(dst: &mut ArenaString, src: &[u8]) {\n unsafe {\n let mut inp = src.as_ptr();\n let mut remaining = src.len();\n let dst = dst.as_mut_vec();\n\n let out_len = encode_len(src.len());\n // ... we can then use this fact to reserve space all at once.\n dst.reserve(out_len);\n\n // SAFETY: Getting a pointer to the reserved space is only safe\n // *after* calling `reserve()` as it may change the pointer.\n let mut out = dst.as_mut_ptr().add(dst.len());\n\n if remaining != 0 {\n // Translate chunks of 3 source bytes into 4 base64-encoded bytes.\n while remaining > 3 {\n // SAFETY: Thanks to `remaining > 3`, reading 4 bytes at once is safe.\n // This improves performance massively over a byte-by-byte approach,\n // because it allows us to byte-swap the read and use simple bit-shifts below.\n let val = u32::from_be((inp as *const u32).read_unaligned());\n inp = inp.add(3);\n remaining -= 3;\n\n *out = CHARSET[(val >> 26) as usize];\n out = out.add(1);\n *out = CHARSET[(val >> 20) as usize & 0x3f];\n out = out.add(1);\n *out = CHARSET[(val >> 14) as usize & 0x3f];\n out = out.add(1);\n *out = CHARSET[(val >> 8) as usize & 0x3f];\n out = out.add(1);\n }\n\n // Convert the remaining 1-3 bytes.\n let mut in1 = 0;\n let mut in2 = 0;\n\n // We can simplify the following logic by assuming that there's only 1\n // byte left. If there's >1 byte left, these two '=' will be overwritten.\n *out.add(3) = b'=';\n *out.add(2) = b'=';\n\n if remaining >= 3 {\n in2 = inp.add(2).read() as usize;\n *out.add(3) = CHARSET[in2 & 0x3f];\n }\n\n if remaining >= 2 {\n in1 = inp.add(1).read() as usize;\n *out.add(2) = CHARSET[(in1 << 2 | in2 >> 6) & 0x3f];\n }\n\n let in0 = inp.add(0).read() as usize;\n *out.add(1) = CHARSET[(in0 << 4 | in1 >> 4) & 0x3f];\n *out.add(0) = CHARSET[in0 >> 2];\n }\n\n dst.set_len(dst.len() + out_len);\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::encode;\n use crate::arena::{Arena, ArenaString};\n\n #[test]\n fn test_basic() {\n let arena = Arena::new(4 * 1024).unwrap();\n let enc = |s: &[u8]| {\n let mut dst = ArenaString::new_in(&arena);\n encode(&mut dst, s);\n dst\n };\n assert_eq!(enc(b\"\"), \"\");\n assert_eq!(enc(b\"a\"), \"YQ==\");\n assert_eq!(enc(b\"ab\"), \"YWI=\");\n assert_eq!(enc(b\"abc\"), \"YWJj\");\n assert_eq!(enc(b\"abcd\"), \"YWJjZA==\");\n assert_eq!(enc(b\"abcde\"), \"YWJjZGU=\");\n assert_eq!(enc(b\"abcdef\"), \"YWJjZGVm\");\n assert_eq!(enc(b\"abcdefg\"), \"YWJjZGVmZw==\");\n assert_eq!(enc(b\"abcdefgh\"), \"YWJjZGVmZ2g=\");\n assert_eq!(enc(b\"abcdefghi\"), \"YWJjZGVmZ2hp\");\n assert_eq!(enc(b\"abcdefghij\"), \"YWJjZGVmZ2hpag==\");\n assert_eq!(enc(b\"abcdefghijk\"), \"YWJjZGVmZ2hpams=\");\n assert_eq!(enc(b\"abcdefghijkl\"), \"YWJjZGVmZ2hpamts\");\n assert_eq!(enc(b\"abcdefghijklm\"), \"YWJjZGVmZ2hpamtsbQ==\");\n assert_eq!(enc(b\"abcdefghijklmN\"), \"YWJjZGVmZ2hpamtsbU4=\");\n assert_eq!(enc(b\"abcdefghijklmNO\"), \"YWJjZGVmZ2hpamtsbU5P\");\n assert_eq!(enc(b\"abcdefghijklmNOP\"), \"YWJjZGVmZ2hpamtsbU5PUA==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQ\"), \"YWJjZGVmZ2hpamtsbU5PUFE=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQR\"), \"YWJjZGVmZ2hpamtsbU5PUFFS\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRS\"), \"YWJjZGVmZ2hpamtsbU5PUFFSUw==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRST\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1Q=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTU\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RV\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUV\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVg==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVW\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVlc=\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWX\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldY\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWXY\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldYWQ==\");\n assert_eq!(enc(b\"abcdefghijklmNOPQRSTUVWXYZ\"), \"YWJjZGVmZ2hpamtsbU5PUFFSU1RVVldYWVo=\");\n }\n}\n"], ["/edit/src/simd/lines_fwd.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ptr;\n\nuse crate::helpers::CoordType;\n\n/// Starting from the `offset` in `haystack` with a current line index of\n/// `line`, this seeks to the `line_stop`-nth line and returns the\n/// new offset and the line index at that point.\n///\n/// It returns an offset *past* the newline.\n/// If `line` is already at or past `line_stop`, it returns immediately.\npub fn lines_fwd(\n haystack: &[u8],\n offset: usize,\n line: CoordType,\n line_stop: CoordType,\n) -> (usize, CoordType) {\n unsafe {\n let beg = haystack.as_ptr();\n let end = beg.add(haystack.len());\n let it = beg.add(offset.min(haystack.len()));\n let (it, line) = lines_fwd_raw(it, end, line, line_stop);\n (it.offset_from_unsigned(beg), line)\n }\n}\n\nunsafe fn lines_fwd_raw(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n #[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\n return unsafe { LINES_FWD_DISPATCH(beg, end, line, line_stop) };\n\n #[cfg(target_arch = \"aarch64\")]\n return unsafe { lines_fwd_neon(beg, end, line, line_stop) };\n\n #[allow(unreachable_code)]\n return unsafe { lines_fwd_fallback(beg, end, line, line_stop) };\n}\n\nunsafe fn lines_fwd_fallback(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n if line < line_stop {\n while !ptr::eq(beg, end) {\n let c = *beg;\n beg = beg.add(1);\n if c == b'\\n' {\n line += 1;\n if line == line_stop {\n break;\n }\n }\n }\n }\n (beg, line)\n }\n}\n\n#[cfg(any(target_arch = \"x86_64\", target_arch = \"loongarch64\"))]\nstatic mut LINES_FWD_DISPATCH: unsafe fn(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) = lines_fwd_dispatch;\n\n#[cfg(target_arch = \"x86_64\")]\nunsafe fn lines_fwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n let func = if is_x86_feature_detected!(\"avx2\") { lines_fwd_avx2 } else { lines_fwd_fallback };\n unsafe { LINES_FWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"x86_64\")]\n#[target_feature(enable = \"avx2\")]\nunsafe fn lines_fwd_avx2(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::x86_64::*;\n\n #[inline(always)]\n unsafe fn horizontal_sum_i64(v: __m256i) -> i64 {\n unsafe {\n let hi = _mm256_extracti128_si256::<1>(v);\n let lo = _mm256_castsi256_si128(v);\n let sum = _mm_add_epi64(lo, hi);\n let shuf = _mm_shuffle_epi32::<0b11_10_11_10>(sum);\n let sum = _mm_add_epi64(sum, shuf);\n _mm_cvtsi128_si64(sum)\n }\n }\n\n let lf = _mm256_set1_epi8(b'\\n' as i8);\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n // Unrolling the loop by 4x speeds things up by >3x.\n // It allows us to accumulate matches before doing a single `vpsadbw`.\n while end.offset_from_unsigned(beg) >= 128 {\n let v1 = _mm256_loadu_si256(beg.add(0) as *const _);\n let v2 = _mm256_loadu_si256(beg.add(32) as *const _);\n let v3 = _mm256_loadu_si256(beg.add(64) as *const _);\n let v4 = _mm256_loadu_si256(beg.add(96) as *const _);\n\n // `vpcmpeqb` leaves each comparison result byte as 0 or -1 (0xff).\n // This allows us to accumulate the comparisons by subtracting them.\n let mut sum = _mm256_setzero_si256();\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v1, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v2, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v3, lf));\n sum = _mm256_sub_epi8(sum, _mm256_cmpeq_epi8(v4, lf));\n\n // Calculate the total number of matches in this chunk.\n let sum = _mm256_sad_epu8(sum, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(128);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = _mm256_loadu_si256(beg as *const _);\n let c = _mm256_cmpeq_epi8(v, lf);\n\n // If you ask an LLM, the best way to do this is\n // to do a `vpmovmskb` followed by `popcnt`.\n // One contemporary hardware that's a bad idea though.\n let ones = _mm256_and_si256(c, _mm256_set1_epi8(0x01));\n let sum = _mm256_sad_epu8(ones, _mm256_setzero_si256());\n let sum = horizontal_sum_i64(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(32);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\nunsafe fn lines_fwd_dispatch(\n beg: *const u8,\n end: *const u8,\n line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n use std::arch::is_loongarch_feature_detected;\n\n let func = if is_loongarch_feature_detected!(\"lasx\") {\n lines_fwd_lasx\n } else if is_loongarch_feature_detected!(\"lsx\") {\n lines_fwd_lsx\n } else {\n lines_fwd_fallback\n };\n unsafe { LINES_FWD_DISPATCH = func };\n unsafe { func(beg, end, line, line_stop) }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lasx\")]\nunsafe fn lines_fwd_lasx(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v32i8) -> u32 {\n unsafe {\n let sum = lasx_xvhaddw_h_b(sum, sum);\n let sum = lasx_xvhaddw_w_h(sum, sum);\n let sum = lasx_xvhaddw_d_w(sum, sum);\n let sum = lasx_xvhaddw_q_d(sum, sum);\n let tmp = lasx_xvpermi_q::<1>(T(sum), T(sum));\n let sum = lasx_xvadd_w(T(sum), T(tmp));\n lasx_xvpickve2gr_wu::<0>(sum)\n }\n }\n\n let lf = lasx_xvrepli_b(b'\\n' as i32);\n let off = beg.align_offset(32);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 128 {\n let v1 = lasx_xvld::<0>(beg as *const _);\n let v2 = lasx_xvld::<32>(beg as *const _);\n let v3 = lasx_xvld::<64>(beg as *const _);\n let v4 = lasx_xvld::<96>(beg as *const _);\n\n let mut sum = lasx_xvrepli_b(0);\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v1, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v2, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v3, lf));\n sum = lasx_xvsub_b(sum, lasx_xvseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(128);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 32 {\n let v = lasx_xvld::<0>(beg as *const _);\n let c = lasx_xvseq_b(v, lf);\n\n let ones = lasx_xvand_v(T(c), T(lasx_xvrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(32);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"loongarch64\")]\n#[target_feature(enable = \"lsx\")]\nunsafe fn lines_fwd_lsx(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::loongarch64::*;\n use std::mem::transmute as T;\n\n #[inline(always)]\n unsafe fn horizontal_sum(sum: v16i8) -> u32 {\n unsafe {\n let sum = lsx_vhaddw_h_b(sum, sum);\n let sum = lsx_vhaddw_w_h(sum, sum);\n let sum = lsx_vhaddw_d_w(sum, sum);\n let sum = lsx_vhaddw_q_d(sum, sum);\n lsx_vpickve2gr_wu::<0>(T(sum))\n }\n }\n\n let lf = lsx_vrepli_b(b'\\n' as i32);\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 64 {\n let v1 = lsx_vld::<0>(beg as *const _);\n let v2 = lsx_vld::<16>(beg as *const _);\n let v3 = lsx_vld::<32>(beg as *const _);\n let v4 = lsx_vld::<48>(beg as *const _);\n\n let mut sum = lsx_vrepli_b(0);\n sum = lsx_vsub_b(sum, lsx_vseq_b(v1, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v2, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v3, lf));\n sum = lsx_vsub_b(sum, lsx_vseq_b(v4, lf));\n let sum = horizontal_sum(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(64);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = lsx_vld::<0>(beg as *const _);\n let c = lsx_vseq_b(v, lf);\n\n let ones = lsx_vand_v(T(c), T(lsx_vrepli_b(1)));\n let sum = horizontal_sum(T(ones));\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(16);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(target_arch = \"aarch64\")]\nunsafe fn lines_fwd_neon(\n mut beg: *const u8,\n end: *const u8,\n mut line: CoordType,\n line_stop: CoordType,\n) -> (*const u8, CoordType) {\n unsafe {\n use std::arch::aarch64::*;\n\n let lf = vdupq_n_u8(b'\\n');\n let off = beg.align_offset(16);\n if off != 0 && off < end.offset_from_unsigned(beg) {\n (beg, line) = lines_fwd_fallback(beg, beg.add(off), line, line_stop);\n }\n\n if line < line_stop {\n while end.offset_from_unsigned(beg) >= 64 {\n let v1 = vld1q_u8(beg.add(0));\n let v2 = vld1q_u8(beg.add(16));\n let v3 = vld1q_u8(beg.add(32));\n let v4 = vld1q_u8(beg.add(48));\n\n // `vceqq_u8` leaves each comparison result byte as 0 or -1 (0xff).\n // This allows us to accumulate the comparisons by subtracting them.\n let mut sum = vdupq_n_u8(0);\n sum = vsubq_u8(sum, vceqq_u8(v1, lf));\n sum = vsubq_u8(sum, vceqq_u8(v2, lf));\n sum = vsubq_u8(sum, vceqq_u8(v3, lf));\n sum = vsubq_u8(sum, vceqq_u8(v4, lf));\n\n let sum = vaddvq_u8(sum);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(64);\n line = line_next;\n }\n\n while end.offset_from_unsigned(beg) >= 16 {\n let v = vld1q_u8(beg);\n let c = vceqq_u8(v, lf);\n let c = vandq_u8(c, vdupq_n_u8(0x01));\n let sum = vaddvq_u8(c);\n\n let line_next = line + sum as CoordType;\n if line_next >= line_stop {\n break;\n }\n\n beg = beg.add(16);\n line = line_next;\n }\n }\n\n lines_fwd_fallback(beg, end, line, line_stop)\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n use crate::helpers::CoordType;\n use crate::simd::test::*;\n\n #[test]\n fn pseudo_fuzz() {\n let text = generate_random_text(1024);\n let lines = count_lines(&text);\n let mut offset_rng = make_rng();\n let mut line_rng = make_rng();\n let mut line_distance_rng = make_rng();\n\n for _ in 0..1000 {\n let offset = offset_rng() % (text.len() + 1);\n let line = line_rng() % 100;\n let line_stop = (line + line_distance_rng() % (lines + 1)).saturating_sub(5);\n\n let line = line as CoordType;\n let line_stop = line_stop as CoordType;\n\n let expected = reference_lines_fwd(text.as_bytes(), offset, line, line_stop);\n let actual = lines_fwd(text.as_bytes(), offset, line, line_stop);\n\n assert_eq!(expected, actual);\n }\n }\n\n fn reference_lines_fwd(\n haystack: &[u8],\n mut offset: usize,\n mut line: CoordType,\n line_stop: CoordType,\n ) -> (usize, CoordType) {\n if line < line_stop {\n while offset < haystack.len() {\n let c = haystack[offset];\n offset += 1;\n if c == b'\\n' {\n line += 1;\n if line == line_stop {\n break;\n }\n }\n }\n }\n (offset, line)\n }\n}\n"], ["/edit/src/buffer/line_cache.rs", "use std::ops::Range;\n\nuse crate::{document::ReadableDocument, simd::memchr2};\n\n/// Cache a line/offset pair every CACHE_EVERY lines to speed up line/offset calculations\nconst CACHE_EVERY: usize = 1024 * 64;\n\n#[derive(Clone)]\npub struct CachePoint {\n pub index: usize,\n pub line: usize,\n // pub snapshot: ParserSnapshot\n}\n\npub struct LineCache {\n cache: Vec,\n}\n\nimpl LineCache {\n pub fn new() -> Self {\n Self { cache: vec![] }\n }\n\n pub fn from_document(&mut self, document: &T) {\n self.cache.clear();\n\n let mut offset = 0;\n let mut line = 0;\n loop {\n let text = document.read_forward(offset);\n if text.is_empty() { return; }\n \n let mut off = 0;\n loop {\n off = memchr2(b'\\n', b'\\n', text, off);\n if off == text.len() { break; }\n\n if line % CACHE_EVERY == 0 {\n self.cache.push(CachePoint { index: offset+off, line });\n }\n line += 1;\n off += 1;\n }\n\n offset += text.len();\n }\n }\n\n /// Updates the cache after a deletion.\n /// `range` is the deleted byte range, and `text` is the content that was deleted.\n pub fn delete(&mut self, range: Range, text: &Vec) {\n let mut newlines = 0;\n for c in text {\n if *c == b'\\n' {\n newlines += 1;\n }\n }\n\n let mut beg_del = None;\n let mut end_del = None;\n for (i, point) in self.cache.iter_mut().enumerate() {\n if point.index >= range.start {\n if point.index < range.end {\n // cache point is within the deleted range\n if beg_del.is_none() { beg_del = Some(i); }\n end_del = Some(i + 1);\n }\n else {\n point.index -= text.len();\n point.line -= newlines;\n }\n }\n }\n\n if let (Some(beg), Some(end)) = (beg_del, end_del) {\n self.cache.drain(beg..end);\n }\n }\n\n /// Updates the cache after an insertion.\n /// `offset` is where the insertion occurs, and `text` is the inserted content.\n pub fn insert(&mut self, offset: usize, text: &[u8]) {\n // Count how many newlines were inserted\n let mut newlines = 0;\n for c in text {\n if *c == b'\\n' {\n newlines += 1;\n }\n }\n\n let len = text.len();\n for point in &mut self.cache {\n if point.index > offset {\n point.index += len;\n point.line += newlines;\n }\n }\n\n // TODO: This also needs to insert new cache points\n }\n\n /// Finds the nearest cached line-offset pair relative to a target line.\n /// If `reverse` is false, it returns the closest *before* the target.\n /// If `reverse` is true, it returns the closest *after or at* the target.\n pub fn nearest_offset(&self, target_count: usize, reverse: bool) -> Option {\n match self.cache.binary_search_by_key(&target_count, |p| p.line) {\n Ok(i) => Some(self.cache[i].clone()),\n Err(i) => {\n if i == 0 || i == self.cache.len() { None } // target < lowest cache point || target > highest cache point\n else {\n Some(self.cache[ if reverse {i} else {i-1} ].clone())\n }\n }\n }\n }\n}\n"], ["/edit/src/bin/edit/draw_statusbar.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena::scratch_arena;\nuse edit::framebuffer::{Attributes, IndexedColor};\nuse edit::fuzzy::score_fuzzy;\nuse edit::helpers::*;\nuse edit::input::vk;\nuse edit::tui::*;\nuse edit::{arena_format, icu};\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_statusbar(ctx: &mut Context, state: &mut State) {\n ctx.table_begin(\"statusbar\");\n ctx.attr_focus_well();\n ctx.attr_background_rgba(state.menubar_color_bg);\n ctx.attr_foreground_rgba(state.menubar_color_fg);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n ctx.attr_padding(Rect::two(0, 1));\n\n if let Some(doc) = state.documents.active() {\n let mut tb = doc.buffer.borrow_mut();\n\n ctx.table_next_row();\n\n if ctx.button(\"newline\", if tb.is_crlf() { \"CRLF\" } else { \"LF\" }, ButtonStyle::default()) {\n let is_crlf = tb.is_crlf();\n tb.normalize_newlines(!is_crlf);\n }\n if state.wants_statusbar_focus {\n state.wants_statusbar_focus = false;\n ctx.steal_focus();\n }\n\n state.wants_encoding_picker |=\n ctx.button(\"encoding\", tb.encoding(), ButtonStyle::default());\n if state.wants_encoding_picker {\n if doc.path.is_some() {\n ctx.block_begin(\"frame\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 1.0,\n offset_x: 0.0,\n offset_y: 0.0,\n });\n ctx.attr_padding(Rect::two(0, 1));\n ctx.attr_border();\n {\n if ctx.button(\"reopen\", loc(LocId::EncodingReopen), ButtonStyle::default()) {\n state.wants_encoding_change = StateEncodingChange::Reopen;\n }\n ctx.focus_on_first_present();\n if ctx.button(\"convert\", loc(LocId::EncodingConvert), ButtonStyle::default()) {\n state.wants_encoding_change = StateEncodingChange::Convert;\n }\n }\n ctx.block_end();\n } else {\n // Can't reopen a file that doesn't exist.\n state.wants_encoding_change = StateEncodingChange::Convert;\n }\n\n if !ctx.contains_focus() {\n state.wants_encoding_picker = false;\n ctx.needs_rerender();\n }\n }\n\n state.wants_indentation_picker |= ctx.button(\n \"indentation\",\n &arena_format!(\n ctx.arena(),\n \"{}:{}\",\n loc(if tb.indent_with_tabs() {\n LocId::IndentationTabs\n } else {\n LocId::IndentationSpaces\n }),\n tb.tab_size(),\n ),\n ButtonStyle::default(),\n );\n if state.wants_indentation_picker {\n ctx.table_begin(\"indentation-picker\");\n ctx.attr_float(FloatSpec {\n anchor: Anchor::Last,\n gravity_x: 0.0,\n gravity_y: 1.0,\n offset_x: 0.0,\n offset_y: 0.0,\n });\n ctx.attr_border();\n ctx.attr_padding(Rect::two(0, 1));\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n {\n if ctx.contains_focus() && ctx.consume_shortcut(vk::RETURN) {\n ctx.toss_focus_up();\n }\n\n ctx.table_next_row();\n\n ctx.list_begin(\"type\");\n ctx.focus_on_first_present();\n ctx.attr_padding(Rect::two(0, 1));\n {\n if ctx.list_item(tb.indent_with_tabs(), loc(LocId::IndentationTabs))\n != ListSelection::Unchanged\n {\n tb.set_indent_with_tabs(true);\n ctx.needs_rerender();\n }\n if ctx.list_item(!tb.indent_with_tabs(), loc(LocId::IndentationSpaces))\n != ListSelection::Unchanged\n {\n tb.set_indent_with_tabs(false);\n ctx.needs_rerender();\n }\n }\n ctx.list_end();\n\n ctx.list_begin(\"width\");\n ctx.attr_padding(Rect::two(0, 2));\n {\n for width in 1u8..=8 {\n let ch = [b'0' + width];\n let label = unsafe { std::str::from_utf8_unchecked(&ch) };\n\n if ctx.list_item(tb.tab_size() == width as CoordType, label)\n != ListSelection::Unchanged\n {\n tb.set_tab_size(width as CoordType);\n ctx.needs_rerender();\n }\n }\n }\n ctx.list_end();\n }\n ctx.table_end();\n\n if !ctx.contains_focus() {\n state.wants_indentation_picker = false;\n ctx.needs_rerender();\n }\n }\n\n ctx.label(\n \"location\",\n &arena_format!(\n ctx.arena(),\n \"{}:{}\",\n tb.cursor_logical_pos().y + 1,\n tb.cursor_logical_pos().x + 1\n ),\n );\n\n #[cfg(feature = \"debug-latency\")]\n ctx.label(\n \"stats\",\n &arena_format!(ctx.arena(), \"{}/{}\", tb.logical_line_count(), tb.visual_line_count(),),\n );\n\n if tb.is_overtype() && ctx.button(\"overtype\", \"OVR\", ButtonStyle::default()) {\n tb.set_overtype(false);\n ctx.needs_rerender();\n }\n\n if tb.is_dirty() {\n ctx.label(\"dirty\", \"*\");\n }\n\n ctx.block_begin(\"filename-container\");\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n {\n let total = state.documents.len();\n let mut filename = doc.filename.as_str();\n let filename_buf;\n\n if total > 1 {\n filename_buf = arena_format!(ctx.arena(), \"{} + {}\", filename, total - 1);\n filename = &filename_buf;\n }\n\n state.wants_go_to_file |= ctx.button(\"filename\", filename, ButtonStyle::default());\n ctx.inherit_focus();\n ctx.attr_overflow(Overflow::TruncateMiddle);\n ctx.attr_position(Position::Right);\n }\n ctx.block_end();\n } else {\n state.wants_statusbar_focus = false;\n state.wants_encoding_picker = false;\n state.wants_indentation_picker = false;\n }\n\n ctx.table_end();\n}\n\npub fn draw_dialog_encoding_change(ctx: &mut Context, state: &mut State) {\n let encoding = state.documents.active_mut().map_or(\"\", |doc| doc.buffer.borrow().encoding());\n let reopen = state.wants_encoding_change == StateEncodingChange::Reopen;\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n let mut change = None;\n let mut done = encoding.is_empty();\n\n ctx.modal_begin(\n \"encode\",\n if reopen { loc(LocId::EncodingReopen) } else { loc(LocId::EncodingConvert) },\n );\n {\n ctx.table_begin(\"encoding-search\");\n ctx.table_set_columns(&[0, COORD_TYPE_SAFE_MAX]);\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n ctx.inherit_focus();\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n ctx.label(\"needle-label\", loc(LocId::SearchNeedleLabel));\n\n if ctx.editline(\"needle\", &mut state.encoding_picker_needle) {\n encoding_picker_update_list(state);\n }\n ctx.inherit_focus();\n }\n ctx.table_end();\n\n ctx.scrollarea_begin(\"scrollarea\", Size { width, height });\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n {\n ctx.list_begin(\"encodings\");\n ctx.inherit_focus();\n\n for enc in state\n .encoding_picker_results\n .as_deref()\n .unwrap_or_else(|| icu::get_available_encodings().preferred)\n {\n if ctx.list_item(enc.canonical == encoding, enc.label) == ListSelection::Activated {\n change = Some(enc.canonical);\n break;\n }\n ctx.attr_overflow(Overflow::TruncateTail);\n }\n ctx.list_end();\n }\n ctx.scrollarea_end();\n }\n done |= ctx.modal_end();\n done |= change.is_some();\n\n if let Some(encoding) = change\n && let Some(doc) = state.documents.active_mut()\n {\n if reopen && doc.path.is_some() {\n let mut res = Ok(());\n if doc.buffer.borrow().is_dirty() {\n res = doc.save(None);\n }\n if res.is_ok() {\n res = doc.reread(Some(encoding));\n }\n if let Err(err) = res {\n error_log_add(ctx, state, err);\n }\n } else {\n doc.buffer.borrow_mut().set_encoding(encoding);\n }\n }\n\n if done {\n state.wants_encoding_change = StateEncodingChange::None;\n state.encoding_picker_needle.clear();\n state.encoding_picker_results = None;\n ctx.needs_rerender();\n }\n}\n\nfn encoding_picker_update_list(state: &mut State) {\n state.encoding_picker_results = None;\n\n let needle = state.encoding_picker_needle.trim_ascii();\n if needle.is_empty() {\n return;\n }\n\n let encodings = icu::get_available_encodings();\n let scratch = scratch_arena(None);\n let mut matches = Vec::new_in(&*scratch);\n\n for enc in encodings.all {\n let local_scratch = scratch_arena(Some(&scratch));\n let (score, _) = score_fuzzy(&local_scratch, enc.label, needle, true);\n\n if score > 0 {\n matches.push((score, *enc));\n }\n }\n\n matches.sort_by(|a, b| b.0.cmp(&a.0));\n state.encoding_picker_results = Some(Vec::from_iter(matches.iter().map(|(_, enc)| *enc)));\n}\n\npub fn draw_go_to_file(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"go-to-file\", loc(LocId::ViewGoToFile));\n {\n let width = (ctx.size().width - 20).max(10);\n let height = (ctx.size().height - 10).max(10);\n\n ctx.scrollarea_begin(\"scrollarea\", Size { width, height });\n ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));\n ctx.inherit_focus();\n {\n ctx.list_begin(\"documents\");\n ctx.inherit_focus();\n\n if state.documents.update_active(|doc| {\n let tb = doc.buffer.borrow();\n\n ctx.styled_list_item_begin();\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.styled_label_add_text(if tb.is_dirty() { \"* \" } else { \" \" });\n ctx.styled_label_add_text(&doc.filename);\n\n if let Some(path) = &doc.dir {\n ctx.styled_label_add_text(\" \");\n ctx.styled_label_set_attributes(Attributes::Italic);\n ctx.styled_label_add_text(path.as_str());\n }\n\n ctx.styled_list_item_end(false) == ListSelection::Activated\n }) {\n state.wants_go_to_file = false;\n ctx.needs_rerender();\n }\n\n ctx.list_end();\n }\n ctx.scrollarea_end();\n }\n if ctx.modal_end() {\n state.wants_go_to_file = false;\n }\n}\n"], ["/edit/src/buffer/navigation.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Range;\n\nuse crate::document::ReadableDocument;\n\n#[derive(Clone, Copy, PartialEq, Eq)]\nenum CharClass {\n Whitespace,\n Newline,\n Separator,\n Word,\n}\n\nconst fn construct_classifier(separators: &[u8]) -> [CharClass; 256] {\n let mut classifier = [CharClass::Word; 256];\n\n classifier[b' ' as usize] = CharClass::Whitespace;\n classifier[b'\\t' as usize] = CharClass::Whitespace;\n classifier[b'\\n' as usize] = CharClass::Newline;\n classifier[b'\\r' as usize] = CharClass::Newline;\n\n let mut i = 0;\n let len = separators.len();\n while i < len {\n let ch = separators[i];\n assert!(ch < 128, \"Only ASCII separators are supported.\");\n classifier[ch as usize] = CharClass::Separator;\n i += 1;\n }\n\n classifier\n}\n\nconst WORD_CLASSIFIER: [CharClass; 256] =\n construct_classifier(br#\"`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?\"#);\n\n/// Finds the next word boundary given a document cursor offset.\n/// Returns the offset of the next word boundary.\npub fn word_forward(doc: &dyn ReadableDocument, offset: usize) -> usize {\n word_navigation(WordForward { doc, offset, chunk: &[], chunk_off: 0 })\n}\n\n/// The backward version of `word_forward`.\npub fn word_backward(doc: &dyn ReadableDocument, offset: usize) -> usize {\n word_navigation(WordBackward { doc, offset, chunk: &[], chunk_off: 0 })\n}\n\n/// Word navigation implementation. Matches the behavior of VS Code.\nfn word_navigation(mut nav: T) -> usize {\n // First, fill `self.chunk` with at least 1 grapheme.\n nav.read();\n\n // Skip one newline, if any.\n nav.skip_newline();\n\n // Skip any whitespace.\n nav.skip_class(CharClass::Whitespace);\n\n // Skip one word or separator and take note of the class.\n let class = nav.peek(CharClass::Whitespace);\n if matches!(class, CharClass::Separator | CharClass::Word) {\n nav.next();\n\n let off = nav.offset();\n\n // Continue skipping the same class.\n nav.skip_class(class);\n\n // If the class was a separator and we only moved one character,\n // continue skipping characters of the word class.\n if off == nav.offset() && class == CharClass::Separator {\n nav.skip_class(CharClass::Word);\n }\n }\n\n nav.offset()\n}\n\ntrait WordNavigation {\n fn read(&mut self);\n fn skip_newline(&mut self);\n fn skip_class(&mut self, class: CharClass);\n fn peek(&self, default: CharClass) -> CharClass;\n fn next(&mut self);\n fn offset(&self) -> usize;\n}\n\nstruct WordForward<'a> {\n doc: &'a dyn ReadableDocument,\n offset: usize,\n chunk: &'a [u8],\n chunk_off: usize,\n}\n\nimpl WordNavigation for WordForward<'_> {\n fn read(&mut self) {\n self.chunk = self.doc.read_forward(self.offset);\n self.chunk_off = 0;\n }\n\n fn skip_newline(&mut self) {\n // We can rely on the fact that the document does not split graphemes across chunks.\n // = If there's a newline it's wholly contained in this chunk.\n // Unlike with `WordBackward`, we can't check for CR and LF separately as only a CR followed\n // by a LF is a newline. A lone CR in the document is just a regular control character.\n self.chunk_off += match self.chunk.get(self.chunk_off) {\n Some(&b'\\n') => 1,\n Some(&b'\\r') if self.chunk.get(self.chunk_off + 1) == Some(&b'\\n') => 2,\n _ => 0,\n }\n }\n\n fn skip_class(&mut self, class: CharClass) {\n while !self.chunk.is_empty() {\n while self.chunk_off < self.chunk.len() {\n if WORD_CLASSIFIER[self.chunk[self.chunk_off] as usize] != class {\n return;\n }\n self.chunk_off += 1;\n }\n\n self.offset += self.chunk.len();\n self.chunk = self.doc.read_forward(self.offset);\n self.chunk_off = 0;\n }\n }\n\n fn peek(&self, default: CharClass) -> CharClass {\n if self.chunk_off < self.chunk.len() {\n WORD_CLASSIFIER[self.chunk[self.chunk_off] as usize]\n } else {\n default\n }\n }\n\n fn next(&mut self) {\n self.chunk_off += 1;\n }\n\n fn offset(&self) -> usize {\n self.offset + self.chunk_off\n }\n}\n\nstruct WordBackward<'a> {\n doc: &'a dyn ReadableDocument,\n offset: usize,\n chunk: &'a [u8],\n chunk_off: usize,\n}\n\nimpl WordNavigation for WordBackward<'_> {\n fn read(&mut self) {\n self.chunk = self.doc.read_backward(self.offset);\n self.chunk_off = self.chunk.len();\n }\n\n fn skip_newline(&mut self) {\n // We can rely on the fact that the document does not split graphemes across chunks.\n // = If there's a newline it's wholly contained in this chunk.\n if self.chunk_off > 0 && self.chunk[self.chunk_off - 1] == b'\\n' {\n self.chunk_off -= 1;\n }\n if self.chunk_off > 0 && self.chunk[self.chunk_off - 1] == b'\\r' {\n self.chunk_off -= 1;\n }\n }\n\n fn skip_class(&mut self, class: CharClass) {\n while !self.chunk.is_empty() {\n while self.chunk_off > 0 {\n if WORD_CLASSIFIER[self.chunk[self.chunk_off - 1] as usize] != class {\n return;\n }\n self.chunk_off -= 1;\n }\n\n self.offset -= self.chunk.len();\n self.chunk = self.doc.read_backward(self.offset);\n self.chunk_off = self.chunk.len();\n }\n }\n\n fn peek(&self, default: CharClass) -> CharClass {\n if self.chunk_off > 0 {\n WORD_CLASSIFIER[self.chunk[self.chunk_off - 1] as usize]\n } else {\n default\n }\n }\n\n fn next(&mut self) {\n self.chunk_off -= 1;\n }\n\n fn offset(&self) -> usize {\n self.offset - self.chunk.len() + self.chunk_off\n }\n}\n\n/// Returns the offset range of the \"word\" at the given offset.\n/// Does not cross newlines. Works similar to VS Code.\npub fn word_select(doc: &dyn ReadableDocument, offset: usize) -> Range {\n let mut beg = offset;\n let mut end = offset;\n let mut class = CharClass::Newline;\n\n let mut chunk = doc.read_forward(end);\n if !chunk.is_empty() {\n // Not at the end of the document? Great!\n // We default to using the next char as the class, because in terminals\n // the cursor is usually always to the left of the cell you clicked on.\n class = WORD_CLASSIFIER[chunk[0] as usize];\n\n let mut chunk_off = 0;\n\n // Select the word, unless we hit a newline.\n if class != CharClass::Newline {\n loop {\n chunk_off += 1;\n end += 1;\n\n if chunk_off >= chunk.len() {\n chunk = doc.read_forward(end);\n chunk_off = 0;\n if chunk.is_empty() {\n break;\n }\n }\n\n if WORD_CLASSIFIER[chunk[chunk_off] as usize] != class {\n break;\n }\n }\n }\n }\n\n let mut chunk = doc.read_backward(beg);\n if !chunk.is_empty() {\n let mut chunk_off = chunk.len();\n\n // If we failed to determine the class, because we hit the end of the document\n // or a newline, we fall back to using the previous character, of course.\n if class == CharClass::Newline {\n class = WORD_CLASSIFIER[chunk[chunk_off - 1] as usize];\n }\n\n // Select the word, unless we hit a newline.\n if class != CharClass::Newline {\n loop {\n if WORD_CLASSIFIER[chunk[chunk_off - 1] as usize] != class {\n break;\n }\n\n chunk_off -= 1;\n beg -= 1;\n\n if chunk_off == 0 {\n chunk = doc.read_backward(beg);\n chunk_off = chunk.len();\n if chunk.is_empty() {\n break;\n }\n }\n }\n }\n }\n\n beg..end\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn test_word_navigation() {\n assert_eq!(word_forward(&\"Hello World\".as_bytes(), 0), 5);\n assert_eq!(word_forward(&\"Hello,World\".as_bytes(), 0), 5);\n assert_eq!(word_forward(&\" Hello\".as_bytes(), 0), 8);\n assert_eq!(word_forward(&\"\\n\\nHello\".as_bytes(), 0), 1);\n\n assert_eq!(word_backward(&\"Hello World\".as_bytes(), 11), 6);\n assert_eq!(word_backward(&\"Hello,World\".as_bytes(), 10), 6);\n assert_eq!(word_backward(&\"Hello \".as_bytes(), 7), 0);\n assert_eq!(word_backward(&\"Hello\\n\\n\".as_bytes(), 7), 6);\n }\n}\n"], ["/edit/src/arena/debug.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![allow(clippy::missing_safety_doc, clippy::mut_from_ref)]\n\nuse std::alloc::{AllocError, Allocator, Layout};\nuse std::mem::{self, MaybeUninit};\nuse std::ptr::NonNull;\n\nuse super::release;\nuse crate::apperr;\n\n/// A debug wrapper for [`release::Arena`].\n///\n/// The problem with [`super::ScratchArena`] is that it only \"borrows\" an underlying\n/// [`release::Arena`]. Once the [`super::ScratchArena`] is dropped it resets the watermark\n/// of the underlying [`release::Arena`], freeing all allocations done since borrowing it.\n///\n/// It is completely valid for the same [`release::Arena`] to be borrowed multiple times at once,\n/// *as long as* you only use the most recent borrow. Bad example:\n/// ```should_panic\n/// use edit::arena::scratch_arena;\n///\n/// let mut scratch1 = scratch_arena(None);\n/// let mut scratch2 = scratch_arena(None);\n///\n/// let foo = scratch1.alloc_uninit::();\n///\n/// // This will also reset `scratch1`'s allocation.\n/// drop(scratch2);\n///\n/// *foo; // BOOM! ...if it wasn't for our debug wrapper.\n/// ```\n///\n/// To avoid this, this wraps the real [`release::Arena`] in a \"debug\" one, which pretends as if every\n/// instance of itself is a distinct [`release::Arena`] instance. Then we use this \"debug\" [`release::Arena`]\n/// for [`super::ScratchArena`] which allows us to track which borrow is the most recent one.\npub enum Arena {\n // Delegate is 'static, because release::Arena requires no lifetime\n // annotations, and so this mere debug helper cannot use them either.\n Delegated { delegate: &'static release::Arena, borrow: usize },\n Owned { arena: release::Arena },\n}\n\nimpl Drop for Arena {\n fn drop(&mut self) {\n if let Self::Delegated { delegate, borrow } = self {\n let borrows = delegate.borrows.get();\n assert_eq!(*borrow, borrows);\n delegate.borrows.set(borrows - 1);\n }\n }\n}\n\nimpl Default for Arena {\n fn default() -> Self {\n Self::empty()\n }\n}\n\nimpl Arena {\n pub const fn empty() -> Self {\n Self::Owned { arena: release::Arena::empty() }\n }\n\n pub fn new(capacity: usize) -> apperr::Result {\n Ok(Self::Owned { arena: release::Arena::new(capacity)? })\n }\n\n pub(super) fn delegated(delegate: &release::Arena) -> Self {\n let borrow = delegate.borrows.get() + 1;\n delegate.borrows.set(borrow);\n Self::Delegated { delegate: unsafe { mem::transmute(delegate) }, borrow }\n }\n\n #[inline]\n pub(super) fn delegate_target(&self) -> &release::Arena {\n match *self {\n Self::Delegated { delegate, borrow } => {\n assert!(\n borrow == delegate.borrows.get(),\n \"Arena already borrowed by a newer ScratchArena\"\n );\n delegate\n }\n Self::Owned { ref arena } => arena,\n }\n }\n\n #[inline]\n pub(super) fn delegate_target_unchecked(&self) -> &release::Arena {\n match self {\n Self::Delegated { delegate, .. } => delegate,\n Self::Owned { arena } => arena,\n }\n }\n\n pub fn offset(&self) -> usize {\n self.delegate_target().offset()\n }\n\n pub unsafe fn reset(&self, to: usize) {\n unsafe { self.delegate_target().reset(to) }\n }\n\n pub fn alloc_uninit(&self) -> &mut MaybeUninit {\n self.delegate_target().alloc_uninit()\n }\n\n pub fn alloc_uninit_slice(&self, count: usize) -> &mut [MaybeUninit] {\n self.delegate_target().alloc_uninit_slice(count)\n }\n}\n\nunsafe impl Allocator for Arena {\n fn allocate(&self, layout: Layout) -> Result, AllocError> {\n self.delegate_target().alloc_raw(layout.size(), layout.align())\n }\n\n fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> {\n self.delegate_target().allocate_zeroed(layout)\n }\n\n // While it is possible to shrink the tail end of the arena, it is\n // not very useful given the existence of scoped scratch arenas.\n unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) {\n unsafe { self.delegate_target().deallocate(ptr, layout) }\n }\n\n unsafe fn grow(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().grow(ptr, old_layout, new_layout) }\n }\n\n unsafe fn grow_zeroed(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().grow_zeroed(ptr, old_layout, new_layout) }\n }\n\n unsafe fn shrink(\n &self,\n ptr: NonNull,\n old_layout: Layout,\n new_layout: Layout,\n ) -> Result, AllocError> {\n unsafe { self.delegate_target().shrink(ptr, old_layout, new_layout) }\n }\n}\n"], ["/edit/src/arena/scratch.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::ops::Deref;\n\n#[cfg(debug_assertions)]\nuse super::debug;\nuse super::{Arena, release};\nuse crate::apperr;\nuse crate::helpers::*;\n\nstatic mut S_SCRATCH: [release::Arena; 2] =\n const { [release::Arena::empty(), release::Arena::empty()] };\n\n/// Initialize the scratch arenas with a given capacity.\n/// Call this before using [`scratch_arena`].\npub fn init(capacity: usize) -> apperr::Result<()> {\n unsafe {\n for s in &mut S_SCRATCH[..] {\n *s = release::Arena::new(capacity)?;\n }\n }\n Ok(())\n}\n\n/// Need an arena for temporary allocations? [`scratch_arena`] got you covered.\n/// Call [`scratch_arena`] and it'll return an [`Arena`] that resets when it goes out of scope.\n///\n/// ---\n///\n/// Most methods make just two kinds of allocations:\n/// * Interior: Temporary data that can be deallocated when the function returns.\n/// * Exterior: Data that is returned to the caller and must remain alive until the caller stops using it.\n///\n/// Such methods only have two lifetimes, for which you consequently also only need two arenas.\n/// ...even if your method calls other methods recursively! This is because the exterior allocations\n/// of a callee are simply interior allocations to the caller, and so on, recursively.\n///\n/// This works as long as the two arenas flip/flop between being used as interior/exterior allocator\n/// along the callstack. To ensure that is the case, we use a recursion counter in debug builds.\n///\n/// This approach was described among others at: \n///\n/// # Safety\n///\n/// If your function takes an [`Arena`] argument, you **MUST** pass it to `scratch_arena` as `Some(&arena)`.\npub fn scratch_arena(conflict: Option<&Arena>) -> ScratchArena<'static> {\n unsafe {\n #[cfg(test)]\n if S_SCRATCH[0].is_empty() {\n init(128 * 1024 * 1024).unwrap();\n }\n\n #[cfg(debug_assertions)]\n let conflict = conflict.map(|a| a.delegate_target_unchecked());\n\n let index = opt_ptr_eq(conflict, Some(&S_SCRATCH[0])) as usize;\n let arena = &S_SCRATCH[index];\n ScratchArena::new(arena)\n }\n}\n\n/// Borrows an [`Arena`] for temporary allocations.\n///\n/// See [`scratch_arena`].\n#[cfg(debug_assertions)]\npub struct ScratchArena<'a> {\n arena: debug::Arena,\n offset: usize,\n _phantom: std::marker::PhantomData<&'a ()>,\n}\n\n#[cfg(not(debug_assertions))]\npub struct ScratchArena<'a> {\n arena: &'a Arena,\n offset: usize,\n}\n\n#[cfg(debug_assertions)]\nimpl<'a> ScratchArena<'a> {\n fn new(arena: &'a release::Arena) -> Self {\n let offset = arena.offset();\n ScratchArena { arena: Arena::delegated(arena), _phantom: std::marker::PhantomData, offset }\n }\n}\n\n#[cfg(not(debug_assertions))]\nimpl<'a> ScratchArena<'a> {\n fn new(arena: &'a release::Arena) -> Self {\n let offset = arena.offset();\n ScratchArena { arena, offset }\n }\n}\n\nimpl Drop for ScratchArena<'_> {\n fn drop(&mut self) {\n unsafe { self.arena.reset(self.offset) };\n }\n}\n\n#[cfg(debug_assertions)]\nimpl Deref for ScratchArena<'_> {\n type Target = debug::Arena;\n\n fn deref(&self) -> &Self::Target {\n &self.arena\n }\n}\n\n#[cfg(not(debug_assertions))]\nimpl Deref for ScratchArena<'_> {\n type Target = Arena;\n\n fn deref(&self) -> &Self::Target {\n self.arena\n }\n}\n"], ["/edit/src/document.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Abstractions over reading/writing arbitrary text containers.\n\nuse std::ffi::OsString;\nuse std::mem;\nuse std::ops::Range;\nuse std::path::PathBuf;\n\nuse crate::arena::{ArenaString, scratch_arena};\nuse crate::helpers::ReplaceRange as _;\n\n/// An abstraction over reading from text containers.\npub trait ReadableDocument {\n /// Read some bytes starting at (including) the given absolute offset.\n ///\n /// # Warning\n ///\n /// * Be lenient on inputs:\n /// * The given offset may be out of bounds and you MUST clamp it.\n /// * You should not assume that offsets are at grapheme cluster boundaries.\n /// * Be strict on outputs:\n /// * You MUST NOT break grapheme clusters across chunks.\n /// * You MUST NOT return an empty slice unless the offset is at or beyond the end.\n fn read_forward(&self, off: usize) -> &[u8];\n\n /// Read some bytes before (but not including) the given absolute offset.\n ///\n /// # Warning\n ///\n /// * Be lenient on inputs:\n /// * The given offset may be out of bounds and you MUST clamp it.\n /// * You should not assume that offsets are at grapheme cluster boundaries.\n /// * Be strict on outputs:\n /// * You MUST NOT break grapheme clusters across chunks.\n /// * You MUST NOT return an empty slice unless the offset is zero.\n fn read_backward(&self, off: usize) -> &[u8];\n}\n\n/// An abstraction over writing to text containers.\npub trait WriteableDocument: ReadableDocument {\n /// Replace the given range with the given bytes.\n ///\n /// # Warning\n ///\n /// * The given range may be out of bounds and you MUST clamp it.\n /// * The replacement may not be valid UTF8.\n fn replace(&mut self, range: Range, replacement: &[u8]);\n}\n\nimpl ReadableDocument for &[u8] {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = *self;\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = *self;\n &s[..off.min(s.len())]\n }\n}\n\nimpl ReadableDocument for String {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = self.as_bytes();\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = self.as_bytes();\n &s[..off.min(s.len())]\n }\n}\n\nimpl WriteableDocument for String {\n fn replace(&mut self, range: Range, replacement: &[u8]) {\n // `replacement` is not guaranteed to be valid UTF-8, so we need to sanitize it.\n let scratch = scratch_arena(None);\n let utf8 = ArenaString::from_utf8_lossy(&scratch, replacement);\n let src = match &utf8 {\n Ok(s) => s,\n Err(s) => s.as_str(),\n };\n\n // SAFETY: `range` is guaranteed to be on codepoint boundaries.\n unsafe { self.as_mut_vec() }.replace_range(range, src.as_bytes());\n }\n}\n\nimpl ReadableDocument for PathBuf {\n fn read_forward(&self, off: usize) -> &[u8] {\n let s = self.as_os_str().as_encoded_bytes();\n &s[off.min(s.len())..]\n }\n\n fn read_backward(&self, off: usize) -> &[u8] {\n let s = self.as_os_str().as_encoded_bytes();\n &s[..off.min(s.len())]\n }\n}\n\nimpl WriteableDocument for PathBuf {\n fn replace(&mut self, range: Range, replacement: &[u8]) {\n let mut vec = mem::take(self).into_os_string().into_encoded_bytes();\n vec.replace_range(range, replacement);\n *self = unsafe { Self::from(OsString::from_encoded_bytes_unchecked(vec)) };\n }\n}\n"], ["/edit/src/bin/edit/localization.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena::scratch_arena;\nuse edit::helpers::AsciiStringHelpers;\nuse edit::sys;\n\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum LocId {\n Ctrl,\n Alt,\n Shift,\n\n Ok,\n Yes,\n No,\n Cancel,\n Always,\n\n // File menu\n File,\n FileNew,\n FileOpen,\n FileSave,\n FileSaveAs,\n FileClose,\n FileExit,\n FileGoto,\n\n // Edit menu\n Edit,\n EditUndo,\n EditRedo,\n EditCut,\n EditCopy,\n EditPaste,\n EditFind,\n EditReplace,\n EditSelectAll,\n\n // View menu\n View,\n ViewFocusStatusbar,\n ViewWordWrap,\n ViewGoToFile,\n\n // Help menu\n Help,\n HelpAbout,\n\n // Exit dialog\n UnsavedChangesDialogTitle,\n UnsavedChangesDialogDescription,\n UnsavedChangesDialogYes,\n UnsavedChangesDialogNo,\n\n // About dialog\n AboutDialogTitle,\n AboutDialogVersion,\n\n // Shown when the clipboard size exceeds the limit for OSC 52\n LargeClipboardWarningLine1,\n LargeClipboardWarningLine2,\n LargeClipboardWarningLine3,\n SuperLargeClipboardWarning,\n\n // Warning dialog\n WarningDialogTitle,\n\n // Error dialog\n ErrorDialogTitle,\n ErrorIcuMissing,\n\n SearchNeedleLabel,\n SearchReplacementLabel,\n SearchMatchCase,\n SearchWholeWord,\n SearchUseRegex,\n SearchReplaceAll,\n SearchClose,\n\n EncodingReopen,\n EncodingConvert,\n\n IndentationTabs,\n IndentationSpaces,\n\n SaveAsDialogPathLabel,\n SaveAsDialogNameLabel,\n\n FileOverwriteWarning,\n FileOverwriteWarningDescription,\n\n Count,\n}\n\n#[allow(non_camel_case_types)]\n#[derive(Clone, Copy, PartialEq, Eq)]\nenum LangId {\n // Base language. It's always the first one.\n en,\n\n // Other languages. Sorted alphabetically.\n de,\n es,\n fr,\n it,\n ja,\n ko,\n pt_br,\n ru,\n zh_hans,\n zh_hant,\n\n Count,\n}\n\n#[rustfmt::skip]\nconst S_LANG_LUT: [[&str; LangId::Count as usize]; LocId::Count as usize] = [\n // Ctrl (the keyboard key)\n [\n /* en */ \"Ctrl\",\n /* de */ \"Strg\",\n /* es */ \"Ctrl\",\n /* fr */ \"Ctrl\",\n /* it */ \"Ctrl\",\n /* ja */ \"Ctrl\",\n /* ko */ \"Ctrl\",\n /* pt_br */ \"Ctrl\",\n /* ru */ \"Ctrl\",\n /* zh_hans */ \"Ctrl\",\n /* zh_hant */ \"Ctrl\",\n ],\n // Alt (the keyboard key)\n [\n /* en */ \"Alt\",\n /* de */ \"Alt\",\n /* es */ \"Alt\",\n /* fr */ \"Alt\",\n /* it */ \"Alt\",\n /* ja */ \"Alt\",\n /* ko */ \"Alt\",\n /* pt_br */ \"Alt\",\n /* ru */ \"Alt\",\n /* zh_hans */ \"Alt\",\n /* zh_hant */ \"Alt\",\n ],\n // Shift (the keyboard key)\n [\n /* en */ \"Shift\",\n /* de */ \"Umschalt\",\n /* es */ \"Mayús\",\n /* fr */ \"Maj\",\n /* it */ \"Maiusc\",\n /* ja */ \"Shift\",\n /* ko */ \"Shift\",\n /* pt_br */ \"Shift\",\n /* ru */ \"Shift\",\n /* zh_hans */ \"Shift\",\n /* zh_hant */ \"Shift\",\n ],\n\n // Ok (used as a common dialog button)\n [\n /* en */ \"Ok\",\n /* de */ \"OK\",\n /* es */ \"Aceptar\",\n /* fr */ \"OK\",\n /* it */ \"OK\",\n /* ja */ \"OK\",\n /* ko */ \"확인\",\n /* pt_br */ \"OK\",\n /* ru */ \"ОК\",\n /* zh_hans */ \"确定\",\n /* zh_hant */ \"確定\",\n ],\n // Yes (used as a common dialog button)\n [\n /* en */ \"Yes\",\n /* de */ \"Ja\",\n /* es */ \"Sí\",\n /* fr */ \"Oui\",\n /* it */ \"Sì\",\n /* ja */ \"はい\",\n /* ko */ \"예\",\n /* pt_br */ \"Sim\",\n /* ru */ \"Да\",\n /* zh_hans */ \"是\",\n /* zh_hant */ \"是\",\n ],\n // No (used as a common dialog button)\n [\n /* en */ \"No\",\n /* de */ \"Nein\",\n /* es */ \"No\",\n /* fr */ \"Non\",\n /* it */ \"No\",\n /* ja */ \"いいえ\",\n /* ko */ \"아니오\",\n /* pt_br */ \"Não\",\n /* ru */ \"Нет\",\n /* zh_hans */ \"否\",\n /* zh_hant */ \"否\",\n ],\n // Cancel (used as a common dialog button)\n [\n /* en */ \"Cancel\",\n /* de */ \"Abbrechen\",\n /* es */ \"Cancelar\",\n /* fr */ \"Annuler\",\n /* it */ \"Annulla\",\n /* ja */ \"キャンセル\",\n /* ko */ \"취소\",\n /* pt_br */ \"Cancelar\",\n /* ru */ \"Отмена\",\n /* zh_hans */ \"取消\",\n /* zh_hant */ \"取消\",\n ],\n // Always (used as a common dialog button)\n [\n /* en */ \"Always\",\n /* de */ \"Immer\",\n /* es */ \"Siempre\",\n /* fr */ \"Toujours\",\n /* it */ \"Sempre\",\n /* ja */ \"常に\",\n /* ko */ \"항상\",\n /* pt_br */ \"Sempre\",\n /* ru */ \"Всегда\",\n /* zh_hans */ \"总是\",\n /* zh_hant */ \"總是\",\n ],\n\n // File (a menu bar item)\n [\n /* en */ \"File\",\n /* de */ \"Datei\",\n /* es */ \"Archivo\",\n /* fr */ \"Fichier\",\n /* it */ \"File\",\n /* ja */ \"ファイル\",\n /* ko */ \"파일\",\n /* pt_br */ \"Arquivo\",\n /* ru */ \"Файл\",\n /* zh_hans */ \"文件\",\n /* zh_hant */ \"檔案\",\n ],\n // FileNew\n [\n /* en */ \"New File\",\n /* de */ \"Neue Datei\",\n /* es */ \"Nuevo archivo\",\n /* fr */ \"Nouveau fichier\",\n /* it */ \"Nuovo file\",\n /* ja */ \"新規ファイル\",\n /* ko */ \"새 파일\",\n /* pt_br */ \"Novo arquivo\",\n /* ru */ \"Новый файл\",\n /* zh_hans */ \"新建文件\",\n /* zh_hant */ \"新增檔案\",\n ],\n // FileOpen\n [\n /* en */ \"Open File…\",\n /* de */ \"Datei öffnen…\",\n /* es */ \"Abrir archivo…\",\n /* fr */ \"Ouvrir un fichier…\",\n /* it */ \"Apri file…\",\n /* ja */ \"ファイルを開く…\",\n /* ko */ \"파일 열기…\",\n /* pt_br */ \"Abrir arquivo…\",\n /* ru */ \"Открыть файл…\",\n /* zh_hans */ \"打开文件…\",\n /* zh_hant */ \"開啟檔案…\",\n ],\n // FileSave\n [\n /* en */ \"Save\",\n /* de */ \"Speichern\",\n /* es */ \"Guardar\",\n /* fr */ \"Enregistrer\",\n /* it */ \"Salva\",\n /* ja */ \"保存\",\n /* ko */ \"저장\",\n /* pt_br */ \"Salvar\",\n /* ru */ \"Сохранить\",\n /* zh_hans */ \"保存\",\n /* zh_hant */ \"儲存\",\n ],\n // FileSaveAs\n [\n /* en */ \"Save As…\",\n /* de */ \"Speichern unter…\",\n /* es */ \"Guardar como…\",\n /* fr */ \"Enregistrer sous…\",\n /* it */ \"Salva come…\",\n /* ja */ \"名前を付けて保存…\",\n /* ko */ \"다른 이름으로 저장…\",\n /* pt_br */ \"Salvar como…\",\n /* ru */ \"Сохранить как…\",\n /* zh_hans */ \"另存为…\",\n /* zh_hant */ \"另存新檔…\",\n ],\n // FileClose\n [\n /* en */ \"Close File\",\n /* de */ \"Datei schließen\",\n /* es */ \"Cerrar archivo\",\n /* fr */ \"Fermer le fichier\",\n /* it */ \"Chiudi file\",\n /* ja */ \"ファイルを閉じる\",\n /* ko */ \"파일 닫기\",\n /* pt_br */ \"Fechar arquivo\",\n /* ru */ \"Закрыть файл\",\n /* zh_hans */ \"关闭文件\",\n /* zh_hant */ \"關閉檔案\",\n ],\n // FileExit\n [\n /* en */ \"Exit\",\n /* de */ \"Beenden\",\n /* es */ \"Salir\",\n /* fr */ \"Quitter\",\n /* it */ \"Esci\",\n /* ja */ \"終了\",\n /* ko */ \"종료\",\n /* pt_br */ \"Sair\",\n /* ru */ \"Выход\",\n /* zh_hans */ \"退出\",\n /* zh_hant */ \"退出\",\n ],\n // FileGoto\n [\n /* en */ \"Go to Line:Column…\",\n /* de */ \"Gehe zu Zeile:Spalte…\",\n /* es */ \"Ir a línea:columna…\",\n /* fr */ \"Aller à la ligne:colonne…\",\n /* it */ \"Vai a riga:colonna…\",\n /* ja */ \"行:列へ移動…\",\n /* ko */ \"행:열로 이동…\",\n /* pt_br */ \"Ir para linha:coluna…\",\n /* ru */ \"Перейти к строке:столбцу…\",\n /* zh_hans */ \"转到行:列…\",\n /* zh_hant */ \"跳至行:列…\",\n ],\n\n // Edit (a menu bar item)\n [\n /* en */ \"Edit\",\n /* de */ \"Bearbeiten\",\n /* es */ \"Editar\",\n /* fr */ \"Édition\",\n /* it */ \"Modifica\",\n /* ja */ \"編集\",\n /* ko */ \"편집\",\n /* pt_br */ \"Editar\",\n /* ru */ \"Правка\",\n /* zh_hans */ \"编辑\",\n /* zh_hant */ \"編輯\",\n ],\n // EditUndo\n [\n /* en */ \"Undo\",\n /* de */ \"Rückgängig\",\n /* es */ \"Deshacer\",\n /* fr */ \"Annuler\",\n /* it */ \"Annulla\",\n /* ja */ \"元に戻す\",\n /* ko */ \"실행 취소\",\n /* pt_br */ \"Desfazer\",\n /* ru */ \"Отменить\",\n /* zh_hans */ \"撤销\",\n /* zh_hant */ \"復原\",\n ],\n // EditRedo\n [\n /* en */ \"Redo\",\n /* de */ \"Wiederholen\",\n /* es */ \"Rehacer\",\n /* fr */ \"Rétablir\",\n /* it */ \"Ripeti\",\n /* ja */ \"やり直し\",\n /* ko */ \"다시 실행\",\n /* pt_br */ \"Refazer\",\n /* ru */ \"Повторить\",\n /* zh_hans */ \"重做\",\n /* zh_hant */ \"重做\",\n ],\n // EditCut\n [\n /* en */ \"Cut\",\n /* de */ \"Ausschneiden\",\n /* es */ \"Cortar\",\n /* fr */ \"Couper\",\n /* it */ \"Taglia\",\n /* ja */ \"切り取り\",\n /* ko */ \"잘라내기\",\n /* pt_br */ \"Cortar\",\n /* ru */ \"Вырезать\",\n /* zh_hans */ \"剪切\",\n /* zh_hant */ \"剪下\",\n ],\n // EditCopy\n [\n /* en */ \"Copy\",\n /* de */ \"Kopieren\",\n /* es */ \"Copiar\",\n /* fr */ \"Copier\",\n /* it */ \"Copia\",\n /* ja */ \"コピー\",\n /* ko */ \"복사\",\n /* pt_br */ \"Copiar\",\n /* ru */ \"Копировать\",\n /* zh_hans */ \"复制\",\n /* zh_hant */ \"複製\",\n ],\n // EditPaste\n [\n /* en */ \"Paste\",\n /* de */ \"Einfügen\",\n /* es */ \"Pegar\",\n /* fr */ \"Coller\",\n /* it */ \"Incolla\",\n /* ja */ \"貼り付け\",\n /* ko */ \"붙여넣기\",\n /* pt_br */ \"Colar\",\n /* ru */ \"Вставить\",\n /* zh_hans */ \"粘贴\",\n /* zh_hant */ \"貼上\",\n ],\n // EditFind\n [\n /* en */ \"Find\",\n /* de */ \"Suchen\",\n /* es */ \"Buscar\",\n /* fr */ \"Rechercher\",\n /* it */ \"Trova\",\n /* ja */ \"検索\",\n /* ko */ \"찾기\",\n /* pt_br */ \"Encontrar\",\n /* ru */ \"Найти\",\n /* zh_hans */ \"查找\",\n /* zh_hant */ \"尋找\",\n ],\n // EditReplace\n [\n /* en */ \"Replace\",\n /* de */ \"Ersetzen\",\n /* es */ \"Reemplazar\",\n /* fr */ \"Remplacer\",\n /* it */ \"Sostituisci\",\n /* ja */ \"置換\",\n /* ko */ \"바꾸기\",\n /* pt_br */ \"Substituir\",\n /* ru */ \"Заменить\",\n /* zh_hans */ \"替换\",\n /* zh_hant */ \"取代\",\n ],\n // EditSelectAll\n [\n /* en */ \"Select All\",\n /* de */ \"Alles auswählen\",\n /* es */ \"Seleccionar todo\",\n /* fr */ \"Tout sélectionner\",\n /* it */ \"Seleziona tutto\",\n /* ja */ \"すべて選択\",\n /* ko */ \"모두 선택\",\n /* pt_br */ \"Selecionar tudo\",\n /* ru */ \"Выделить всё\",\n /* zh_hans */ \"全选\",\n /* zh_hant */ \"全選\"\n ],\n\n // View (a menu bar item)\n [\n /* en */ \"View\",\n /* de */ \"Ansicht\",\n /* es */ \"Ver\",\n /* fr */ \"Affichage\",\n /* it */ \"Visualizza\",\n /* ja */ \"表示\",\n /* ko */ \"보기\",\n /* pt_br */ \"Exibir\",\n /* ru */ \"Вид\",\n /* zh_hans */ \"视图\",\n /* zh_hant */ \"檢視\",\n ],\n // ViewFocusStatusbar\n [\n /* en */ \"Focus Statusbar\",\n /* de */ \"Statusleiste fokussieren\",\n /* es */ \"Enfocar barra de estado\",\n /* fr */ \"Activer la barre d’état\",\n /* it */ \"Attiva barra di stato\",\n /* ja */ \"ステータスバーにフォーカス\",\n /* ko */ \"상태 표시줄로 포커스 이동\",\n /* pt_br */ \"Focar barra de status\",\n /* ru */ \"Фокус на строку состояния\",\n /* zh_hans */ \"聚焦状态栏\",\n /* zh_hant */ \"聚焦狀態列\",\n ],\n // ViewWordWrap\n [\n /* en */ \"Word Wrap\",\n /* de */ \"Zeilenumbruch\",\n /* es */ \"Ajuste de línea\",\n /* fr */ \"Retour automatique à la ligne\",\n /* it */ \"A capo automatico\",\n /* ja */ \"折り返し\",\n /* ko */ \"자동 줄 바꿈\",\n /* pt_br */ \"Quebra de linha\",\n /* ru */ \"Перенос слов\",\n /* zh_hans */ \"自动换行\",\n /* zh_hant */ \"自動換行\",\n ],\n // ViewGoToFile\n [\n /* en */ \"Go to File…\",\n /* de */ \"Gehe zu Datei…\",\n /* es */ \"Ir a archivo…\",\n /* fr */ \"Aller au fichier…\",\n /* it */ \"Vai al file…\",\n /* ja */ \"ファイルへ移動…\",\n /* ko */ \"파일로 이동…\",\n /* pt_br */ \"Ir para arquivo…\",\n /* ru */ \"Перейти к файлу…\",\n /* zh_hans */ \"转到文件…\",\n /* zh_hant */ \"跳至檔案…\",\n ],\n\n // Help (a menu bar item)\n [\n /* en */ \"Help\",\n /* de */ \"Hilfe\",\n /* es */ \"Ayuda\",\n /* fr */ \"Aide\",\n /* it */ \"Aiuto\",\n /* ja */ \"ヘルプ\",\n /* ko */ \"도움말\",\n /* pt_br */ \"Ajuda\",\n /* ru */ \"Помощь\",\n /* zh_hans */ \"帮助\",\n /* zh_hant */ \"幫助\",\n ],\n // HelpAbout\n [\n /* en */ \"About\",\n /* de */ \"Über\",\n /* es */ \"Acerca de\",\n /* fr */ \"À propos\",\n /* it */ \"Informazioni\",\n /* ja */ \"情報\",\n /* ko */ \"정보\",\n /* pt_br */ \"Sobre\",\n /* ru */ \"О программе\",\n /* zh_hans */ \"关于\",\n /* zh_hant */ \"關於\",\n ],\n\n // UnsavedChangesDialogTitle\n [\n /* en */ \"Unsaved Changes\",\n /* de */ \"Ungespeicherte Änderungen\",\n /* es */ \"Cambios sin guardar\",\n /* fr */ \"Modifications non enregistrées\",\n /* it */ \"Modifiche non salvate\",\n /* ja */ \"未保存の変更\",\n /* ko */ \"저장되지 않은 변경 사항\",\n /* pt_br */ \"Alterações não salvas\",\n /* ru */ \"Несохраненные изменения\",\n /* zh_hans */ \"未保存的更改\",\n /* zh_hant */ \"未儲存的變更\",\n ],\n // UnsavedChangesDialogDescription\n [\n /* en */ \"Do you want to save the changes you made?\",\n /* de */ \"Möchten Sie die vorgenommenen Änderungen speichern?\",\n /* es */ \"¿Desea guardar los cambios realizados?\",\n /* fr */ \"Voulez-vous enregistrer les modifications apportées ?\",\n /* it */ \"Vuoi salvare le modifiche apportate?\",\n /* ja */ \"変更内容を保存しますか?\",\n /* ko */ \"변경한 내용을 저장하시겠습니까?\",\n /* pt_br */ \"Deseja salvar as alterações feitas?\",\n /* ru */ \"Вы хотите сохранить внесённые изменения?\",\n /* zh_hans */ \"您要保存所做的更改吗?\",\n /* zh_hant */ \"您要保存所做的變更嗎?\",\n ],\n // UnsavedChangesDialogYes\n [\n /* en */ \"Save\",\n /* de */ \"Speichern\",\n /* es */ \"Guardar\",\n /* fr */ \"Enregistrer\",\n /* it */ \"Salva\",\n /* ja */ \"保存する\",\n /* ko */ \"저장\",\n /* pt_br */ \"Salvar\",\n /* ru */ \"Сохранить\",\n /* zh_hans */ \"保存\",\n /* zh_hant */ \"儲存\",\n ],\n // UnsavedChangesDialogNo\n [\n /* en */ \"Don't Save\",\n /* de */ \"Nicht speichern\",\n /* es */ \"No guardar\",\n /* fr */ \"Ne pas enregistrer\",\n /* it */ \"Non salvare\",\n /* ja */ \"保存しない\",\n /* ko */ \"저장 안 함\",\n /* pt_br */ \"Não salvar\",\n /* ru */ \"Не сохранять\",\n /* zh_hans */ \"不保存\",\n /* zh_hant */ \"不儲存\",\n ],\n\n // AboutDialogTitle\n [\n /* en */ \"About\",\n /* de */ \"Über\",\n /* es */ \"Acerca de\",\n /* fr */ \"À propos\",\n /* it */ \"Informazioni\",\n /* ja */ \"情報\",\n /* ko */ \"정보\",\n /* pt_br */ \"Sobre\",\n /* ru */ \"О программе\",\n /* zh_hans */ \"关于\",\n /* zh_hant */ \"關於\",\n ],\n // AboutDialogVersion\n [\n /* en */ \"Version: \",\n /* de */ \"Version: \",\n /* es */ \"Versión: \",\n /* fr */ \"Version : \",\n /* it */ \"Versione: \",\n /* ja */ \"バージョン: \",\n /* ko */ \"버전: \",\n /* pt_br */ \"Versão: \",\n /* ru */ \"Версия: \",\n /* zh_hans */ \"版本: \",\n /* zh_hant */ \"版本: \",\n ],\n\n // Shown when the clipboard size exceeds the limit for OSC 52\n // LargeClipboardWarningLine1\n [\n /* en */ \"Text you copy is shared with the terminal clipboard.\",\n /* de */ \"Der kopierte Text wird mit der Terminal-Zwischenablage geteilt.\",\n /* es */ \"El texto que copies se comparte con el portapapeles del terminal.\",\n /* fr */ \"Le texte que vous copiez est partagé avec le presse-papiers du terminal.\",\n /* it */ \"Il testo copiato viene condiviso con gli appunti del terminale.\",\n /* ja */ \"コピーしたテキストはターミナルのクリップボードと共有されます。\",\n /* ko */ \"복사한 텍스트가 터미널 클립보드와 공유됩니다.\",\n /* pt_br */ \"O texto copiado é compartilhado com a área de transferência do terminal.\",\n /* ru */ \"Скопированный текст передаётся в буфер обмена терминала.\",\n /* zh_hans */ \"你复制的文本将共享到终端剪贴板。\",\n /* zh_hant */ \"您複製的文字將會與終端機剪貼簿分享。\",\n ],\n // LargeClipboardWarningLine2\n [\n /* en */ \"You copied {size} which may take a long time to share.\",\n /* de */ \"Sie haben {size} kopiert. Das Weitergeben könnte länger dauern.\",\n /* es */ \"Copiaste {size}, lo que puede tardar en compartirse.\",\n /* fr */ \"Vous avez copié {size}, ce qui peut être long à partager.\",\n /* it */ \"Hai copiato {size}, potrebbe richiedere molto tempo per condividerlo.\",\n /* ja */ \"{size} をコピーしました。共有に時間がかかる可能性があります。\",\n /* ko */ \"{size}를 복사했습니다. 공유하는 데 시간이 오래 걸릴 수 있습니다.\",\n /* pt_br */ \"Você copiou {size}, o que pode demorar para compartilhar.\",\n /* ru */ \"Вы скопировали {size}; передача может занять много времени.\",\n /* zh_hans */ \"你复制了 {size},共享可能需要较长时间。\",\n /* zh_hant */ \"您已複製 {size},共享可能需要較長時間。\",\n ],\n // LargeClipboardWarningLine3\n [\n /* en */ \"Do you want to send it anyway?\",\n /* de */ \"Möchten Sie es trotzdem senden?\",\n /* es */ \"¿Desea enviarlo de todas formas?\",\n /* fr */ \"Voulez-vous quand même l’envoyer ?\",\n /* it */ \"Vuoi inviarlo comunque?\",\n /* ja */ \"それでも送信しますか?\",\n /* ko */ \"그래도 전송하시겠습니까?\",\n /* pt_br */ \"Deseja enviar mesmo assim?\",\n /* ru */ \"Отправить в любом случае?\",\n /* zh_hans */ \"仍要发送吗?\",\n /* zh_hant */ \"仍要傳送嗎?\",\n ],\n // SuperLargeClipboardWarning (as an alternative to LargeClipboardWarningLine2 and 3)\n [\n /* en */ \"The text you copied is too large to be shared.\",\n /* de */ \"Der kopierte Text ist zu groß, um geteilt zu werden.\",\n /* es */ \"El texto que copiaste es demasiado grande para compartirse.\",\n /* fr */ \"Le texte que vous avez copié est trop volumineux pour être partagé.\",\n /* it */ \"Il testo copiato è troppo grande per essere condiviso.\",\n /* ja */ \"コピーしたテキストは大きすぎて共有できません。\",\n /* ko */ \"복사한 텍스트가 너무 커서 공유할 수 없습니다.\",\n /* pt_br */ \"O texto copiado é grande demais para ser compartilhado.\",\n /* ru */ \"Скопированный текст слишком велик для передачи.\",\n /* zh_hans */ \"你复制的文本过大,无法共享。\",\n /* zh_hant */ \"您複製的文字過大,無法分享。\",\n ],\n\n // WarningDialogTitle\n [\n /* en */ \"Warning\",\n /* de */ \"Warnung\",\n /* es */ \"Advertencia\",\n /* fr */ \"Avertissement\",\n /* it */ \"Avviso\",\n /* ja */ \"警告\",\n /* ko */ \"경고\",\n /* pt_br */ \"Aviso\",\n /* ru */ \"Предупреждение\",\n /* zh_hans */ \"警告\",\n /* zh_hant */ \"警告\",\n ],\n\n // ErrorDialogTitle\n [\n /* en */ \"Error\",\n /* de */ \"Fehler\",\n /* es */ \"Error\",\n /* fr */ \"Erreur\",\n /* it */ \"Errore\",\n /* ja */ \"エラー\",\n /* ko */ \"오류\",\n /* pt_br */ \"Erro\",\n /* ru */ \"Ошибка\",\n /* zh_hans */ \"错误\",\n /* zh_hant */ \"錯誤\",\n ],\n // ErrorIcuMissing\n [\n /* en */ \"This operation requires the ICU library\",\n /* de */ \"Diese Operation erfordert die ICU-Bibliothek\",\n /* es */ \"Esta operación requiere la biblioteca ICU\",\n /* fr */ \"Cette opération nécessite la bibliothèque ICU\",\n /* it */ \"Questa operazione richiede la libreria ICU\",\n /* ja */ \"この操作にはICUライブラリが必要です\",\n /* ko */ \"이 작업에는 ICU 라이브러리가 필요합니다\",\n /* pt_br */ \"Esta operação requer a biblioteca ICU\",\n /* ru */ \"Эта операция требует наличия библиотеки ICU\",\n /* zh_hans */ \"此操作需要 ICU 库\",\n /* zh_hant */ \"此操作需要 ICU 庫\",\n ],\n\n // SearchNeedleLabel (for input field)\n [\n /* en */ \"Find:\",\n /* de */ \"Suchen:\",\n /* es */ \"Buscar:\",\n /* fr */ \"Rechercher :\",\n /* it */ \"Trova:\",\n /* ja */ \"検索:\",\n /* ko */ \"찾기:\",\n /* pt_br */ \"Encontrar:\",\n /* ru */ \"Найти:\",\n /* zh_hans */ \"查找:\",\n /* zh_hant */ \"尋找:\",\n ],\n // SearchReplacementLabel (for input field)\n [\n /* en */ \"Replace:\",\n /* de */ \"Ersetzen:\",\n /* es */ \"Reemplazar:\",\n /* fr */ \"Remplacer :\",\n /* it */ \"Sostituire:\",\n /* ja */ \"置換:\",\n /* ko */ \"바꾸기:\",\n /* pt_br */ \"Substituir:\",\n /* ru */ \"Замена:\",\n /* zh_hans */ \"替换:\",\n /* zh_hant */ \"替換:\",\n ],\n // SearchMatchCase (toggle)\n [\n /* en */ \"Match Case\",\n /* de */ \"Groß/Klein\",\n /* es */ \"May/Min\",\n /* fr */ \"Resp. la casse\",\n /* it */ \"Maius/minus\",\n /* ja */ \"大/小文字を区別\",\n /* ko */ \"대소문자\",\n /* pt_br */ \"Maius/minus\",\n /* ru */ \"Регистр\",\n /* zh_hans */ \"区分大小写\",\n /* zh_hant */ \"區分大小寫\",\n ],\n // SearchWholeWord (toggle)\n [\n /* en */ \"Whole Word\",\n /* de */ \"Ganzes Wort\",\n /* es */ \"Palabra\",\n /* fr */ \"Mot entier\",\n /* it */ \"Parola\",\n /* ja */ \"単語全体\",\n /* ko */ \"전체 단어\",\n /* pt_br */ \"Palavra\",\n /* ru */ \"Слово\",\n /* zh_hans */ \"全字匹配\",\n /* zh_hant */ \"全字匹配\",\n ],\n // SearchUseRegex (toggle)\n [\n /* en */ \"Use Regex\",\n /* de */ \"RegEx\",\n /* es */ \"RegEx\",\n /* fr */ \"RegEx\",\n /* it */ \"RegEx\",\n /* ja */ \"正規表現\",\n /* ko */ \"정규식\",\n /* pt_br */ \"RegEx\",\n /* ru */ \"RegEx\",\n /* zh_hans */ \"正则\",\n /* zh_hant */ \"正則\",\n ],\n // SearchReplaceAll (button)\n [\n /* en */ \"Replace All\",\n /* de */ \"Alle ersetzen\",\n /* es */ \"Reemplazar todo\",\n /* fr */ \"Remplacer tout\",\n /* it */ \"Sostituisci tutto\",\n /* ja */ \"すべて置換\",\n /* ko */ \"모두 바꾸기\",\n /* pt_br */ \"Substituir tudo\",\n /* ru */ \"Заменить все\",\n /* zh_hans */ \"全部替换\",\n /* zh_hant */ \"全部取代\",\n ],\n // SearchClose (button)\n [\n /* en */ \"Close\",\n /* de */ \"Schließen\",\n /* es */ \"Cerrar\",\n /* fr */ \"Fermer\",\n /* it */ \"Chiudi\",\n /* ja */ \"閉じる\",\n /* ko */ \"닫기\",\n /* pt_br */ \"Fechar\",\n /* ru */ \"Закрыть\",\n /* zh_hans */ \"关闭\",\n /* zh_hant */ \"關閉\",\n ],\n\n // EncodingReopen\n [\n /* en */ \"Reopen with encoding…\",\n /* de */ \"Mit Kodierung erneut öffnen…\",\n /* es */ \"Reabrir con codificación…\",\n /* fr */ \"Rouvrir avec un encodage différent…\",\n /* it */ \"Riapri con codifica…\",\n /* ja */ \"指定エンコーディングで再度開く…\",\n /* ko */ \"인코딩으로 다시 열기…\",\n /* pt_br */ \"Reabrir com codificação…\",\n /* ru */ \"Открыть снова с кодировкой…\",\n /* zh_hans */ \"使用编码重新打开…\",\n /* zh_hant */ \"使用編碼重新打開…\",\n ],\n // EncodingConvert\n [\n /* en */ \"Convert to encoding…\",\n /* de */ \"In Kodierung konvertieren…\",\n /* es */ \"Convertir a otra codificación…\",\n /* fr */ \"Convertir vers l’encodage…\",\n /* it */ \"Converti in codifica…\",\n /* ja */ \"エンコーディングを変換…\",\n /* ko */ \"인코딩으로 변환…\",\n /* pt_br */ \"Converter para codificação…\",\n /* ru */ \"Преобразовать в кодировку…\",\n /* zh_hans */ \"转换为编码…\",\n /* zh_hant */ \"轉換為編碼…\",\n ],\n\n // IndentationTabs\n [\n /* en */ \"Tabs\",\n /* de */ \"Tabs\",\n /* es */ \"Tabulaciones\",\n /* fr */ \"Tabulations\",\n /* it */ \"Tabulazioni\",\n /* ja */ \"タブ\",\n /* ko */ \"탭\",\n /* pt_br */ \"Tabulações\",\n /* ru */ \"Табы\",\n /* zh_hans */ \"制表符\",\n /* zh_hant */ \"製表符\",\n ],\n // IndentationSpaces\n [\n /* en */ \"Spaces\",\n /* de */ \"Leerzeichen\",\n /* es */ \"Espacios\",\n /* fr */ \"Espaces\",\n /* it */ \"Spazi\",\n /* ja */ \"スペース\",\n /* ko */ \"공백\",\n /* pt_br */ \"Espaços\",\n /* ru */ \"Пробелы\",\n /* zh_hans */ \"空格\",\n /* zh_hant */ \"空格\",\n ],\n\n // SaveAsDialogPathLabel\n [\n /* en */ \"Folder:\",\n /* de */ \"Ordner:\",\n /* es */ \"Carpeta:\",\n /* fr */ \"Dossier :\",\n /* it */ \"Cartella:\",\n /* ja */ \"フォルダ:\",\n /* ko */ \"폴더:\",\n /* pt_br */ \"Pasta:\",\n /* ru */ \"Папка:\",\n /* zh_hans */ \"文件夹:\",\n /* zh_hant */ \"資料夾:\",\n ],\n // SaveAsDialogNameLabel\n [\n /* en */ \"File name:\",\n /* de */ \"Dateiname:\",\n /* es */ \"Nombre de archivo:\",\n /* fr */ \"Nom du fichier :\",\n /* it */ \"Nome del file:\",\n /* ja */ \"ファイル名:\",\n /* ko */ \"파일 이름:\",\n /* pt_br */ \"Nome do arquivo:\",\n /* ru */ \"Имя файла:\",\n /* zh_hans */ \"文件名:\",\n /* zh_hant */ \"檔案名稱:\",\n ],\n\n // FileOverwriteWarning\n [\n /* en */ \"Confirm Save As\",\n /* de */ \"Speichern unter bestätigen\",\n /* es */ \"Confirmar Guardar como\",\n /* fr */ \"Confirmer Enregistrer sous\",\n /* it */ \"Conferma Salva con nome\",\n /* ja */ \"名前を付けて保存の確認\",\n /* ko */ \"다른 이름으로 저장 확인\",\n /* pt_br */ \"Confirmar Salvar como\",\n /* ru */ \"Подтвердите «Сохранить как…»\",\n /* zh_hans */ \"确认另存为\",\n /* zh_hant */ \"確認另存新檔\",\n ],\n // FileOverwriteWarningDescription\n [\n /* en */ \"File already exists. Do you want to overwrite it?\",\n /* de */ \"Datei existiert bereits. Möchten Sie sie überschreiben?\",\n /* es */ \"El archivo ya existe. ¿Desea sobrescribirlo?\",\n /* fr */ \"Le fichier existe déjà. Voulez-vous l’écraser ?\",\n /* it */ \"Il file esiste già. Vuoi sovrascriverlo?\",\n /* ja */ \"ファイルは既に存在します。上書きしますか?\",\n /* ko */ \"파일이 이미 존재합니다. 덮어쓰시겠습니까?\",\n /* pt_br */ \"O arquivo já existe. Deseja sobrescrevê-lo?\",\n /* ru */ \"Файл уже существует. Перезаписать?\",\n /* zh_hans */ \"文件已存在。要覆盖它吗?\",\n /* zh_hant */ \"檔案已存在。要覆蓋它嗎?\",\n ],\n];\n\nstatic mut S_LANG: LangId = LangId::en;\n\npub fn init() {\n // WARNING:\n // Generic language tags such as \"zh\" MUST be sorted after more specific tags such\n // as \"zh-hant\" to ensure that the prefix match finds the most specific one first.\n const LANG_MAP: &[(&str, LangId)] = &[\n (\"en\", LangId::en),\n // ----------------\n (\"de\", LangId::de),\n (\"es\", LangId::es),\n (\"fr\", LangId::fr),\n (\"it\", LangId::it),\n (\"ja\", LangId::ja),\n (\"ko\", LangId::ko),\n (\"pt-br\", LangId::pt_br),\n (\"ru\", LangId::ru),\n (\"zh-hant\", LangId::zh_hant),\n (\"zh-tw\", LangId::zh_hant),\n (\"zh\", LangId::zh_hans),\n ];\n\n let scratch = scratch_arena(None);\n let langs = sys::preferred_languages(&scratch);\n let mut lang = LangId::en;\n\n 'outer: for l in langs {\n for (prefix, id) in LANG_MAP {\n if l.starts_with_ignore_ascii_case(prefix) {\n lang = *id;\n break 'outer;\n }\n }\n }\n\n unsafe {\n S_LANG = lang;\n }\n}\n\npub fn loc(id: LocId) -> &'static str {\n S_LANG_LUT[id as usize][unsafe { S_LANG as usize }]\n}\n"], ["/edit/src/bin/edit/draw_editor.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse std::num::ParseIntError;\n\nuse edit::framebuffer::IndexedColor;\nuse edit::helpers::*;\nuse edit::icu;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_editor(ctx: &mut Context, state: &mut State) {\n if !matches!(state.wants_search.kind, StateSearchKind::Hidden | StateSearchKind::Disabled) {\n draw_search(ctx, state);\n }\n\n let size = ctx.size();\n // TODO: The layout code should be able to just figure out the height on its own.\n let height_reduction = match state.wants_search.kind {\n StateSearchKind::Search => 4,\n StateSearchKind::Replace => 5,\n _ => 2,\n };\n\n if let Some(doc) = state.documents.active() {\n ctx.textarea(\"textarea\", doc.buffer.clone());\n ctx.inherit_focus();\n } else {\n ctx.block_begin(\"empty\");\n ctx.block_end();\n }\n\n ctx.attr_intrinsic_size(Size { width: 0, height: size.height - height_reduction });\n}\n\nfn draw_search(ctx: &mut Context, state: &mut State) {\n if let Err(err) = icu::init() {\n error_log_add(ctx, state, err);\n state.wants_search.kind = StateSearchKind::Disabled;\n return;\n }\n\n let Some(doc) = state.documents.active() else {\n state.wants_search.kind = StateSearchKind::Hidden;\n return;\n };\n\n let mut action = None;\n let mut focus = StateSearchKind::Hidden;\n\n if state.wants_search.focus {\n state.wants_search.focus = false;\n focus = StateSearchKind::Search;\n\n // If the selection is empty, focus the search input field.\n // Otherwise, focus the replace input field, if it exists.\n if let Some(selection) = doc.buffer.borrow_mut().extract_user_selection(false) {\n state.search_needle = String::from_utf8_lossy_owned(selection);\n focus = state.wants_search.kind;\n }\n }\n\n ctx.block_begin(\"search\");\n ctx.attr_focus_well();\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::White));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::Black));\n {\n if ctx.contains_focus() && ctx.consume_shortcut(vk::ESCAPE) {\n state.wants_search.kind = StateSearchKind::Hidden;\n }\n\n ctx.table_begin(\"needle\");\n ctx.table_set_cell_gap(Size { width: 1, height: 0 });\n {\n {\n ctx.table_next_row();\n ctx.label(\"label\", loc(LocId::SearchNeedleLabel));\n\n if ctx.editline(\"needle\", &mut state.search_needle) {\n action = Some(SearchAction::Search);\n }\n if !state.search_success {\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n }\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n if focus == StateSearchKind::Search {\n ctx.steal_focus();\n }\n if ctx.is_focused() && ctx.consume_shortcut(vk::RETURN) {\n action = Some(SearchAction::Search);\n }\n }\n\n if state.wants_search.kind == StateSearchKind::Replace {\n ctx.table_next_row();\n ctx.label(\"label\", loc(LocId::SearchReplacementLabel));\n\n ctx.editline(\"replacement\", &mut state.search_replacement);\n ctx.attr_intrinsic_size(Size { width: COORD_TYPE_SAFE_MAX, height: 1 });\n if focus == StateSearchKind::Replace {\n ctx.steal_focus();\n }\n if ctx.is_focused() {\n if ctx.consume_shortcut(vk::RETURN) {\n action = Some(SearchAction::Replace);\n } else if ctx.consume_shortcut(kbmod::CTRL_ALT | vk::RETURN) {\n action = Some(SearchAction::ReplaceAll);\n }\n }\n }\n }\n ctx.table_end();\n\n ctx.table_begin(\"options\");\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n let mut change = false;\n let mut change_action = Some(SearchAction::Search);\n\n ctx.table_next_row();\n\n change |= ctx.checkbox(\n \"match-case\",\n loc(LocId::SearchMatchCase),\n &mut state.search_options.match_case,\n );\n change |= ctx.checkbox(\n \"whole-word\",\n loc(LocId::SearchWholeWord),\n &mut state.search_options.whole_word,\n );\n change |= ctx.checkbox(\n \"use-regex\",\n loc(LocId::SearchUseRegex),\n &mut state.search_options.use_regex,\n );\n if state.wants_search.kind == StateSearchKind::Replace\n && ctx.button(\"replace-all\", loc(LocId::SearchReplaceAll), ButtonStyle::default())\n {\n change = true;\n change_action = Some(SearchAction::ReplaceAll);\n }\n if ctx.button(\"close\", loc(LocId::SearchClose), ButtonStyle::default()) {\n state.wants_search.kind = StateSearchKind::Hidden;\n }\n\n if change {\n action = change_action;\n state.wants_search.focus = true;\n ctx.needs_rerender();\n }\n }\n ctx.table_end();\n }\n ctx.block_end();\n\n if let Some(action) = action {\n search_execute(ctx, state, action);\n }\n}\n\npub enum SearchAction {\n Search,\n Replace,\n ReplaceAll,\n}\n\npub fn search_execute(ctx: &mut Context, state: &mut State, action: SearchAction) {\n let Some(doc) = state.documents.active_mut() else {\n return;\n };\n\n state.search_success = match action {\n SearchAction::Search => {\n doc.buffer.borrow_mut().find_and_select(&state.search_needle, state.search_options)\n }\n SearchAction::Replace => doc.buffer.borrow_mut().find_and_replace(\n &state.search_needle,\n state.search_options,\n state.search_replacement.as_bytes(),\n ),\n SearchAction::ReplaceAll => doc.buffer.borrow_mut().find_and_replace_all(\n &state.search_needle,\n state.search_options,\n state.search_replacement.as_bytes(),\n ),\n }\n .is_ok();\n\n ctx.needs_rerender();\n}\n\npub fn draw_handle_save(ctx: &mut Context, state: &mut State) {\n if let Some(doc) = state.documents.active_mut() {\n if doc.path.is_some() {\n if let Err(err) = doc.save(None) {\n error_log_add(ctx, state, err);\n }\n } else {\n // No path? Show the file picker.\n state.wants_file_picker = StateFilePicker::SaveAs;\n state.wants_save = false;\n ctx.needs_rerender();\n }\n }\n\n state.wants_save = false;\n}\n\npub fn draw_handle_wants_close(ctx: &mut Context, state: &mut State) {\n let Some(doc) = state.documents.active() else {\n state.wants_close = false;\n return;\n };\n\n if !doc.buffer.borrow().is_dirty() {\n state.documents.remove_active();\n state.wants_close = false;\n ctx.needs_rerender();\n return;\n }\n\n enum Action {\n None,\n Save,\n Discard,\n Cancel,\n }\n let mut action = Action::None;\n\n ctx.modal_begin(\"unsaved-changes\", loc(LocId::UnsavedChangesDialogTitle));\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n {\n let contains_focus = ctx.contains_focus();\n\n ctx.label(\"description\", loc(LocId::UnsavedChangesDialogDescription));\n ctx.attr_padding(Rect::three(1, 2, 1));\n\n ctx.table_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(0, 2, 1));\n ctx.attr_position(Position::Center);\n ctx.table_set_cell_gap(Size { width: 2, height: 0 });\n {\n ctx.table_next_row();\n ctx.inherit_focus();\n\n if ctx.button(\n \"yes\",\n loc(LocId::UnsavedChangesDialogYes),\n ButtonStyle::default().accelerator('S'),\n ) {\n action = Action::Save;\n }\n ctx.inherit_focus();\n if ctx.button(\n \"no\",\n loc(LocId::UnsavedChangesDialogNo),\n ButtonStyle::default().accelerator('N'),\n ) {\n action = Action::Discard;\n }\n if ctx.button(\"cancel\", loc(LocId::Cancel), ButtonStyle::default()) {\n action = Action::Cancel;\n }\n\n // Handle accelerator shortcuts\n if contains_focus {\n if ctx.consume_shortcut(vk::S) {\n action = Action::Save;\n } else if ctx.consume_shortcut(vk::N) {\n action = Action::Discard;\n }\n }\n }\n ctx.table_end();\n }\n if ctx.modal_end() {\n action = Action::Cancel;\n }\n\n match action {\n Action::None => return,\n Action::Save => {\n state.wants_save = true;\n }\n Action::Discard => {\n state.documents.remove_active();\n state.wants_close = false;\n }\n Action::Cancel => {\n state.wants_exit = false;\n state.wants_close = false;\n }\n }\n\n ctx.needs_rerender();\n}\n\npub fn draw_goto_menu(ctx: &mut Context, state: &mut State) {\n let mut done = false;\n\n if let Some(doc) = state.documents.active_mut() {\n ctx.modal_begin(\"goto\", loc(LocId::FileGoto));\n {\n if ctx.editline(\"goto-line\", &mut state.goto_target) {\n state.goto_invalid = false;\n }\n if state.goto_invalid {\n ctx.attr_background_rgba(ctx.indexed(IndexedColor::Red));\n ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightWhite));\n }\n\n ctx.attr_intrinsic_size(Size { width: 24, height: 1 });\n ctx.steal_focus();\n\n if ctx.consume_shortcut(vk::RETURN) {\n match validate_goto_point(&state.goto_target) {\n Ok(point) => {\n let mut buf = doc.buffer.borrow_mut();\n buf.cursor_move_to_logical(point);\n buf.make_cursor_visible();\n done = true;\n }\n Err(_) => state.goto_invalid = true,\n }\n ctx.needs_rerender();\n }\n }\n done |= ctx.modal_end();\n } else {\n done = true;\n }\n\n if done {\n state.wants_goto = false;\n state.goto_target.clear();\n state.goto_invalid = false;\n ctx.needs_rerender();\n }\n}\n\nfn validate_goto_point(line: &str) -> Result {\n let mut coords = [0; 2];\n let (y, x) = line.split_once(':').unwrap_or((line, \"0\"));\n // Using a loop here avoids 2 copies of the str->int code.\n // This makes the binary more compact.\n for (i, s) in [x, y].iter().enumerate() {\n coords[i] = s.parse::()?.saturating_sub(1);\n }\n Ok(Point { x: coords[0], y: coords[1] })\n}\n"], ["/edit/src/oklab.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Oklab colorspace conversions.\n//!\n//! Implements Oklab as defined at: \n\n#![allow(clippy::excessive_precision)]\n\n/// An Oklab color with alpha.\npub struct Lab {\n pub l: f32,\n pub a: f32,\n pub b: f32,\n pub alpha: f32,\n}\n\n/// Converts a 32-bit sRGB color to Oklab.\npub fn srgb_to_oklab(color: u32) -> Lab {\n let r = SRGB_TO_RGB_LUT[(color & 0xff) as usize];\n let g = SRGB_TO_RGB_LUT[((color >> 8) & 0xff) as usize];\n let b = SRGB_TO_RGB_LUT[((color >> 16) & 0xff) as usize];\n let alpha = (color >> 24) as f32 * (1.0 / 255.0);\n\n let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;\n let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;\n let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;\n\n let l_ = cbrtf_est(l);\n let m_ = cbrtf_est(m);\n let s_ = cbrtf_est(s);\n\n Lab {\n l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,\n a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,\n b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,\n alpha,\n }\n}\n\n/// Converts an Oklab color to a 32-bit sRGB color.\npub fn oklab_to_srgb(c: Lab) -> u32 {\n let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;\n let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;\n let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;\n\n let l = l_ * l_ * l_;\n let m = m_ * m_ * m_;\n let s = s_ * s_ * s_;\n\n let r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;\n let g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;\n let b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s;\n\n let r = r.clamp(0.0, 1.0);\n let g = g.clamp(0.0, 1.0);\n let b = b.clamp(0.0, 1.0);\n let alpha = c.alpha.clamp(0.0, 1.0);\n\n let r = linear_to_srgb(r);\n let g = linear_to_srgb(g);\n let b = linear_to_srgb(b);\n let a = (alpha * 255.0) as u32;\n\n r | (g << 8) | (b << 16) | (a << 24)\n}\n\n/// Blends two 32-bit sRGB colors in the Oklab color space.\npub fn oklab_blend(dst: u32, src: u32) -> u32 {\n let dst = srgb_to_oklab(dst);\n let src = srgb_to_oklab(src);\n\n let inv_a = 1.0 - src.alpha;\n let l = src.l + dst.l * inv_a;\n let a = src.a + dst.a * inv_a;\n let b = src.b + dst.b * inv_a;\n let alpha = src.alpha + dst.alpha * inv_a;\n\n oklab_to_srgb(Lab { l, a, b, alpha })\n}\n\nfn linear_to_srgb(c: f32) -> u32 {\n (if c > 0.0031308 {\n 255.0 * 1.055 * c.powf(1.0 / 2.4) - 255.0 * 0.055\n } else {\n 255.0 * 12.92 * c\n }) as u32\n}\n\n#[inline]\nfn cbrtf_est(a: f32) -> f32 {\n // http://metamerist.com/cbrt/cbrt.htm showed a great estimator for the cube root:\n // f32_as_uint32_t / 3 + 709921077\n // It's similar to the well known \"fast inverse square root\" trick.\n // Lots of numbers around 709921077 perform at least equally well to 709921077,\n // and it is unknown how and why 709921077 was chosen specifically.\n let u: u32 = f32::to_bits(a); // evil f32ing point bit level hacking\n let u = u / 3 + 709921077; // what the fuck?\n let x: f32 = f32::from_bits(u);\n\n // One round of Newton's method. It follows the Wikipedia article at\n // https://en.wikipedia.org/wiki/Cube_root#Numerical_methods\n // For `a`s in the range between 0 and 1, this results in a maximum error of\n // less than 6.7e-4f, which is not good, but good enough for us, because\n // we're not an image editor. The benefit is that it's really fast.\n (1.0 / 3.0) * (a / (x * x) + (x + x)) // 1st iteration\n}\n\n#[rustfmt::skip]\n#[allow(clippy::excessive_precision)]\nconst SRGB_TO_RGB_LUT: [f32; 256] = [\n 0.0000000000, 0.0003035270, 0.0006070540, 0.0009105810, 0.0012141080, 0.0015176350, 0.0018211619, 0.0021246888, 0.0024282159, 0.0027317430, 0.0030352699, 0.0033465356, 0.0036765069, 0.0040247170, 0.0043914421, 0.0047769533,\n 0.0051815170, 0.0056053917, 0.0060488326, 0.0065120910, 0.0069954102, 0.0074990317, 0.0080231922, 0.0085681248, 0.0091340570, 0.0097212177, 0.0103298230, 0.0109600937, 0.0116122449, 0.0122864870, 0.0129830306, 0.0137020806,\n 0.0144438436, 0.0152085144, 0.0159962922, 0.0168073755, 0.0176419523, 0.0185002182, 0.0193823613, 0.0202885624, 0.0212190095, 0.0221738834, 0.0231533647, 0.0241576303, 0.0251868572, 0.0262412224, 0.0273208916, 0.0284260381,\n 0.0295568332, 0.0307134409, 0.0318960287, 0.0331047624, 0.0343398079, 0.0356013142, 0.0368894450, 0.0382043645, 0.0395462364, 0.0409151986, 0.0423114114, 0.0437350273, 0.0451862030, 0.0466650836, 0.0481718220, 0.0497065634,\n 0.0512694679, 0.0528606549, 0.0544802807, 0.0561284944, 0.0578054339, 0.0595112406, 0.0612460710, 0.0630100295, 0.0648032799, 0.0666259527, 0.0684781820, 0.0703601092, 0.0722718611, 0.0742135793, 0.0761853904, 0.0781874284,\n 0.0802198276, 0.0822827145, 0.0843762159, 0.0865004659, 0.0886556059, 0.0908417329, 0.0930589810, 0.0953074843, 0.0975873619, 0.0998987406, 0.1022417471, 0.1046164930, 0.1070231125, 0.1094617173, 0.1119324341, 0.1144353822,\n 0.1169706732, 0.1195384338, 0.1221387982, 0.1247718409, 0.1274376959, 0.1301364899, 0.1328683347, 0.1356333494, 0.1384316236, 0.1412633061, 0.1441284865, 0.1470272839, 0.1499598026, 0.1529261619, 0.1559264660, 0.1589608639,\n 0.1620294005, 0.1651322246, 0.1682693958, 0.1714410931, 0.1746473908, 0.1778884083, 0.1811642349, 0.1844749898, 0.1878207624, 0.1912016720, 0.1946178079, 0.1980693042, 0.2015562356, 0.2050787061, 0.2086368501, 0.2122307271,\n 0.2158605307, 0.2195262313, 0.2232279778, 0.2269658893, 0.2307400703, 0.2345506549, 0.2383976579, 0.2422811985, 0.2462013960, 0.2501583695, 0.2541521788, 0.2581829131, 0.2622507215, 0.2663556635, 0.2704978585, 0.2746773660,\n 0.2788943350, 0.2831487954, 0.2874408960, 0.2917706966, 0.2961383164, 0.3005438447, 0.3049873710, 0.3094689548, 0.3139887452, 0.3185468316, 0.3231432438, 0.3277781308, 0.3324515820, 0.3371636569, 0.3419144452, 0.3467040956,\n 0.3515326977, 0.3564002514, 0.3613068759, 0.3662526906, 0.3712377846, 0.3762622178, 0.3813261092, 0.3864295185, 0.3915725648, 0.3967553079, 0.4019778669, 0.4072403014, 0.4125427008, 0.4178851545, 0.4232677519, 0.4286905527,\n 0.4341537058, 0.4396572411, 0.4452012479, 0.4507858455, 0.4564110637, 0.4620770514, 0.4677838385, 0.4735315442, 0.4793202281, 0.4851499796, 0.4910208881, 0.4969330430, 0.5028865933, 0.5088814497, 0.5149177909, 0.5209956765,\n 0.5271152258, 0.5332764983, 0.5394796133, 0.5457245708, 0.5520114899, 0.5583404899, 0.5647116303, 0.5711249113, 0.5775805116, 0.5840784907, 0.5906189084, 0.5972018838, 0.6038274169, 0.6104956269, 0.6172066331, 0.6239604354,\n 0.6307572126, 0.6375969648, 0.6444797516, 0.6514056921, 0.6583748460, 0.6653873324, 0.6724432111, 0.6795425415, 0.6866854429, 0.6938719153, 0.7011020184, 0.7083759308, 0.7156936526, 0.7230552435, 0.7304608822, 0.7379105687,\n 0.7454043627, 0.7529423237, 0.7605246305, 0.7681512833, 0.7758223414, 0.7835379243, 0.7912980318, 0.7991028428, 0.8069523573, 0.8148466945, 0.8227858543, 0.8307699561, 0.8387991190, 0.8468732834, 0.8549926877, 0.8631572723,\n 0.8713672161, 0.8796223402, 0.8879231811, 0.8962693810, 0.9046613574, 0.9130986929, 0.9215820432, 0.9301108718, 0.9386858940, 0.9473065734, 0.9559735060, 0.9646862745, 0.9734454751, 0.9822505713, 0.9911022186, 1.0000000000,\n];\n"], ["/edit/src/hash.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides fast, non-cryptographic hash functions.\n\n/// The venerable wyhash hash function.\n///\n/// It's fast, has good statistical properties, and is in the public domain.\n/// See: \n/// If you visit the link, you'll find that it was superseded by \"rapidhash\",\n/// but that's not particularly interesting for this project. rapidhash results\n/// in way larger assembly and isn't faster when hashing small amounts of data.\npub fn hash(mut seed: u64, data: &[u8]) -> u64 {\n unsafe {\n const S0: u64 = 0xa0761d6478bd642f;\n const S1: u64 = 0xe7037ed1a0b428db;\n const S2: u64 = 0x8ebc6af09c88c6e3;\n const S3: u64 = 0x589965cc75374cc3;\n\n let len = data.len();\n let mut p = data.as_ptr();\n let a;\n let b;\n\n seed ^= S0;\n\n if len <= 16 {\n if len >= 4 {\n a = (wyr4(p) << 32) | wyr4(p.add((len >> 3) << 2));\n b = (wyr4(p.add(len - 4)) << 32) | wyr4(p.add(len - 4 - ((len >> 3) << 2)));\n } else if len > 0 {\n a = wyr3(p, len);\n b = 0;\n } else {\n a = 0;\n b = 0;\n }\n } else {\n let mut i = len;\n if i > 48 {\n let mut seed1 = seed;\n let mut seed2 = seed;\n while {\n seed = wymix(wyr8(p) ^ S1, wyr8(p.add(8)) ^ seed);\n seed1 = wymix(wyr8(p.add(16)) ^ S2, wyr8(p.add(24)) ^ seed1);\n seed2 = wymix(wyr8(p.add(32)) ^ S3, wyr8(p.add(40)) ^ seed2);\n p = p.add(48);\n i -= 48;\n i > 48\n } {}\n seed ^= seed1 ^ seed2;\n }\n while i > 16 {\n seed = wymix(wyr8(p) ^ S1, wyr8(p.add(8)) ^ seed);\n i -= 16;\n p = p.add(16);\n }\n a = wyr8(p.offset(i as isize - 16));\n b = wyr8(p.offset(i as isize - 8));\n }\n\n wymix(S1 ^ (len as u64), wymix(a ^ S1, b ^ seed))\n }\n}\n\nunsafe fn wyr3(p: *const u8, k: usize) -> u64 {\n let p0 = unsafe { p.read() as u64 };\n let p1 = unsafe { p.add(k >> 1).read() as u64 };\n let p2 = unsafe { p.add(k - 1).read() as u64 };\n (p0 << 16) | (p1 << 8) | p2\n}\n\nunsafe fn wyr4(p: *const u8) -> u64 {\n unsafe { (p as *const u32).read_unaligned() as u64 }\n}\n\nunsafe fn wyr8(p: *const u8) -> u64 {\n unsafe { (p as *const u64).read_unaligned() }\n}\n\n// This is a weak mix function on its own. It may be worth considering\n// replacing external uses of this function with a stronger one.\n// On the other hand, it's very fast.\npub fn wymix(lhs: u64, rhs: u64) -> u64 {\n let lhs = lhs as u128;\n let rhs = rhs as u128;\n let r = lhs * rhs;\n (r >> 64) as u64 ^ (r as u64)\n}\n\npub fn hash_str(seed: u64, s: &str) -> u64 {\n hash(seed, s.as_bytes())\n}\n"], ["/edit/src/path.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Path related helpers.\n\nuse std::ffi::{OsStr, OsString};\nuse std::path::{Component, MAIN_SEPARATOR_STR, Path, PathBuf};\n\n/// Normalizes a given path by removing redundant components.\n/// The given path must be absolute (e.g. by joining it with the current working directory).\npub fn normalize(path: &Path) -> PathBuf {\n let mut res = PathBuf::with_capacity(path.as_os_str().as_encoded_bytes().len());\n let mut root_len = 0;\n\n for component in path.components() {\n match component {\n Component::Prefix(p) => res.push(p.as_os_str()),\n Component::RootDir => {\n res.push(OsStr::new(MAIN_SEPARATOR_STR));\n root_len = res.as_os_str().as_encoded_bytes().len();\n }\n Component::CurDir => {}\n Component::ParentDir => {\n // Get the length up to the parent directory\n if let Some(len) = res\n .parent()\n .map(|p| p.as_os_str().as_encoded_bytes().len())\n // Ensure we don't pop the root directory\n && len >= root_len\n {\n // Pop the last component from `res`.\n //\n // This can be replaced with a plain `res.as_mut_os_string().truncate(len)`\n // once `os_string_truncate` is stabilized (#133262).\n let mut bytes = res.into_os_string().into_encoded_bytes();\n bytes.truncate(len);\n res = PathBuf::from(unsafe { OsString::from_encoded_bytes_unchecked(bytes) });\n }\n }\n Component::Normal(p) => res.push(p),\n }\n }\n\n res\n}\n\n#[cfg(test)]\nmod tests {\n use std::ffi::OsString;\n use std::path::Path;\n\n use super::*;\n\n fn norm(s: &str) -> OsString {\n normalize(Path::new(s)).into_os_string()\n }\n\n #[cfg(unix)]\n #[test]\n fn test_unix() {\n assert_eq!(norm(\"/a/b/c\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/b/c/\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/./b\"), \"/a/b\");\n assert_eq!(norm(\"/a/b/../c\"), \"/a/c\");\n assert_eq!(norm(\"/../../a\"), \"/a\");\n assert_eq!(norm(\"/../\"), \"/\");\n assert_eq!(norm(\"/a//b/c\"), \"/a/b/c\");\n assert_eq!(norm(\"/a/b/c/../../../../d\"), \"/d\");\n assert_eq!(norm(\"//\"), \"/\");\n }\n\n #[cfg(windows)]\n #[test]\n fn test_windows() {\n assert_eq!(norm(r\"C:\\a\\b\\c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\b\\c\\\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\.\\b\"), r\"C:\\a\\b\");\n assert_eq!(norm(r\"C:\\a\\b\\..\\c\"), r\"C:\\a\\c\");\n assert_eq!(norm(r\"C:\\..\\..\\a\"), r\"C:\\a\");\n assert_eq!(norm(r\"C:\\..\\\"), r\"C:\\\");\n assert_eq!(norm(r\"C:\\a\\\\b\\c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:/a\\b/c\"), r\"C:\\a\\b\\c\");\n assert_eq!(norm(r\"C:\\a\\b\\c\\..\\..\\..\\..\\d\"), r\"C:\\d\");\n assert_eq!(norm(r\"\\\\server\\share\\path\"), r\"\\\\server\\share\\path\");\n }\n}\n"], ["/edit/src/bin/edit/draw_menubar.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nuse edit::arena_format;\nuse edit::helpers::*;\nuse edit::input::{kbmod, vk};\nuse edit::tui::*;\n\nuse crate::localization::*;\nuse crate::state::*;\n\npub fn draw_menubar(ctx: &mut Context, state: &mut State) {\n ctx.menubar_begin();\n ctx.attr_background_rgba(state.menubar_color_bg);\n ctx.attr_foreground_rgba(state.menubar_color_fg);\n {\n let contains_focus = ctx.contains_focus();\n\n if ctx.menubar_menu_begin(loc(LocId::File), 'F') {\n draw_menu_file(ctx, state);\n }\n if !contains_focus && ctx.consume_shortcut(vk::F10) {\n ctx.steal_focus();\n }\n if state.documents.active().is_some() {\n if ctx.menubar_menu_begin(loc(LocId::Edit), 'E') {\n draw_menu_edit(ctx, state);\n }\n if ctx.menubar_menu_begin(loc(LocId::View), 'V') {\n draw_menu_view(ctx, state);\n }\n }\n if ctx.menubar_menu_begin(loc(LocId::Help), 'H') {\n draw_menu_help(ctx, state);\n }\n }\n ctx.menubar_end();\n}\n\nfn draw_menu_file(ctx: &mut Context, state: &mut State) {\n if ctx.menubar_menu_button(loc(LocId::FileNew), 'N', kbmod::CTRL | vk::N) {\n draw_add_untitled_document(ctx, state);\n }\n if ctx.menubar_menu_button(loc(LocId::FileOpen), 'O', kbmod::CTRL | vk::O) {\n state.wants_file_picker = StateFilePicker::Open;\n }\n if state.documents.active().is_some() {\n if ctx.menubar_menu_button(loc(LocId::FileSave), 'S', kbmod::CTRL | vk::S) {\n state.wants_save = true;\n }\n if ctx.menubar_menu_button(loc(LocId::FileSaveAs), 'A', vk::NULL) {\n state.wants_file_picker = StateFilePicker::SaveAs;\n }\n if ctx.menubar_menu_button(loc(LocId::FileClose), 'C', kbmod::CTRL | vk::W) {\n state.wants_close = true;\n }\n }\n if ctx.menubar_menu_button(loc(LocId::FileExit), 'X', kbmod::CTRL | vk::Q) {\n state.wants_exit = true;\n }\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_edit(ctx: &mut Context, state: &mut State) {\n let doc = state.documents.active().unwrap();\n let mut tb = doc.buffer.borrow_mut();\n\n if ctx.menubar_menu_button(loc(LocId::EditUndo), 'U', kbmod::CTRL | vk::Z) {\n tb.undo();\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditRedo), 'R', kbmod::CTRL | vk::Y) {\n tb.redo();\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditCut), 'T', kbmod::CTRL | vk::X) {\n tb.cut(ctx.clipboard_mut());\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditCopy), 'C', kbmod::CTRL | vk::C) {\n tb.copy(ctx.clipboard_mut());\n ctx.needs_rerender();\n }\n if ctx.menubar_menu_button(loc(LocId::EditPaste), 'P', kbmod::CTRL | vk::V) {\n tb.paste(ctx.clipboard_ref());\n ctx.needs_rerender();\n }\n if state.wants_search.kind != StateSearchKind::Disabled {\n if ctx.menubar_menu_button(loc(LocId::EditFind), 'F', kbmod::CTRL | vk::F) {\n state.wants_search.kind = StateSearchKind::Search;\n state.wants_search.focus = true;\n }\n if ctx.menubar_menu_button(loc(LocId::EditReplace), 'L', kbmod::CTRL | vk::R) {\n state.wants_search.kind = StateSearchKind::Replace;\n state.wants_search.focus = true;\n }\n }\n if ctx.menubar_menu_button(loc(LocId::EditSelectAll), 'A', kbmod::CTRL | vk::A) {\n tb.select_all();\n ctx.needs_rerender();\n }\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_view(ctx: &mut Context, state: &mut State) {\n if let Some(doc) = state.documents.active() {\n let mut tb = doc.buffer.borrow_mut();\n let word_wrap = tb.is_word_wrap_enabled();\n\n // All values on the statusbar are currently document specific.\n if ctx.menubar_menu_button(loc(LocId::ViewFocusStatusbar), 'S', vk::NULL) {\n state.wants_statusbar_focus = true;\n }\n if ctx.menubar_menu_button(loc(LocId::ViewGoToFile), 'F', kbmod::CTRL | vk::P) {\n state.wants_go_to_file = true;\n }\n if ctx.menubar_menu_button(loc(LocId::FileGoto), 'G', kbmod::CTRL | vk::G) {\n state.wants_goto = true;\n }\n if ctx.menubar_menu_checkbox(loc(LocId::ViewWordWrap), 'W', kbmod::ALT | vk::Z, word_wrap) {\n tb.set_word_wrap(!word_wrap);\n ctx.needs_rerender();\n }\n }\n\n ctx.menubar_menu_end();\n}\n\nfn draw_menu_help(ctx: &mut Context, state: &mut State) {\n if ctx.menubar_menu_button(loc(LocId::HelpAbout), 'A', vk::NULL) {\n state.wants_about = true;\n }\n ctx.menubar_menu_end();\n}\n\npub fn draw_dialog_about(ctx: &mut Context, state: &mut State) {\n ctx.modal_begin(\"about\", loc(LocId::AboutDialogTitle));\n {\n ctx.block_begin(\"content\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(1, 2, 1));\n {\n ctx.label(\"description\", \"Microsoft Edit\");\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_position(Position::Center);\n\n ctx.label(\n \"version\",\n &arena_format!(\n ctx.arena(),\n \"{}{}\",\n loc(LocId::AboutDialogVersion),\n env!(\"CARGO_PKG_VERSION\")\n ),\n );\n ctx.attr_overflow(Overflow::TruncateHead);\n ctx.attr_position(Position::Center);\n\n ctx.label(\"copyright\", \"Copyright (c) Microsoft Corp 2025\");\n ctx.attr_overflow(Overflow::TruncateTail);\n ctx.attr_position(Position::Center);\n\n ctx.block_begin(\"choices\");\n ctx.inherit_focus();\n ctx.attr_padding(Rect::three(1, 2, 0));\n ctx.attr_position(Position::Center);\n {\n if ctx.button(\"ok\", loc(LocId::Ok), ButtonStyle::default()) {\n state.wants_about = false;\n }\n ctx.inherit_focus();\n }\n ctx.block_end();\n }\n ctx.block_end();\n }\n if ctx.modal_end() {\n state.wants_about = false;\n }\n}\n"], ["/edit/src/clipboard.rs", "//! Clipboard facilities for the editor.\n\n/// The builtin, internal clipboard of the editor.\n///\n/// This is useful particularly when the terminal doesn't support\n/// OSC 52 or when the clipboard contents are huge (e.g. 1GiB).\n#[derive(Default)]\npub struct Clipboard {\n data: Vec,\n line_copy: bool,\n wants_host_sync: bool,\n}\n\nimpl Clipboard {\n /// If true, we should emit a OSC 52 sequence to sync the clipboard\n /// with the hosting terminal.\n pub fn wants_host_sync(&self) -> bool {\n self.wants_host_sync\n }\n\n /// Call this once the clipboard has been synchronized with the host.\n pub fn mark_as_synchronized(&mut self) {\n self.wants_host_sync = false;\n }\n\n /// The editor has a special behavior when you have no selection and press\n /// Ctrl+C: It copies the current line to the clipboard. Then, when you\n /// paste it, it inserts the line at *the start* of the current line.\n /// This effectively prepends the current line with the copied line.\n /// `clipboard_line_start` is true in that case.\n pub fn is_line_copy(&self) -> bool {\n self.line_copy\n }\n\n /// Returns the current contents of the clipboard.\n pub fn read(&self) -> &[u8] {\n &self.data\n }\n\n /// Fill the clipboard with the given data.\n pub fn write(&mut self, data: Vec) {\n if !data.is_empty() {\n self.data = data;\n self.line_copy = false;\n self.wants_host_sync = true;\n }\n }\n\n /// See [`Clipboard::is_line_copy`].\n pub fn write_was_line_copy(&mut self, line_copy: bool) {\n self.line_copy = line_copy;\n }\n}\n"], ["/edit/src/cell.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! [`std::cell::RefCell`], but without runtime checks in release builds.\n\n#[cfg(debug_assertions)]\npub use debug::*;\n#[cfg(not(debug_assertions))]\npub use release::*;\n\n#[allow(unused)]\n#[cfg(debug_assertions)]\nmod debug {\n pub type SemiRefCell = std::cell::RefCell;\n pub type Ref<'b, T> = std::cell::Ref<'b, T>;\n pub type RefMut<'b, T> = std::cell::RefMut<'b, T>;\n}\n\n#[cfg(not(debug_assertions))]\nmod release {\n #[derive(Default)]\n #[repr(transparent)]\n pub struct SemiRefCell(std::cell::UnsafeCell);\n\n impl SemiRefCell {\n #[inline(always)]\n pub const fn new(value: T) -> Self {\n Self(std::cell::UnsafeCell::new(value))\n }\n\n #[inline(always)]\n pub const fn as_ptr(&self) -> *mut T {\n self.0.get()\n }\n\n #[inline(always)]\n pub const fn borrow(&self) -> Ref<'_, T> {\n Ref(unsafe { &*self.0.get() })\n }\n\n #[inline(always)]\n pub const fn borrow_mut(&self) -> RefMut<'_, T> {\n RefMut(unsafe { &mut *self.0.get() })\n }\n }\n\n #[repr(transparent)]\n pub struct Ref<'b, T>(&'b T);\n\n impl<'b, T> Ref<'b, T> {\n #[inline(always)]\n pub fn clone(orig: &Self) -> Self {\n Ref(orig.0)\n }\n }\n\n impl<'b, T> std::ops::Deref for Ref<'b, T> {\n type Target = T;\n\n #[inline(always)]\n fn deref(&self) -> &Self::Target {\n self.0\n }\n }\n\n #[repr(transparent)]\n pub struct RefMut<'b, T>(&'b mut T);\n\n impl<'b, T> std::ops::Deref for RefMut<'b, T> {\n type Target = T;\n\n #[inline(always)]\n fn deref(&self) -> &Self::Target {\n self.0\n }\n }\n\n impl<'b, T> std::ops::DerefMut for RefMut<'b, T> {\n #[inline(always)]\n fn deref_mut(&mut self) -> &mut Self::Target {\n self.0\n }\n }\n}\n"], ["/edit/src/simd/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides various high-throughput utilities.\n\npub mod lines_bwd;\npub mod lines_fwd;\nmod memchr2;\nmod memset;\n\npub use lines_bwd::*;\npub use lines_fwd::*;\npub use memchr2::*;\npub use memset::*;\n\n#[cfg(test)]\nmod test {\n // Knuth's MMIX LCG\n pub fn make_rng() -> impl FnMut() -> usize {\n let mut state = 1442695040888963407u64;\n move || {\n state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);\n state as usize\n }\n }\n\n pub fn generate_random_text(len: usize) -> String {\n const ALPHABET: &[u8; 20] = b\"0123456789abcdef\\n\\n\\n\\n\";\n\n let mut rng = make_rng();\n let mut res = String::new();\n\n for _ in 0..len {\n res.push(ALPHABET[rng() % ALPHABET.len()] as char);\n }\n\n res\n }\n\n pub fn count_lines(text: &str) -> usize {\n text.lines().count()\n }\n}\n"], ["/edit/src/apperr.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Provides a transparent error type for edit.\n\nuse std::{io, result};\n\nuse crate::sys;\n\npub const APP_ICU_MISSING: Error = Error::new_app(0);\n\n/// Edit's transparent `Result` type.\npub type Result = result::Result;\n\n/// Edit's transparent `Error` type.\n/// Abstracts over system and application errors.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum Error {\n App(u32),\n Icu(u32),\n Sys(u32),\n}\n\nimpl Error {\n pub const fn new_app(code: u32) -> Self {\n Self::App(code)\n }\n\n pub const fn new_icu(code: u32) -> Self {\n Self::Icu(code)\n }\n\n pub const fn new_sys(code: u32) -> Self {\n Self::Sys(code)\n }\n}\n\nimpl From for Error {\n fn from(err: io::Error) -> Self {\n sys::io_error_to_apperr(err)\n }\n}\n"], ["/edit/src/unicode/tables.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n// BEGIN: Generated by grapheme-table-gen on 2025-06-03T13:50:48Z, from Unicode 16.0.0, with --lang=rust --extended --line-breaks, 17688 bytes\n#[rustfmt::skip]\nconst STAGE0: [u16; 544] = [\n 0x0000, 0x0040, 0x007f, 0x00bf, 0x00ff, 0x013f, 0x017f, 0x0194, 0x0194, 0x01a6, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x01e6, 0x0226, 0x024a, 0x024b, 0x024c, 0x0246, 0x0255, 0x0295, 0x02d5, 0x02d5, 0x02d5, 0x030d,\n 0x034d, 0x038d, 0x03cd, 0x040d, 0x044d, 0x0478, 0x04b8, 0x04db, 0x04fc, 0x0295, 0x0295, 0x0295, 0x0534, 0x0574, 0x0194, 0x0194,\n 0x05b4, 0x05f4, 0x0295, 0x0295, 0x0295, 0x061d, 0x065d, 0x067d, 0x0295, 0x06a3, 0x06e3, 0x0723, 0x0763, 0x07a3, 0x07e3, 0x0823,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0863,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194,\n 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0194, 0x0863,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x08a3, 0x08b3, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295, 0x0295,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x08f3,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5,\n 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x02d5, 0x08f3,\n];\n#[rustfmt::skip]\nconst STAGE1: [u16; 2355] = [\n 0x0000, 0x0008, 0x0010, 0x0018, 0x0020, 0x0028, 0x0030, 0x0038, 0x0040, 0x0047, 0x004f, 0x0056, 0x0059, 0x0059, 0x005e, 0x0059, 0x0059, 0x0059, 0x0066, 0x006a, 0x0059, 0x0059, 0x0071, 0x0059, 0x0079, 0x0079, 0x007e, 0x0086, 0x008e, 0x0096, 0x009e, 0x0059, 0x00a6, 0x00aa, 0x00ae, 0x0059, 0x00b6, 0x0059, 0x0059, 0x0059, 0x0059, 0x00ba, 0x00bf, 0x0059, 0x00c6, 0x00cb, 0x00d3, 0x00d9, 0x00e1, 0x0059, 0x00e9, 0x00f1, 0x0059, 0x0059, 0x00f6, 0x00fe, 0x0105, 0x010a, 0x0110, 0x0059, 0x0059, 0x0117, 0x011f, 0x0125,\n 0x012d, 0x0134, 0x013c, 0x0144, 0x0149, 0x0059, 0x0151, 0x0159, 0x0161, 0x0167, 0x016f, 0x0177, 0x017f, 0x0185, 0x018d, 0x0195, 0x019d, 0x01a3, 0x01ab, 0x01b3, 0x01bb, 0x01c1, 0x01c9, 0x01d1, 0x01d9, 0x01df, 0x01e7, 0x01ef, 0x01f7, 0x01ff, 0x0207, 0x020e, 0x0216, 0x021c, 0x0224, 0x022c, 0x0234, 0x023a, 0x0242, 0x024a, 0x0252, 0x0258, 0x0260, 0x0268, 0x0270, 0x0277, 0x027f, 0x0287, 0x028d, 0x0291, 0x0299, 0x028d, 0x028d, 0x02a0, 0x02a8, 0x028d, 0x02b0, 0x02b8, 0x00bc, 0x02c0, 0x02c8, 0x02cf, 0x02d7, 0x028d,\n 0x02de, 0x02e6, 0x02ee, 0x02f6, 0x0059, 0x02fe, 0x0059, 0x0306, 0x0306, 0x0306, 0x030e, 0x030e, 0x0314, 0x0316, 0x0316, 0x0059, 0x0059, 0x031e, 0x0059, 0x0326, 0x032a, 0x0332, 0x0059, 0x0338, 0x0059, 0x033e, 0x0346, 0x034e, 0x0059, 0x0059, 0x0356, 0x035e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0366, 0x0059, 0x0059, 0x036e, 0x0376, 0x037e, 0x0386, 0x038e, 0x028d, 0x0393, 0x039b, 0x03a3, 0x03ab,\n 0x0059, 0x0059, 0x03b3, 0x03bb, 0x03c1, 0x0059, 0x03c5, 0x03cd, 0x03d5, 0x03dd, 0x028d, 0x028d, 0x028d, 0x03e1, 0x0059, 0x03e9, 0x028d, 0x03f1, 0x03f9, 0x0401, 0x0408, 0x040d, 0x028d, 0x0415, 0x0418, 0x0420, 0x0428, 0x0430, 0x0438, 0x028d, 0x0440, 0x0059, 0x0447, 0x044f, 0x0456, 0x0144, 0x045e, 0x0466, 0x046e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0476, 0x047a, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0356, 0x0059, 0x0482, 0x048a, 0x0059, 0x0492, 0x0496, 0x049e, 0x04a6,\n 0x04ae, 0x04b6, 0x04be, 0x04c6, 0x04ce, 0x04d6, 0x04da, 0x04e2, 0x04ea, 0x04f1, 0x04f9, 0x0500, 0x0507, 0x050e, 0x0515, 0x051d, 0x0525, 0x052d, 0x0535, 0x053d, 0x0544, 0x0059, 0x054c, 0x0552, 0x0559, 0x0059, 0x0059, 0x055f, 0x0059, 0x0564, 0x056a, 0x0059, 0x0571, 0x0579, 0x0581, 0x0581, 0x0581, 0x0589, 0x058f, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0597, 0x059f, 0x05a7, 0x05af, 0x05b7, 0x05bf, 0x05c7, 0x05cf, 0x05d7, 0x05df, 0x05e7, 0x05ef, 0x05f6, 0x05fe, 0x0606, 0x060e, 0x0616, 0x061e, 0x0625, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0629, 0x0059, 0x0059, 0x0631, 0x0059, 0x0638, 0x063f, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0647, 0x0059, 0x064f, 0x0656, 0x065c, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0662, 0x0059, 0x02fe, 0x0059, 0x066a, 0x0672, 0x067a, 0x067a, 0x0079, 0x0682, 0x068a, 0x0692, 0x028d, 0x069a, 0x06a1, 0x06a1, 0x06a4, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06ac, 0x06b2, 0x06ba,\n 0x06c2, 0x06ca, 0x06d2, 0x06da, 0x06e2, 0x06d2, 0x06ea, 0x06f2, 0x06f6, 0x06a1, 0x06a1, 0x06fb, 0x06a1, 0x06a1, 0x0702, 0x070a, 0x06a1, 0x0712, 0x06a1, 0x0716, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x071e, 0x071e, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0726, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x072c, 0x06a1, 0x0733, 0x0456, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0738, 0x0740, 0x0059, 0x0748, 0x0750, 0x0059, 0x0059, 0x0758, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0760, 0x0768, 0x0770, 0x0778, 0x0059, 0x0780, 0x0788, 0x078b, 0x0792, 0x079a, 0x011f, 0x07a2, 0x07a9, 0x07b1, 0x07b9, 0x07bd, 0x07c5, 0x07cd, 0x028d, 0x07d4, 0x07dc, 0x07e4, 0x028d, 0x07ec, 0x07f4, 0x07fc, 0x0804, 0x080c,\n 0x0059, 0x0811, 0x0059, 0x0059, 0x0059, 0x0819, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822,\n 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x0827, 0x0821, 0x0822, 0x0823, 0x0824, 0x0825, 0x0826, 0x082e, 0x0835, 0x0838, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581,\n 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0840, 0x0848, 0x0850, 0x0059, 0x0059, 0x0059, 0x0858, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x085d, 0x0059, 0x0059, 0x0657, 0x0059, 0x0865, 0x0869, 0x0871, 0x0879, 0x0880,\n 0x0888, 0x0059, 0x0059, 0x0059, 0x088e, 0x0896, 0x089e, 0x08a6, 0x08ae, 0x08b3, 0x08bb, 0x08c3, 0x08cb, 0x00bb, 0x08d3, 0x08db, 0x028d, 0x0059, 0x0059, 0x0059, 0x0852, 0x08e3, 0x08e6, 0x0059, 0x0059, 0x08ec, 0x028c, 0x08f4, 0x08f8, 0x028d, 0x028d, 0x028d, 0x028d, 0x0900, 0x0059, 0x0903, 0x090b, 0x0059, 0x0911, 0x0144, 0x0915, 0x091d, 0x0059, 0x0925, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x048a, 0x03af, 0x092d, 0x0933, 0x0059, 0x0938, 0x0059, 0x093f, 0x0943, 0x0948, 0x0059, 0x0950, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0672, 0x03c5, 0x0953, 0x095b, 0x095f, 0x028d, 0x028d, 0x0967, 0x096a, 0x0972, 0x0059, 0x03cd, 0x097a, 0x028d, 0x0982, 0x0989, 0x0991, 0x028d, 0x028d, 0x0059, 0x0999, 0x0657, 0x0059, 0x09a1, 0x09a8, 0x09b0, 0x0059, 0x0059, 0x028d, 0x0059, 0x09b8, 0x0059, 0x09c0, 0x048c, 0x09c8, 0x09ce, 0x09d6, 0x028d, 0x028d, 0x0059, 0x0059, 0x09de, 0x028d, 0x0059, 0x0854, 0x0059, 0x09e6, 0x0059, 0x09ed, 0x011f, 0x09f5, 0x09fc, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x03cd, 0x0059, 0x0a04, 0x0a0c, 0x0a0e, 0x0059, 0x0938, 0x0a16, 0x08f4, 0x0a1e, 0x08f4, 0x0952, 0x0672, 0x0a26, 0x0a28, 0x0a2f, 0x0a36, 0x0430, 0x0a3e, 0x0a46, 0x0a4c, 0x0a54, 0x0a5b, 0x0a63, 0x0a67, 0x0430, 0x0a6f, 0x0a77, 0x0a7f, 0x065d, 0x0a87, 0x0a8f, 0x028d, 0x0a97, 0x0a9f, 0x0a55, 0x0aa7, 0x0aaf, 0x0ab1, 0x0ab9, 0x0ac1, 0x028d, 0x0ac7, 0x0acf, 0x0ad7, 0x0059, 0x0adf, 0x0ae7, 0x0aef, 0x0059, 0x0af7, 0x0aff, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0b07, 0x0b0f, 0x028d, 0x0059, 0x0b17, 0x0b1f,\n 0x0b27, 0x0059, 0x0b2f, 0x0b37, 0x0b3e, 0x0b3f, 0x0b47, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0b4f, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0b57, 0x028d, 0x0b5f, 0x0b67, 0x028d, 0x028d, 0x0659, 0x0b6f, 0x0b77, 0x0b7f, 0x0b83, 0x0b8b, 0x0059, 0x0b92, 0x0b9a, 0x0059, 0x03b3, 0x0ba2, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0baa, 0x0bb2, 0x0bb7, 0x0bbf, 0x0bc6, 0x0bcb, 0x0bd1, 0x028d, 0x028d, 0x0bd9, 0x0bdd, 0x0be5, 0x0bed, 0x0bf3, 0x0bfb, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x0bff, 0x0c07, 0x0c0a, 0x0c12, 0x028d, 0x028d, 0x0c19, 0x0c21, 0x0c29, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x034e, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0c31, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c39, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0059, 0x0059, 0x0854, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c41, 0x0059, 0x0c49, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c4c, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c53, 0x0c5b, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0852, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0c63, 0x0059, 0x0059, 0x0059, 0x0c6a, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0c6c, 0x0c74, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059,\n 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x03b3, 0x03cd, 0x0c7c, 0x0059, 0x03cd, 0x03af, 0x0c81, 0x0059, 0x0c89, 0x0c90, 0x0c98, 0x0951, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0ca0, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0ca8, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0cb0, 0x0cb5, 0x0cbb, 0x028d, 0x028d, 0x0cc3, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a3, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x071e, 0x0ccb, 0x0cd1, 0x0cd9, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0cdd, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0ce5, 0x0cea, 0x0cf1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a2, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0cf9, 0x0cfe, 0x0d06, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d0e, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0950, 0x028d, 0x028d, 0x0079, 0x0d16, 0x0d1d, 0x0059, 0x0059, 0x0059, 0x0c39, 0x028d, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x03c5, 0x0059, 0x0d24, 0x0059, 0x0d2b, 0x0d33, 0x0d39, 0x0059, 0x0579, 0x0059, 0x0059, 0x0d41, 0x028d, 0x028d, 0x028d, 0x0950, 0x0950, 0x071e, 0x071e, 0x0d49, 0x0d51, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x0059, 0x0059, 0x0492, 0x0059, 0x0d59, 0x0d61, 0x0d69, 0x0059, 0x0d70, 0x0d6b, 0x0d78, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d7f, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0d84, 0x0d88, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0079, 0x0d90, 0x0079, 0x0d97, 0x0d9e, 0x0da6, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x03cd, 0x0dad, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0db5, 0x0dbd, 0x0059, 0x0dc2, 0x0dc7, 0x028d, 0x028d, 0x028d, 0x0059, 0x0dcf, 0x0dd7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0ddf, 0x0059, 0x0de7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0def, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x08f4, 0x0df7, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0dff, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0e07, 0x028d, 0x0059, 0x0059, 0x0e0f, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d,\n 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0e17, 0x0059, 0x0e1c, 0x028d, 0x028d, 0x0e24, 0x048a, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0d69, 0x0e2c, 0x0e34, 0x0e3c, 0x0e44, 0x0e4c, 0x028d, 0x0ba6, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x028d, 0x0e54, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e5b, 0x0e56, 0x0e63, 0x0e68, 0x0581, 0x0e6e, 0x0e76, 0x0e7d, 0x0e56, 0x0e84, 0x0e8c, 0x0e93, 0x0e9b, 0x0ea3, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0eab, 0x0eb3, 0x0eab, 0x0eb9, 0x0ec1,\n 0x0ec9, 0x0ed1, 0x0ed9, 0x0eab, 0x0ee1, 0x0ee9, 0x0eab, 0x0eab, 0x0ef1, 0x0eab, 0x0ef6, 0x0efe, 0x0f05, 0x0f0d, 0x0f13, 0x0f1a, 0x0e54, 0x0f20, 0x0f27, 0x0eab, 0x0eab, 0x0f2e, 0x0f32, 0x0eab, 0x0eab, 0x0f3a, 0x0f42, 0x0059, 0x0059, 0x0059, 0x0f4a, 0x0059, 0x0059, 0x0f52, 0x0f5a, 0x0f62, 0x0059, 0x0f68, 0x0059, 0x0f70, 0x0f75, 0x0f7d, 0x0f7e, 0x0f86, 0x0f89, 0x0f90, 0x0eab, 0x0eab, 0x0eab, 0x0eab, 0x0eab, 0x0f98, 0x0f98, 0x0f9b, 0x0fa0, 0x0fa8, 0x0eab, 0x0faf, 0x0fb7, 0x0059, 0x0059, 0x0059, 0x0059, 0x0fbf,\n 0x0059, 0x0059, 0x0d0e, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0e56, 0x0fc7, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1,\n 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x06a1, 0x0fcf, 0x0fd7, 0x0079, 0x0079, 0x0079, 0x0020, 0x0020, 0x0020, 0x0020, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0079, 0x0fdf, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,\n 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581,\n 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0581, 0x0fe7,\n];\n#[rustfmt::skip]\nconst STAGE2: [u16; 4079] = [\n 0x0000, 0x0004, 0x0008, 0x000c, 0x0010, 0x0014, 0x0018, 0x001c,\n 0x0020, 0x0024, 0x0028, 0x002c, 0x0030, 0x0034, 0x0038, 0x003c,\n 0x0040, 0x0044, 0x0048, 0x004c, 0x0050, 0x0054, 0x0058, 0x005c,\n 0x0060, 0x0064, 0x0068, 0x006c, 0x0070, 0x0074, 0x0078, 0x007c,\n 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,\n 0x0080, 0x0084, 0x0087, 0x008b, 0x008f, 0x0093, 0x0095, 0x0099,\n 0x0040, 0x009d, 0x0040, 0x0040, 0x009f, 0x00a0, 0x009f, 0x00a4,\n 0x00a6, 0x009d, 0x00aa, 0x00a6, 0x00ac, 0x00a0, 0x00aa, 0x00af,\n 0x009e, 0x0040, 0x0040, 0x0040, 0x00b0, 0x0040, 0x00b4, 0x0040,\n 0x00a4, 0x00b4, 0x0040, 0x00a9, 0x0040, 0x009f, 0x00b4, 0x00aa,\n 0x009f, 0x00b7, 0x009e, 0x00a4, 0x0040, 0x0040, 0x0040, 0x00a4,\n 0x00b4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x009d, 0x00af, 0x00af, 0x00af, 0x009f, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x009e, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ba, 0x00be, 0x00c2, 0x00c3, 0x0040, 0x00c7,\n 0x00cb, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x00d0, 0x00cf, 0x00cf, 0x00cf, 0x00d3, 0x00d4, 0x00cf,\n 0x00cf, 0x00cf, 0x0040, 0x0040, 0x00d8, 0x00da, 0x00de, 0x0040,\n 0x00e2, 0x00e4, 0x00a9, 0x00b7, 0x00b7, 0x00b7, 0x00e8, 0x00b7,\n 0x00a6, 0x0040, 0x00a9, 0x00b7, 0x00b7, 0x00b7, 0x00ab, 0x00b7,\n 0x00a6, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x009e, 0x0040,\n 0x0040, 0x0040, 0x00b7, 0x00b7, 0x00b7, 0x00b7, 0x00b7, 0x00b7,\n 0x00b7, 0x00b7, 0x009e, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00cf,\n 0x00ef, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e1, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040, 0x0040,\n 0x00f2, 0x00f5, 0x00f9, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x00cf, 0x00fb, 0x00ee, 0x00fe, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x00df, 0x0040, 0x00dd, 0x00de,\n 0x00de, 0x0102, 0x0104, 0x0107, 0x003a, 0x00cf, 0x00cf, 0x010b,\n 0x010d, 0x0040, 0x0040, 0x00ec, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x0030, 0x0030, 0x0111, 0x0114, 0x0118, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x011c, 0x00cf, 0x011f, 0x00cf, 0x0122,\n 0x0125, 0x00ef, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040, 0x0040,\n 0x012b, 0x0117, 0x0040, 0x0040, 0x0040, 0x0040, 0x00cf, 0x00cf,\n 0x00cf, 0x00cf, 0x012f, 0x00e1, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00ed, 0x00cf, 0x00cf, 0x0133, 0x00de, 0x00de, 0x00de, 0x0030,\n 0x0030, 0x0129, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec,\n 0x00cf, 0x00cf, 0x0040, 0x0137, 0x013a, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x013e, 0x00cf, 0x0140, 0x0140, 0x0142,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0140, 0x0144, 0x0040, 0x0040, 0x00e2, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0148, 0x014a, 0x00cf,\n 0x00cf, 0x0040, 0x0040, 0x00ed, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x014d, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x0150, 0x0040, 0x0040, 0x0040, 0x0040, 0x0154, 0x0155,\n 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0157, 0x015b, 0x015e,\n 0x00cf, 0x0161, 0x0164, 0x0140, 0x00cf, 0x0155, 0x0155, 0x00ed,\n 0x0168, 0x0030, 0x0030, 0x0040, 0x0040, 0x0155, 0x0155, 0x016c,\n 0x00e1, 0x0040, 0x0170, 0x0170, 0x0154, 0x0155, 0x0155, 0x0174,\n 0x0155, 0x0177, 0x017a, 0x017c, 0x015b, 0x015e, 0x0180, 0x0183,\n 0x0186, 0x00de, 0x0189, 0x00de, 0x0176, 0x00ed, 0x018d, 0x0030,\n 0x0030, 0x0191, 0x0040, 0x0195, 0x0199, 0x019c, 0x00e1, 0x00e2,\n 0x00df, 0x0170, 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x00e4,\n 0x01a0, 0x01a1, 0x01a5, 0x01a8, 0x014a, 0x01aa, 0x0142, 0x017f,\n 0x00de, 0x00e1, 0x01ae, 0x00de, 0x018d, 0x0030, 0x0030, 0x00ef,\n 0x01b2, 0x00de, 0x00de, 0x019c, 0x00e1, 0x0040, 0x00e3, 0x00e3,\n 0x0154, 0x0155, 0x0155, 0x0174, 0x0155, 0x0174, 0x01b5, 0x017c,\n 0x015b, 0x015e, 0x0130, 0x01b9, 0x01bc, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x00ed, 0x018d, 0x0030, 0x0030, 0x01c0, 0x00de, 0x01c3,\n 0x00cf, 0x01c7, 0x00e1, 0x0040, 0x0170, 0x0170, 0x0154, 0x0155,\n 0x0155, 0x0174, 0x0155, 0x0174, 0x01b5, 0x017c, 0x01cb, 0x015e,\n 0x0180, 0x0183, 0x01bc, 0x00de, 0x019c, 0x00de, 0x0176, 0x00ed,\n 0x018d, 0x0030, 0x0030, 0x01cf, 0x0040, 0x00de, 0x00de, 0x01ab,\n 0x00e1, 0x00e2, 0x00d8, 0x00e4, 0x01a1, 0x01a0, 0x00e4, 0x00df,\n 0x00dd, 0x00e2, 0x00d8, 0x0040, 0x0040, 0x01a1, 0x01d3, 0x01d7,\n 0x01d3, 0x01d9, 0x01dc, 0x00dd, 0x0189, 0x00de, 0x00de, 0x018d,\n 0x0030, 0x0030, 0x0040, 0x0040, 0x01e0, 0x00de, 0x0161, 0x0118,\n 0x0040, 0x00e4, 0x00e4, 0x0154, 0x0155, 0x0155, 0x0174, 0x0155,\n 0x0155, 0x0155, 0x017c, 0x0125, 0x0161, 0x01e4, 0x019b, 0x01e7,\n 0x00de, 0x01ea, 0x01ee, 0x01f1, 0x00ed, 0x018d, 0x0030, 0x0030,\n 0x00de, 0x01f3, 0x0040, 0x0040, 0x016c, 0x01f6, 0x0040, 0x00e4,\n 0x00e4, 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x0040, 0x00e1,\n 0x01a1, 0x01cb, 0x01fa, 0x01fd, 0x01d9, 0x0142, 0x00de, 0x0201,\n 0x00de, 0x01a0, 0x00ed, 0x018d, 0x0030, 0x0030, 0x0204, 0x00de,\n 0x00de, 0x00de, 0x0160, 0x0040, 0x0040, 0x00e4, 0x00e4, 0x0154,\n 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0155, 0x0156, 0x015b,\n 0x015e, 0x01a5, 0x01d9, 0x0207, 0x00de, 0x01f7, 0x0040, 0x0040,\n 0x00ed, 0x018d, 0x0030, 0x0030, 0x0040, 0x0040, 0x020a, 0x0040,\n 0x01c7, 0x00e1, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00d8, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040, 0x0040, 0x01f1, 0x0040,\n 0x00e2, 0x017e, 0x0189, 0x015d, 0x020e, 0x01fa, 0x01fa, 0x00de,\n 0x018d, 0x0030, 0x0030, 0x01d3, 0x00dd, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x01a4, 0x00cf, 0x012f,\n 0x0211, 0x00de, 0x014a, 0x00cf, 0x0215, 0x0030, 0x0030, 0x0219,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x01a4, 0x00cf, 0x00cf, 0x0210,\n 0x00de, 0x00de, 0x00cf, 0x012f, 0x0030, 0x0030, 0x021d, 0x00de,\n 0x0221, 0x0224, 0x0228, 0x022c, 0x022e, 0x003f, 0x00ef, 0x0040,\n 0x0030, 0x0030, 0x0129, 0x0040, 0x0040, 0x0232, 0x0234, 0x0236,\n 0x0040, 0x0040, 0x0040, 0x00dd, 0x00f9, 0x00cf, 0x00cf, 0x023a,\n 0x00cf, 0x00fc, 0x0040, 0x0140, 0x00cf, 0x00cf, 0x00f9, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x023e, 0x0040,\n 0x0116, 0x0040, 0x00e4, 0x0242, 0x0040, 0x0246, 0x00de, 0x00de,\n 0x00de, 0x00f9, 0x024a, 0x00cf, 0x019c, 0x01a8, 0x0030, 0x0030,\n 0x0219, 0x0040, 0x00de, 0x01d3, 0x0142, 0x014b, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x00f9, 0x0210, 0x00de, 0x00de, 0x017e, 0x01a8,\n 0x00de, 0x017f, 0x0030, 0x0030, 0x021d, 0x017f, 0x0040, 0x00e3,\n 0x00de, 0x01f1, 0x0040, 0x0040, 0x0040, 0x0040, 0x024e, 0x024e,\n 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x0252, 0x0252,\n 0x0252, 0x0252, 0x0252, 0x0252, 0x0252, 0x0252, 0x0256, 0x0256,\n 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0040, 0x0040,\n 0x00e4, 0x01a1, 0x0040, 0x00e2, 0x00e4, 0x01a1, 0x0040, 0x0040,\n 0x00e4, 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4, 0x01a1,\n 0x0040, 0x00e2, 0x00e4, 0x01a1, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4, 0x01a1, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00f9, 0x025a, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01a1, 0x0040, 0x01a1, 0x025b, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x025b, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0058, 0x025f, 0x0040, 0x0040,\n 0x0263, 0x0266, 0x0040, 0x0040, 0x00dd, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x026a, 0x00de, 0x00df, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x026e, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x00e4, 0x0272, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0274, 0x00cf, 0x0160, 0x01fa, 0x01d5, 0x015e, 0x00cf, 0x00cf,\n 0x0278, 0x027c, 0x017f, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x01a1, 0x00de, 0x0280, 0x0284, 0x0288, 0x028b, 0x0030,\n 0x0030, 0x021d, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00dd, 0x00de, 0x0040, 0x00ee, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01b2, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0150, 0x028f, 0x0161,\n 0x00de, 0x01d5, 0x01fa, 0x015e, 0x00de, 0x00dd, 0x010f, 0x0030,\n 0x0030, 0x00de, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030, 0x0293,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec, 0x01c8,\n 0x00d8, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0296, 0x00cf,\n 0x012f, 0x020e, 0x00f9, 0x00cf, 0x0161, 0x028f, 0x00cf, 0x00cf,\n 0x01aa, 0x0030, 0x0030, 0x021d, 0x00de, 0x0030, 0x0030, 0x021d,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x012f, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x0299, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x024a, 0x0150, 0x0161,\n 0x01d5, 0x0299, 0x00de, 0x029b, 0x00de, 0x00de, 0x029b, 0x029f,\n 0x02a2, 0x02a3, 0x02a4, 0x00cf, 0x00cf, 0x02a3, 0x02a3, 0x029f,\n 0x0151, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x02a8, 0x0160, 0x0274, 0x00ef, 0x0030, 0x0030, 0x0129, 0x0040,\n 0x00de, 0x02ac, 0x0160, 0x02af, 0x0160, 0x00de, 0x00de, 0x0040,\n 0x01fa, 0x01fa, 0x00cf, 0x00cf, 0x015d, 0x029a, 0x02b3, 0x0030,\n 0x0030, 0x021d, 0x00e1, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0264, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040, 0x0040,\n 0x00de, 0x00de, 0x0215, 0x00cf, 0x00cf, 0x00cf, 0x024a, 0x00cf,\n 0x0118, 0x0117, 0x0040, 0x02b7, 0x02bb, 0x00de, 0x00cf, 0x00cf,\n 0x00cf, 0x02bf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf,\n 0x00cf, 0x02c0, 0x0040, 0x01a1, 0x0040, 0x01a1, 0x0040, 0x0040,\n 0x01af, 0x01af, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e4,\n 0x0040, 0x0040, 0x0040, 0x00d8, 0x0040, 0x00e1, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00d8, 0x00e4, 0x0040, 0x02c4, 0x02b3, 0x02c8,\n 0x02cc, 0x02d0, 0x02d4, 0x00c8, 0x02d8, 0x02d8, 0x02dc, 0x02e0,\n 0x02e4, 0x02e6, 0x02ea, 0x02ee, 0x02f2, 0x02f6, 0x0040, 0x02fa,\n 0x02fd, 0x0040, 0x0040, 0x02ff, 0x02b3, 0x0303, 0x0307, 0x030a,\n 0x00cf, 0x00cf, 0x01a1, 0x00c3, 0x0040, 0x030e, 0x0094, 0x00c3,\n 0x0040, 0x0312, 0x0040, 0x0040, 0x0040, 0x00dd, 0x0316, 0x0317,\n 0x0316, 0x031b, 0x0316, 0x031d, 0x0317, 0x031d, 0x031f, 0x0316,\n 0x0316, 0x0316, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x0323, 0x00a2, 0x0325, 0x0040, 0x00a0, 0x0327,\n 0x0040, 0x0040, 0x032a, 0x009d, 0x00a0, 0x0040, 0x0040, 0x0040,\n 0x032d, 0x0040, 0x0040, 0x0040, 0x0040, 0x0331, 0x0334, 0x0331,\n 0x00c8, 0x00c7, 0x00c7, 0x00c7, 0x0040, 0x00c7, 0x00c7, 0x0338,\n 0x0040, 0x0040, 0x00a2, 0x00de, 0x00c7, 0x033c, 0x033e, 0x0040,\n 0x0040, 0x0341, 0x0040, 0x0040, 0x0040, 0x00a6, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00a1, 0x00c3, 0x0040, 0x0040, 0x00b4, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0345, 0x00a0, 0x0348,\n 0x00a0, 0x034a, 0x00a2, 0x00a1, 0x0094, 0x0348, 0x0344, 0x00c7,\n 0x00ca, 0x0040, 0x00c7, 0x0040, 0x0338, 0x0040, 0x0040, 0x00c3,\n 0x00c3, 0x00a1, 0x0040, 0x0040, 0x0040, 0x0338, 0x00c7, 0x00c5,\n 0x00c5, 0x0040, 0x0040, 0x0040, 0x0040, 0x00c5, 0x00c5, 0x0040,\n 0x0040, 0x0040, 0x00a2, 0x00a2, 0x0040, 0x00a2, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00a0, 0x0040, 0x0040, 0x0040, 0x034e,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0352, 0x0040, 0x00a1, 0x0040,\n 0x0356, 0x0040, 0x0040, 0x035a, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x035e, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x035f,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0363, 0x0366, 0x036a, 0x0040,\n 0x036e, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x00c7, 0x0372, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x00c7, 0x0375, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x0378, 0x00c9,\n 0x00c7, 0x037c, 0x0040, 0x00c5, 0x0380, 0x0040, 0x0338, 0x0382,\n 0x00c5, 0x0348, 0x00c5, 0x0338, 0x0040, 0x0040, 0x0040, 0x00c5,\n 0x0338, 0x0040, 0x00a0, 0x0040, 0x0040, 0x035f, 0x0386, 0x038a,\n 0x038e, 0x0391, 0x0393, 0x036e, 0x0397, 0x039b, 0x039f, 0x03a3,\n 0x03a3, 0x03a3, 0x03a3, 0x03a7, 0x03a7, 0x03ab, 0x03a3, 0x03af,\n 0x03a3, 0x03a7, 0x03a7, 0x03a7, 0x03a3, 0x03a3, 0x03a3, 0x03b3,\n 0x03b3, 0x03b7, 0x03b3, 0x03a3, 0x03a3, 0x03a3, 0x0367, 0x03a3,\n 0x037e, 0x03bb, 0x03bd, 0x03a4, 0x03a3, 0x03a3, 0x0393, 0x03c1,\n 0x03a3, 0x03a5, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03c4, 0x038a,\n 0x03c5, 0x03c8, 0x03cb, 0x03ce, 0x03d2, 0x03c7, 0x03d6, 0x03d9,\n 0x03a3, 0x03dc, 0x033c, 0x03df, 0x03e3, 0x03e6, 0x03e9, 0x038a,\n 0x03ed, 0x03f1, 0x03f5, 0x036e, 0x03f8, 0x0040, 0x032d, 0x0040,\n 0x03fc, 0x0040, 0x035f, 0x035e, 0x0040, 0x009e, 0x0040, 0x0400,\n 0x0040, 0x0404, 0x0407, 0x040a, 0x040e, 0x0411, 0x0414, 0x03a2,\n 0x0352, 0x0352, 0x0352, 0x0418, 0x00c7, 0x00c7, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0363, 0x0040, 0x0040, 0x032d, 0x0040,\n 0x0040, 0x0040, 0x03fc, 0x0040, 0x0040, 0x0407, 0x0040, 0x041c,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x041f, 0x0352,\n 0x0352, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x037e, 0x0040,\n 0x0040, 0x0058, 0x0422, 0x0422, 0x0422, 0x0422, 0x0422, 0x0426,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0352, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0354, 0x0040,\n 0x0429, 0x0040, 0x0040, 0x0040, 0x0040, 0x0407, 0x03fc, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x03fc, 0x042d, 0x0338, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00d8, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e3, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00ef, 0x00de,\n 0x0431, 0x0434, 0x0040, 0x0040, 0x00de, 0x00df, 0x0437, 0x00de,\n 0x00de, 0x014a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x00de, 0x00de, 0x0040, 0x00e2, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x0040, 0x00e2, 0x0411, 0x0411, 0x0411, 0x043b, 0x02b3, 0x043d,\n 0x0441, 0x0445, 0x0449, 0x0352, 0x044b, 0x044d, 0x043d, 0x025b,\n 0x01a1, 0x0451, 0x0455, 0x02b3, 0x0451, 0x0453, 0x003c, 0x0459,\n 0x045b, 0x045f, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0465, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x00de, 0x00de, 0x00de, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0468, 0x00de, 0x00de, 0x00de, 0x00de, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x046c, 0x046f, 0x0473, 0x0473, 0x0475, 0x0473,\n 0x0473, 0x0479, 0x0463, 0x0463, 0x047d, 0x047f, 0x0483, 0x0486,\n 0x0488, 0x048b, 0x048f, 0x0491, 0x0486, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0491, 0x0463, 0x0485, 0x0463, 0x0493,\n 0x0496, 0x0499, 0x049d, 0x0491, 0x0486, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0484, 0x0491, 0x0463, 0x0485, 0x0463, 0x049f,\n 0x0488, 0x04a3, 0x00de, 0x0462, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0462, 0x0463, 0x0463, 0x0463, 0x0464, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0468, 0x00de, 0x04a7, 0x04ab, 0x04ab,\n 0x04ab, 0x04ab, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0464, 0x0463, 0x0463, 0x00c7, 0x00c7, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x04af, 0x04b1, 0x0463, 0x03bd, 0x03bd,\n 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x046f, 0x0463, 0x0463, 0x0463, 0x04a6,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0464, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x04b5, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0030, 0x0030, 0x0129, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x00ec, 0x0215, 0x00cf, 0x00cf, 0x00ef,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ed,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x04b9, 0x02b3, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x01a1, 0x00e3, 0x00e1, 0x0040, 0x00dd,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00d8, 0x0040, 0x0040, 0x0040,\n 0x0116, 0x0116, 0x00ec, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x01f7, 0x04bd, 0x0040, 0x0210, 0x0040, 0x0040, 0x04c1, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x04c5, 0x00de, 0x00de,\n 0x04c9, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x01fa, 0x01fa, 0x01fa, 0x0142, 0x00de, 0x029b, 0x0030, 0x0030,\n 0x021d, 0x00de, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00ef, 0x0040,\n 0x0040, 0x04cd, 0x0040, 0x00ed, 0x00cf, 0x04d0, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ec, 0x00cf, 0x00cf, 0x0160, 0x00de, 0x00de,\n 0x00df, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e, 0x024e,\n 0x04d4, 0x0150, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x014a, 0x015d, 0x0160, 0x0160, 0x04d8, 0x04d9, 0x02a1,\n 0x04dd, 0x00de, 0x00de, 0x00de, 0x04e1, 0x00de, 0x017f, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x00de, 0x00f9, 0x0150,\n 0x04bd, 0x01a8, 0x00de, 0x00de, 0x02b4, 0x02b3, 0x02b3, 0x026a,\n 0x00de, 0x00de, 0x00de, 0x029f, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0210, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x019b, 0x01aa, 0x0210, 0x014b, 0x017f, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x01f7, 0x0160,\n 0x0266, 0x04e5, 0x00de, 0x00de, 0x00e1, 0x00e2, 0x00e1, 0x00e2,\n 0x00e1, 0x00e2, 0x00de, 0x00de, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x01f7, 0x01d6, 0x04e9, 0x01dc, 0x0030, 0x0030, 0x021d,\n 0x00de, 0x04ed, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee,\n 0x04ed, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x04ee, 0x00de,\n 0x00de, 0x00de, 0x0252, 0x0252, 0x0252, 0x0252, 0x04f2, 0x04f5,\n 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x0256, 0x00de,\n 0x0040, 0x00e2, 0x00de, 0x00de, 0x00df, 0x0040, 0x00de, 0x01b1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x01ae,\n 0x00e3, 0x00e4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00e2, 0x00de, 0x00de, 0x00de, 0x00df, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x04f9, 0x0040, 0x0040, 0x00de,\n 0x00df, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x04fd, 0x00cf, 0x00cf, 0x00cf, 0x0501, 0x0505, 0x0508, 0x050c,\n 0x00de, 0x0510, 0x0512, 0x0511, 0x0513, 0x0463, 0x0472, 0x0517,\n 0x0517, 0x051b, 0x051f, 0x0463, 0x0523, 0x0527, 0x0472, 0x0474,\n 0x0463, 0x0464, 0x052b, 0x00de, 0x0040, 0x00e4, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x052f, 0x0533, 0x0537,\n 0x0475, 0x053b, 0x0463, 0x0463, 0x053e, 0x0542, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0546, 0x053c, 0x0463, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0546, 0x054a, 0x054e, 0x0551,\n 0x00de, 0x00de, 0x0554, 0x02a3, 0x02a3, 0x02a3, 0x02a3, 0x02a3,\n 0x02a3, 0x02a3, 0x0556, 0x02a3, 0x02a3, 0x02a3, 0x02a3, 0x02a3,\n 0x02a3, 0x02a3, 0x055a, 0x04e1, 0x02a3, 0x04e1, 0x02a3, 0x04e1,\n 0x02a3, 0x04e1, 0x055c, 0x0560, 0x0563, 0x0040, 0x00e2, 0x0000,\n 0x0000, 0x02e5, 0x0333, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e2, 0x00e3, 0x0040, 0x0040, 0x0040, 0x01a1, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x0567, 0x00df, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00df, 0x0040, 0x0040, 0x0040, 0x00e2,\n 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x056b,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd,\n 0x00de, 0x00de, 0x00de, 0x0118, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x012f, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x056f, 0x0040, 0x00de, 0x0040,\n 0x0040, 0x025b, 0x01a1, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00de, 0x00de, 0x00df, 0x0040, 0x0040, 0x00e2, 0x0040, 0x00e2,\n 0x00e3, 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040, 0x00e3, 0x00dd,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x0040, 0x00e3, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e4, 0x0040, 0x00e2, 0x00de, 0x0040,\n 0x01a1, 0x00e4, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e3,\n 0x00dd, 0x0170, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x056f,\n 0x0040, 0x0040, 0x00de, 0x00df, 0x0040, 0x0040, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x01a1,\n 0x00df, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x029a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1,\n 0x00df, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de,\n 0x0040, 0x0140, 0x01ea, 0x00de, 0x00cf, 0x0040, 0x00e1, 0x00e1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x012f, 0x014a,\n 0x0040, 0x0040, 0x00dd, 0x00de, 0x02b3, 0x02b3, 0x00dd, 0x00de,\n 0x0040, 0x0573, 0x00df, 0x0040, 0x02b3, 0x0577, 0x00de, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x02c7, 0x02b3,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01a1, 0x00de, 0x00e1, 0x00dd, 0x00de, 0x00de,\n 0x00e1, 0x0040, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x00dd, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x00e2, 0x00de, 0x00d8, 0x0040, 0x00cf, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040, 0x01a1, 0x00f9,\n 0x057b, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00d8,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040, 0x057e, 0x0581,\n 0x01a1, 0x00de, 0x00de, 0x00de, 0x00d8, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x0040, 0x00ed,\n 0x00cf, 0x00cf, 0x0118, 0x0040, 0x01a1, 0x00de, 0x00ed, 0x00ef,\n 0x01a1, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0297, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x00cf,\n 0x00fa, 0x02a2, 0x055b, 0x04e1, 0x02a3, 0x02a3, 0x02a3, 0x055b,\n 0x00de, 0x00de, 0x01aa, 0x0210, 0x00de, 0x0583, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x0150, 0x02ba, 0x0587, 0x0589, 0x00de,\n 0x00de, 0x058c, 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de,\n 0x0030, 0x0030, 0x021d, 0x00de, 0x0215, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec, 0x00cf, 0x015e, 0x00cf,\n 0x0590, 0x0030, 0x0030, 0x02b3, 0x0594, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00ec, 0x02c4, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01f7, 0x015d, 0x00cf, 0x0150, 0x0596,\n 0x0265, 0x059a, 0x01cb, 0x0030, 0x0030, 0x059e, 0x0303, 0x00e1,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x00dd, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x0160, 0x024a, 0x043d, 0x05a2, 0x056b,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x00e2, 0x00e4, 0x00e3, 0x0040, 0x0040, 0x0040, 0x00e3, 0x0040,\n 0x0040, 0x05a5, 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x028f,\n 0x00cf, 0x012f, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0160,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x014a,\n 0x05a9, 0x0161, 0x0183, 0x0183, 0x05ab, 0x00de, 0x0189, 0x00de,\n 0x04df, 0x01d3, 0x014b, 0x00cf, 0x0210, 0x00cf, 0x0210, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x05ad, 0x028f, 0x00cf, 0x05b1,\n 0x05b2, 0x01fb, 0x01d5, 0x05b6, 0x05b9, 0x055c, 0x00de, 0x01ea,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01f9, 0x00cf, 0x00cf, 0x015d,\n 0x0159, 0x0263, 0x0451, 0x0030, 0x0030, 0x0219, 0x01b1, 0x01a1,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x028f, 0x00cf, 0x02ae, 0x028f, 0x024a,\n 0x0040, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x01f7, 0x015d, 0x0142, 0x01fa, 0x0274, 0x05bd,\n 0x05c1, 0x0303, 0x02b3, 0x02b3, 0x02b3, 0x0040, 0x0142, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x028f, 0x00cf, 0x0150, 0x02af, 0x05c5,\n 0x00dd, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x05c9,\n 0x05c9, 0x05c9, 0x05cc, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x00ec, 0x01d6, 0x00cf, 0x0274, 0x01a1, 0x00de, 0x0030,\n 0x0030, 0x021d, 0x00de, 0x0030, 0x0030, 0x0030, 0x0030, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0249, 0x014b,\n 0x0274, 0x00cf, 0x00de, 0x0030, 0x0030, 0x021d, 0x0567, 0x0040,\n 0x0040, 0x0040, 0x028f, 0x00cf, 0x00cf, 0x02ba, 0x00de, 0x0030,\n 0x0030, 0x0129, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00df, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x01fa, 0x01d8, 0x05d0, 0x05d3, 0x05d7,\n 0x0567, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x01f9, 0x00cf, 0x014b, 0x01fa, 0x02c3,\n 0x0299, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0140,\n 0x00cf, 0x0215, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00ec,\n 0x00cf, 0x05da, 0x05dd, 0x0303, 0x05e1, 0x00de, 0x00de, 0x0140,\n 0x0150, 0x015e, 0x0040, 0x05e5, 0x05e7, 0x00cf, 0x00cf, 0x0150,\n 0x04d0, 0x05c7, 0x05eb, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x05c9, 0x05c9, 0x05cb, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x01a1, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030,\n 0x021d, 0x00de, 0x0040, 0x0040, 0x00e4, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x01f7, 0x00cf, 0x012f, 0x00cf, 0x0274, 0x0303,\n 0x05ec, 0x00de, 0x00de, 0x0030, 0x0030, 0x0129, 0x0040, 0x0040,\n 0x0040, 0x00dd, 0x05f0, 0x0040, 0x0040, 0x0040, 0x0040, 0x014b,\n 0x00cf, 0x00cf, 0x00cf, 0x05f4, 0x00cf, 0x024a, 0x01a8, 0x00de,\n 0x00de, 0x0040, 0x00e2, 0x00e3, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0140, 0x012f, 0x017e, 0x0130, 0x00cf, 0x05f6, 0x00de,\n 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040, 0x00e3, 0x00e4,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x01f8, 0x01fb, 0x05f9,\n 0x02af, 0x00dd, 0x00de, 0x0030, 0x0030, 0x021d, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x05fd, 0x04e9, 0x0437, 0x00de, 0x0600,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x015d,\n 0x012f, 0x01d3, 0x0275, 0x02a2, 0x02a3, 0x02a3, 0x00de, 0x00de,\n 0x017e, 0x00de, 0x00de, 0x00de, 0x00de, 0x00dd, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0107, 0x04fd, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de,\n 0x029a, 0x0040, 0x0040, 0x0040, 0x00e2, 0x02b3, 0x0437, 0x00de,\n 0x00de, 0x0040, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0604,\n 0x0607, 0x0609, 0x041f, 0x0354, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x060c, 0x0040, 0x0040, 0x0040, 0x0058, 0x00d3,\n 0x0610, 0x0614, 0x0618, 0x0118, 0x00ec, 0x00cf, 0x00cf, 0x00cf,\n 0x0142, 0x00de, 0x00de, 0x0040, 0x0040, 0x0040, 0x041f, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x014b, 0x00cf, 0x00cf, 0x0160, 0x015e,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x0030, 0x0030, 0x021d, 0x029b,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00cf, 0x0581, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00cf, 0x00fa, 0x0266,\n 0x0040, 0x061c, 0x00de, 0x00de, 0x0030, 0x0030, 0x0620, 0x0040,\n 0x00e3, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x00de, 0x00e1,\n 0x0623, 0x0623, 0x0626, 0x0264, 0x0030, 0x0030, 0x021d, 0x00de,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0263, 0x057d, 0x00de,\n 0x0040, 0x0040, 0x00e2, 0x014a, 0x01f9, 0x01fa, 0x01fa, 0x01fa,\n 0x01fa, 0x01fa, 0x01fa, 0x01fa, 0x01fa, 0x00de, 0x014a, 0x0215,\n 0x0040, 0x0040, 0x0040, 0x062a, 0x062e, 0x00de, 0x00de, 0x0632,\n 0x00de, 0x00de, 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd,\n 0x0636, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x0638, 0x0463, 0x0463, 0x04a6, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x03bd, 0x063a, 0x03bd, 0x0635, 0x0464, 0x00de, 0x00de,\n 0x00de, 0x063e, 0x00de, 0x00de, 0x00de, 0x00de, 0x0642, 0x0645,\n 0x00de, 0x00de, 0x04ab, 0x00de, 0x00de, 0x0463, 0x0463, 0x0463,\n 0x0463, 0x0040, 0x0040, 0x00e2, 0x00de, 0x0040, 0x0040, 0x0040,\n 0x00dd, 0x00de, 0x0040, 0x0040, 0x01a1, 0x04cf, 0x00cf, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0030, 0x0030, 0x021d, 0x00de, 0x00cf, 0x00cf,\n 0x00cf, 0x0142, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x012f, 0x00de,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x00e2, 0x00e1, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x015c, 0x00ef, 0x01f9, 0x028f,\n 0x00cf, 0x00cf, 0x00cf, 0x0215, 0x0140, 0x00cf, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00ed, 0x00ef, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00ed, 0x0133, 0x00de, 0x00de, 0x00de, 0x00de, 0x00de,\n 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x063b, 0x00de,\n 0x00de, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x03bd, 0x0649, 0x00dd,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x00e4, 0x0144, 0x01a0, 0x00e1, 0x00e4, 0x0040, 0x0040, 0x00e3,\n 0x00e1, 0x0040, 0x00e1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x00e3, 0x00e2, 0x00e1, 0x0040, 0x00e4, 0x0040, 0x00e4,\n 0x0040, 0x01ae, 0x00d8, 0x0040, 0x00e4, 0x0040, 0x0040, 0x0040,\n 0x01a1, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x018d,\n 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,\n 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x00cf, 0x0215, 0x00ec, 0x00cf,\n 0x00cf, 0x00cf, 0x0118, 0x0040, 0x0117, 0x0040, 0x0040, 0x064d,\n 0x0451, 0x00de, 0x00de, 0x00de, 0x014a, 0x00cf, 0x00f9, 0x00cf,\n 0x00cf, 0x00cf, 0x00de, 0x00de, 0x00de, 0x00de, 0x00e1, 0x00e2,\n 0x00de, 0x00de, 0x00de, 0x00de, 0x00de, 0x00cf, 0x012f, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x01aa, 0x00cf, 0x0130, 0x019b, 0x012f,\n 0x00de, 0x0040, 0x0040, 0x0040, 0x0040, 0x01a1, 0x00de, 0x00de,\n 0x00de, 0x00de, 0x014a, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00dd, 0x00cf, 0x0215, 0x0040, 0x01a1, 0x0030,\n 0x0030, 0x021d, 0x00d8, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x0199, 0x00de, 0x00de, 0x00de, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00cf, 0x0030, 0x0030, 0x021d, 0x0211, 0x0040,\n 0x0040, 0x0040, 0x00cf, 0x0030, 0x0030, 0x021d, 0x00de, 0x0040,\n 0x0040, 0x0040, 0x00ed, 0x0651, 0x0030, 0x0293, 0x00df, 0x0040,\n 0x00e2, 0x0040, 0x01a0, 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040,\n 0x0170, 0x0040, 0x0040, 0x00cf, 0x012f, 0x00de, 0x00de, 0x0040,\n 0x00cf, 0x0215, 0x00de, 0x0030, 0x0030, 0x021d, 0x0655, 0x00de,\n 0x00de, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040, 0x04fd,\n 0x04fd, 0x00dd, 0x00de, 0x00de, 0x00e1, 0x0040, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x0040, 0x01a0, 0x0170, 0x00e1, 0x0040,\n 0x00e2, 0x0040, 0x01af, 0x00de, 0x0144, 0x00df, 0x01af, 0x00e1,\n 0x01a0, 0x0170, 0x01af, 0x01af, 0x01a0, 0x0170, 0x00e2, 0x0040,\n 0x00e2, 0x0040, 0x00e1, 0x01ae, 0x0040, 0x0040, 0x00e3, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00de, 0x00e1, 0x00e1, 0x00e3, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00de, 0x038a, 0x0659, 0x038a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x065a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x00c7, 0x00c7, 0x065e, 0x0661, 0x00c7,\n 0x00c7, 0x00c7, 0x00c7, 0x0665, 0x00c7, 0x00c7, 0x00c7, 0x00c7,\n 0x0338, 0x03a3, 0x0669, 0x00c7, 0x00c7, 0x066b, 0x00c7, 0x00c7,\n 0x00c7, 0x066f, 0x0672, 0x0673, 0x0674, 0x00c7, 0x00c7, 0x00c7,\n 0x0677, 0x038a, 0x038a, 0x038a, 0x038a, 0x0679, 0x067b, 0x067b,\n 0x067b, 0x067b, 0x067b, 0x067b, 0x067f, 0x038a, 0x038a, 0x038a,\n 0x0463, 0x0463, 0x04b0, 0x0463, 0x0463, 0x0463, 0x04af, 0x0683,\n 0x0685, 0x0686, 0x038a, 0x0463, 0x0463, 0x0689, 0x038a, 0x03f3,\n 0x038a, 0x038a, 0x038a, 0x0685, 0x03f3, 0x038a, 0x038a, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0685, 0x0659, 0x038a, 0x038a, 0x068c, 0x0685,\n 0x068e, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068f, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x038a, 0x038a,\n 0x0693, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0697, 0x0685,\n 0x0699, 0x0685, 0x0685, 0x068d, 0x065a, 0x0685, 0x038a, 0x038a,\n 0x038a, 0x0685, 0x0685, 0x0685, 0x0685, 0x0659, 0x0659, 0x069a,\n 0x069d, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068d, 0x068f, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x0685, 0x06a1, 0x0699, 0x0685, 0x06a4, 0x0697, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x036a, 0x03a7, 0x06a7,\n 0x0685, 0x0685, 0x0685, 0x06a4, 0x03a7, 0x03a7, 0x0699, 0x0685,\n 0x0685, 0x06a5, 0x03a7, 0x03a7, 0x06ab, 0x0040, 0x0340, 0x06af,\n 0x068d, 0x0685, 0x0685, 0x0685, 0x0685, 0x038a, 0x038a, 0x038a,\n 0x038a, 0x06b3, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x03f2,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x03a3, 0x03a3, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x03a3, 0x06af, 0x0685, 0x0685,\n 0x0685, 0x0685, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x040f,\n 0x06b7, 0x0040, 0x0685, 0x03f3, 0x038a, 0x0659, 0x068d, 0x068c,\n 0x038a, 0x0685, 0x038a, 0x038a, 0x065a, 0x0659, 0x038a, 0x0685,\n 0x0685, 0x0659, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x038a,\n 0x038a, 0x038a, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0389,\n 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x038a, 0x0659, 0x038a,\n 0x038a, 0x038a, 0x0040, 0x0040, 0x0040, 0x06bb, 0x0040, 0x0040,\n 0x0040, 0x0040, 0x06bb, 0x06bb, 0x0040, 0x0040, 0x06bf, 0x06bb,\n 0x0040, 0x0040, 0x06bb, 0x06bb, 0x0040, 0x0040, 0x0040, 0x0040,\n 0x06bf, 0x03a3, 0x03a3, 0x03a3, 0x06bb, 0x06c3, 0x06bb, 0x06bb,\n 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x06bb, 0x0040, 0x0040,\n 0x0040, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x06c7,\n 0x0685, 0x06c8, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3, 0x03a3,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x0685, 0x0685, 0x0685, 0x0659,\n 0x0685, 0x0685, 0x03f3, 0x065a, 0x0685, 0x0685, 0x0685, 0x0685,\n 0x068d, 0x038a, 0x03f1, 0x0685, 0x0685, 0x0685, 0x036a, 0x0685,\n 0x0685, 0x03f3, 0x038a, 0x0685, 0x0685, 0x0659, 0x038a, 0x0040,\n 0x0040, 0x0040, 0x0040, 0x00e2, 0x0040, 0x0040, 0x0040, 0x038a,\n 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x038a, 0x06cc, 0x0463,\n 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0463, 0x0468, 0x06d0,\n 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00cf,\n 0x00cf, 0x00cf, 0x00cf, 0x0000, 0x0000, 0x0000, 0x0000, 0x00c7,\n 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x00c7, 0x06d4,\n];\n#[rustfmt::skip]\nconst STAGE3: [u16; 1752] = [\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0963, 0x0802, 0x0803,\n 0x0803, 0x0801, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0803, 0x0803, 0x0803, 0x0803,\n 0x0900, 0x0ac0, 0x0c00, 0x0d80,\n 0x0d00, 0x0cc0, 0x0d80, 0x0c00,\n 0x0bc0, 0x0a80, 0x0d80, 0x0d00,\n 0x0c40, 0x09c0, 0x0c40, 0x0d40,\n 0x0c80, 0x0c80, 0x0c80, 0x0c80,\n 0x0c80, 0x0c80, 0x0c80, 0x0c80,\n 0x0c80, 0x0c80, 0x0c40, 0x0c40,\n 0x0d80, 0x0d80, 0x0d80, 0x0ac0,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0bc0,\n 0x0d00, 0x0a80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0bc0,\n 0x0940, 0x0a00, 0x0d80, 0x0803,\n 0x08c0, 0x1bc0, 0x0cc0, 0x0d00,\n 0x1d00, 0x0d00, 0x0d80, 0x1800,\n 0x0d8e, 0x1800, 0x0c00, 0x0d80,\n 0x0944, 0x1d8e, 0x0d80, 0x1cc0,\n 0x1d00, 0x1800, 0x1800, 0x1980,\n 0x0d80, 0x1800, 0x1800, 0x1800,\n 0x0c00, 0x1800, 0x1800, 0x1800,\n 0x1bc0, 0x0d80, 0x0d80, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x1800,\n 0x0d80, 0x0d80, 0x1d80, 0x1d80,\n 0x0d80, 0x0d80, 0x1d80, 0x1d80,\n 0x1d80, 0x0d80, 0x1d80, 0x1d80,\n 0x0d80, 0x1d80, 0x0d80, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x1d80,\n 0x1d80, 0x1d80, 0x1d80, 0x0d80,\n 0x0d80, 0x1800, 0x0980, 0x1800,\n 0x1800, 0x1800, 0x0980, 0x1800,\n 0x0d80, 0x0d80, 0x0d80, 0x1800,\n 0x1800, 0x1800, 0x1800, 0x0d80,\n 0x1800, 0x0d80, 0x1980, 0x0004,\n 0x0004, 0x0004, 0x0004, 0x00c4,\n 0x00c4, 0x00c4, 0x00c4, 0x0004,\n 0x0800, 0x0800, 0x0d80, 0x0d80,\n 0x0c40, 0x0d80, 0x0800, 0x0800,\n 0x0800, 0x0800, 0x0d80, 0x0d80,\n 0x0d80, 0x0800, 0x0d80, 0x0d80,\n 0x1d80, 0x1d80, 0x0800, 0x1d80,\n 0x0d80, 0x0d80, 0x0d80, 0x0004,\n 0x0004, 0x0d80, 0x0d80, 0x0c40,\n 0x0940, 0x0800, 0x0d80, 0x0d80,\n 0x0d00, 0x0800, 0x0004, 0x0004,\n 0x0004, 0x0940, 0x0004, 0x0004,\n 0x0ac0, 0x0004, 0x0486, 0x0486,\n 0x0486, 0x0486, 0x0d80, 0x0d80,\n 0x0cc0, 0x0cc0, 0x0cc0, 0x0004,\n 0x0004, 0x0004, 0x0ac0, 0x0ac0,\n 0x0ac0, 0x0c80, 0x0c80, 0x0cc0,\n 0x0c80, 0x0d80, 0x0d80, 0x0d80,\n 0x0004, 0x0d80, 0x0d80, 0x0d80,\n 0x0ac0, 0x0d80, 0x0004, 0x0004,\n 0x0486, 0x0d80, 0x0004, 0x0d80,\n 0x0d80, 0x0004, 0x0d80, 0x0004,\n 0x0004, 0x0c80, 0x0c80, 0x0d80,\n 0x0d80, 0x0800, 0x0586, 0x0004,\n 0x0004, 0x0004, 0x0800, 0x0004,\n 0x0d80, 0x0800, 0x0800, 0x0c40,\n 0x0ac0, 0x0d80, 0x0800, 0x0004,\n 0x0d00, 0x0d00, 0x0004, 0x0004,\n 0x0d80, 0x0004, 0x0004, 0x0004,\n 0x0800, 0x0800, 0x0d80, 0x0800,\n 0x0486, 0x0486, 0x0800, 0x0800,\n 0x0800, 0x0004, 0x0004, 0x0486,\n 0x0004, 0x0004, 0x0004, 0x0804,\n 0x0d80, 0x0d8d, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0004, 0x0804, 0x0004,\n 0x0d80, 0x0804, 0x0804, 0x0004,\n 0x0004, 0x0004, 0x0804, 0x0804,\n 0x0804, 0x000c, 0x0804, 0x0804,\n 0x0940, 0x0940, 0x0c80, 0x0c80,\n 0x0d80, 0x0004, 0x0804, 0x0804,\n 0x0d80, 0x0800, 0x0800, 0x0d80,\n 0x0d8d, 0x0800, 0x0d8d, 0x0d8d,\n 0x0800, 0x0d8d, 0x0800, 0x0800,\n 0x0d8d, 0x0d8d, 0x0800, 0x0800,\n 0x0004, 0x0800, 0x0800, 0x0804,\n 0x0800, 0x0800, 0x0804, 0x000c,\n 0x0d80, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0c80,\n 0x0c80, 0x0d8d, 0x0d8d, 0x0cc0,\n 0x0cc0, 0x0d80, 0x0cc0, 0x0d80,\n 0x0d00, 0x0d80, 0x0d80, 0x0004,\n 0x0800, 0x0004, 0x0004, 0x0804,\n 0x0800, 0x0d80, 0x0d80, 0x0800,\n 0x0800, 0x0004, 0x0800, 0x0804,\n 0x0804, 0x0004, 0x0004, 0x0800,\n 0x0800, 0x0004, 0x0d80, 0x0800,\n 0x0d80, 0x0800, 0x0d80, 0x0004,\n 0x0d80, 0x0800, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0004, 0x0804, 0x0800,\n 0x0804, 0x000c, 0x0800, 0x0800,\n 0x0d80, 0x0d00, 0x0800, 0x0800,\n 0x0d8d, 0x0004, 0x0004, 0x0800,\n 0x0004, 0x0804, 0x0804, 0x0004,\n 0x0d80, 0x0804, 0x0004, 0x0d80,\n 0x0d8d, 0x0d80, 0x0d80, 0x0800,\n 0x0800, 0x0804, 0x0804, 0x0004,\n 0x0804, 0x0804, 0x0800, 0x0804,\n 0x0804, 0x0004, 0x0800, 0x0800,\n 0x0d80, 0x0d00, 0x0d80, 0x0800,\n 0x0804, 0x0800, 0x0004, 0x0004,\n 0x000c, 0x0800, 0x0800, 0x0004,\n 0x0004, 0x0800, 0x0d8d, 0x0d8d,\n 0x0d8d, 0x0800, 0x0d80, 0x0800,\n 0x0800, 0x0800, 0x0980, 0x0d80,\n 0x0d80, 0x0d80, 0x0804, 0x0804,\n 0x0804, 0x0804, 0x0800, 0x0004,\n 0x0804, 0x0800, 0x0804, 0x0804,\n 0x0800, 0x0d80, 0x0d80, 0x0804,\n 0x000c, 0x0d86, 0x0d80, 0x0cc0,\n 0x0d80, 0x0d80, 0x0004, 0x0800,\n 0x0004, 0x0800, 0x0800, 0x0800,\n 0x0d00, 0x0004, 0x0004, 0x0004,\n 0x0d80, 0x0c80, 0x0c80, 0x0940,\n 0x0940, 0x0c80, 0x0c80, 0x0800,\n 0x0800, 0x0d80, 0x0980, 0x0980,\n 0x0980, 0x0d80, 0x0980, 0x0980,\n 0x08c0, 0x0980, 0x0980, 0x0940,\n 0x08c0, 0x0ac0, 0x0ac0, 0x0ac0,\n 0x08c0, 0x0d80, 0x0940, 0x0004,\n 0x0d80, 0x0004, 0x0bc0, 0x0a00,\n 0x0804, 0x0804, 0x0004, 0x0004,\n 0x0004, 0x0944, 0x0004, 0x0800,\n 0x0940, 0x0940, 0x0980, 0x0980,\n 0x0940, 0x0980, 0x0d80, 0x08c0,\n 0x08c0, 0x0800, 0x0004, 0x0804,\n 0x0004, 0x0004, 0x1007, 0x1007,\n 0x1007, 0x1007, 0x0808, 0x0808,\n 0x0808, 0x0808, 0x0809, 0x0809,\n 0x0809, 0x0809, 0x0d80, 0x0940,\n 0x0d80, 0x0d80, 0x0d80, 0x0a00,\n 0x0800, 0x0800, 0x0800, 0x0d80,\n 0x0d80, 0x0d80, 0x0940, 0x0940,\n 0x0d80, 0x0d80, 0x0004, 0x0804,\n 0x0800, 0x0800, 0x0804, 0x0940,\n 0x0940, 0x0800, 0x0d80, 0x0800,\n 0x0004, 0x0004, 0x0804, 0x0004,\n 0x0940, 0x0940, 0x0b40, 0x0800,\n 0x0940, 0x0d80, 0x0940, 0x0d00,\n 0x0d80, 0x0d80, 0x0ac0, 0x0ac0,\n 0x0940, 0x0940, 0x0980, 0x0d80,\n 0x0ac0, 0x0ac0, 0x0d80, 0x0004,\n 0x0004, 0x00c4, 0x0004, 0x0804,\n 0x0804, 0x0804, 0x0004, 0x0c80,\n 0x0c80, 0x0c80, 0x0800, 0x0804,\n 0x0004, 0x0804, 0x0800, 0x0800,\n 0x0800, 0x0940, 0x0940, 0x0dc0,\n 0x0940, 0x0940, 0x0940, 0x0dc0,\n 0x0dc0, 0x0dc0, 0x0dc0, 0x0004,\n 0x0d80, 0x0804, 0x0004, 0x0004,\n 0x0800, 0x0800, 0x0004, 0x0804,\n 0x0004, 0x0804, 0x0004, 0x0940,\n 0x0940, 0x0940, 0x0940, 0x0004,\n 0x0d80, 0x0d80, 0x0804, 0x0004,\n 0x0004, 0x0d80, 0x0800, 0x0004,\n 0x00c4, 0x0004, 0x0004, 0x0004,\n 0x0d80, 0x0980, 0x0d80, 0x0800,\n 0x0940, 0x0940, 0x0940, 0x08c0,\n 0x0940, 0x0940, 0x0940, 0x0084,\n 0x0004, 0x000f, 0x0004, 0x0004,\n 0x1940, 0x08c0, 0x0940, 0x1940,\n 0x1c00, 0x1c00, 0x0bc0, 0x0c00,\n 0x1800, 0x1800, 0x1d80, 0x0d80,\n 0x1b00, 0x1b00, 0x1b00, 0x1940,\n 0x0803, 0x0803, 0x0004, 0x0004,\n 0x0004, 0x08c0, 0x1cc0, 0x0cc0,\n 0x1cc0, 0x1cc0, 0x0cc0, 0x1cc0,\n 0x0cc0, 0x0cc0, 0x0d80, 0x0c00,\n 0x0c00, 0x1800, 0x0b4e, 0x0b40,\n 0x1d80, 0x0d80, 0x0c40, 0x0bc0,\n 0x0a00, 0x0b40, 0x0b4e, 0x0d80,\n 0x0d80, 0x0940, 0x0cc0, 0x0d80,\n 0x0940, 0x0940, 0x0940, 0x0044,\n 0x0584, 0x0584, 0x0584, 0x0803,\n 0x0004, 0x0004, 0x0d80, 0x0bc0,\n 0x0a00, 0x1800, 0x0d80, 0x0bc0,\n 0x0a00, 0x0800, 0x0d00, 0x0d00,\n 0x0d00, 0x0d00, 0x0cc0, 0x1d00,\n 0x0d00, 0x0d00, 0x0d00, 0x0cc0,\n 0x0d00, 0x0d00, 0x0d00, 0x0d80,\n 0x0d80, 0x0d80, 0x1cc0, 0x0d80,\n 0x0d80, 0x1d00, 0x0d80, 0x1800,\n 0x180e, 0x0d80, 0x0d8e, 0x0d80,\n 0x0d80, 0x0800, 0x0800, 0x0800,\n 0x1800, 0x0800, 0x0800, 0x0800,\n 0x1800, 0x1800, 0x0d80, 0x0d80,\n 0x180e, 0x180e, 0x180e, 0x180e,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d8e,\n 0x0d80, 0x1800, 0x0d80, 0x1800,\n 0x1800, 0x0d80, 0x0d80, 0x1800,\n 0x0d00, 0x0d00, 0x0d80, 0x0d80,\n 0x0d80, 0x0b00, 0x0bc0, 0x0a00,\n 0x0bc0, 0x0a00, 0x0d80, 0x0d80,\n 0x15ce, 0x15ce, 0x0d8e, 0x1380,\n 0x1200, 0x0d80, 0x0d8e, 0x0d80,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d80,\n 0x158e, 0x158e, 0x158e, 0x0d8e,\n 0x0d8e, 0x0d8e, 0x15ce, 0x0dce,\n 0x0dce, 0x15ce, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x0d80, 0x1800, 0x1800,\n 0x180e, 0x1800, 0x1800, 0x0800,\n 0x1800, 0x1800, 0x1800, 0x1d80,\n 0x1800, 0x1800, 0x0d8e, 0x0d8e,\n 0x0d80, 0x0d80, 0x180e, 0x1800,\n 0x0d80, 0x0d80, 0x0d8e, 0x158e,\n 0x158e, 0x0d80, 0x0dce, 0x0dce,\n 0x0dce, 0x0dce, 0x0d8e, 0x180e,\n 0x1800, 0x0d8e, 0x180e, 0x0d8e,\n 0x0d8e, 0x180e, 0x180e, 0x15ce,\n 0x15ce, 0x080e, 0x080e, 0x0dce,\n 0x0d8e, 0x0dce, 0x0dce, 0x1dce,\n 0x0dce, 0x1dce, 0x0dce, 0x0d8e,\n 0x0d8e, 0x0d8e, 0x0d8e, 0x158e,\n 0x158e, 0x158e, 0x158e, 0x0d8e,\n 0x0dce, 0x0dce, 0x0dce, 0x180e,\n 0x0d8e, 0x180e, 0x0d8e, 0x180e,\n 0x180e, 0x0d8e, 0x180e, 0x1dce,\n 0x180e, 0x180e, 0x0d8e, 0x0d80,\n 0x0d80, 0x1580, 0x1580, 0x1580,\n 0x1580, 0x0d8e, 0x158e, 0x0d8e,\n 0x0d8e, 0x15ce, 0x15ce, 0x1dce,\n 0x1dce, 0x180e, 0x180e, 0x180e,\n 0x1dce, 0x158e, 0x1dce, 0x1dce,\n 0x180e, 0x1dce, 0x15ce, 0x180e,\n 0x180e, 0x180e, 0x1dce, 0x180e,\n 0x180e, 0x1dce, 0x1dce, 0x0d8e,\n 0x180e, 0x180e, 0x15ce, 0x180e,\n 0x1dce, 0x15ce, 0x15ce, 0x1dce,\n 0x15ce, 0x180e, 0x1dce, 0x1dce,\n 0x15ce, 0x180e, 0x15ce, 0x1dce,\n 0x1dce, 0x0dce, 0x158e, 0x0d80,\n 0x0d80, 0x0dce, 0x0dce, 0x15ce,\n 0x15ce, 0x0dce, 0x0dce, 0x0d8e,\n 0x0d8e, 0x0d80, 0x0d8e, 0x0d80,\n 0x158e, 0x0d80, 0x0d80, 0x0d80,\n 0x0d8e, 0x0d80, 0x0d80, 0x0d8e,\n 0x158e, 0x0d80, 0x158e, 0x0d80,\n 0x0d80, 0x0d80, 0x158e, 0x158e,\n 0x0d80, 0x100e, 0x0d80, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0c00,\n 0x0c00, 0x0d80, 0x0ac0, 0x0ace,\n 0x0bc0, 0x0a00, 0x1800, 0x1800,\n 0x0d80, 0x0bc0, 0x0a00, 0x0d80,\n 0x0d80, 0x0bc0, 0x0a00, 0x0bc0,\n 0x0a00, 0x0bc0, 0x0a00, 0x0d80,\n 0x0d80, 0x0d80, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x0d80, 0x100e, 0x1800,\n 0x1800, 0x0800, 0x0ac0, 0x0940,\n 0x0940, 0x0d80, 0x0ac0, 0x0940,\n 0x0800, 0x0800, 0x0800, 0x0c00,\n 0x0c00, 0x0940, 0x0940, 0x0d80,\n 0x0940, 0x0bc0, 0x0940, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0d80,\n 0x0d80, 0x0c00, 0x0c00, 0x0bc0,\n 0x0a00, 0x0940, 0x0940, 0x0ac0,\n 0x0d80, 0x0940, 0x0940, 0x0940,\n 0x0d80, 0x0940, 0x0940, 0x0bc0,\n 0x0940, 0x0ac0, 0x0bc0, 0x0a80,\n 0x0bc0, 0x0a80, 0x0bc0, 0x0a80,\n 0x0940, 0x0800, 0x0800, 0x15c0,\n 0x15c0, 0x15c0, 0x15c0, 0x0800,\n 0x15c0, 0x15c0, 0x0800, 0x0800,\n 0x1140, 0x1200, 0x1200, 0x15c0,\n 0x1340, 0x15c0, 0x15c0, 0x1380,\n 0x1200, 0x1380, 0x1200, 0x15c0,\n 0x15c0, 0x1340, 0x1380, 0x1200,\n 0x1200, 0x15c0, 0x15c0, 0x0004,\n 0x0004, 0x1004, 0x1004, 0x15ce,\n 0x15c0, 0x15c0, 0x15c0, 0x1000,\n 0x15c0, 0x15c0, 0x15c0, 0x1340,\n 0x15ce, 0x15c0, 0x0dc0, 0x0800,\n 0x1000, 0x15c0, 0x1000, 0x15c0,\n 0x1000, 0x1000, 0x0800, 0x0004,\n 0x0004, 0x1340, 0x1340, 0x1340,\n 0x15c0, 0x1340, 0x1000, 0x15c0,\n 0x1000, 0x1000, 0x15c0, 0x1000,\n 0x1340, 0x1340, 0x15c0, 0x0800,\n 0x0800, 0x0800, 0x15c0, 0x1000,\n 0x1000, 0x1000, 0x1000, 0x15c0,\n 0x15c0, 0x15c0, 0x15ce, 0x15c0,\n 0x15c0, 0x0d80, 0x0940, 0x0ac0,\n 0x0940, 0x0004, 0x0004, 0x0d80,\n 0x0940, 0x0804, 0x0004, 0x0004,\n 0x0804, 0x0cc0, 0x0d80, 0x0800,\n 0x0800, 0x0980, 0x0980, 0x0ac0,\n 0x0ac0, 0x0804, 0x0804, 0x0d80,\n 0x0d80, 0x0980, 0x0d80, 0x0d80,\n 0x0004, 0x0004, 0x0940, 0x0940,\n 0x1007, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0dc0, 0x0dc0, 0x0dc0,\n 0x0940, 0x0dc0, 0x0dc0, 0x0800,\n 0x0940, 0x0800, 0x0800, 0x0dc0,\n 0x0dc0, 0x0d80, 0x0804, 0x0004,\n 0x0800, 0x0004, 0x0804, 0x0804,\n 0x0940, 0x100a, 0x100b, 0x100b,\n 0x100b, 0x100b, 0x0808, 0x0808,\n 0x0808, 0x0800, 0x0800, 0x0800,\n 0x0809, 0x0d80, 0x0d80, 0x0a00,\n 0x0bc0, 0x0cc0, 0x0d80, 0x0d80,\n 0x0d80, 0x0004, 0x0004, 0x0004,\n 0x1004, 0x1200, 0x1200, 0x1200,\n 0x1340, 0x12c0, 0x12c0, 0x1380,\n 0x1200, 0x1300, 0x0800, 0x0800,\n 0x00c4, 0x0004, 0x00c4, 0x0004,\n 0x00c4, 0x00c4, 0x0004, 0x1200,\n 0x1380, 0x1200, 0x1380, 0x1200,\n 0x15c0, 0x15c0, 0x1380, 0x1200,\n 0x15c0, 0x15c0, 0x15c0, 0x1200,\n 0x15c0, 0x1200, 0x0800, 0x1340,\n 0x1340, 0x12c0, 0x12c0, 0x15c0,\n 0x1500, 0x14c0, 0x15c0, 0x0d80,\n 0x0800, 0x0800, 0x0044, 0x0800,\n 0x12c0, 0x15c0, 0x15c0, 0x1500,\n 0x14c0, 0x15c0, 0x15c0, 0x1200,\n 0x15c0, 0x1200, 0x15c0, 0x15c0,\n 0x1340, 0x1340, 0x15c0, 0x15c0,\n 0x15c0, 0x12c0, 0x15c0, 0x15c0,\n 0x15c0, 0x1380, 0x15c0, 0x1200,\n 0x15c0, 0x1380, 0x1200, 0x0a00,\n 0x0b80, 0x0a00, 0x0b40, 0x0dc0,\n 0x0800, 0x0dc0, 0x0dc0, 0x0dc0,\n 0x0b44, 0x0b44, 0x0dc0, 0x0dc0,\n 0x0dc0, 0x0800, 0x0800, 0x0800,\n 0x14c0, 0x1500, 0x15c0, 0x15c0,\n 0x1500, 0x1500, 0x0800, 0x0940,\n 0x0940, 0x0940, 0x0800, 0x0d80,\n 0x0004, 0x0800, 0x0800, 0x0d80,\n 0x0d80, 0x0800, 0x0940, 0x0d80,\n 0x0004, 0x0004, 0x0800, 0x0940,\n 0x0940, 0x0b00, 0x0800, 0x0004,\n 0x0004, 0x0940, 0x0d80, 0x0d80,\n 0x0800, 0x0004, 0x0940, 0x0800,\n 0x0800, 0x0800, 0x00c4, 0x0d80,\n 0x0486, 0x0940, 0x0940, 0x0004,\n 0x0800, 0x0486, 0x0800, 0x0800,\n 0x0004, 0x0800, 0x0c80, 0x0c80,\n 0x0d80, 0x0804, 0x0804, 0x0d80,\n 0x0d86, 0x0d86, 0x0940, 0x0004,\n 0x0004, 0x0004, 0x0c80, 0x0c80,\n 0x0d80, 0x0980, 0x0940, 0x0d80,\n 0x0004, 0x0d80, 0x0940, 0x0800,\n 0x0800, 0x0004, 0x0940, 0x0804,\n 0x0804, 0x0800, 0x0800, 0x0800,\n 0x0dc0, 0x0004, 0x0800, 0x0804,\n 0x0800, 0x0804, 0x0004, 0x0806,\n 0x0004, 0x0dc0, 0x0dc0, 0x0800,\n 0x0dc0, 0x0004, 0x0980, 0x0940,\n 0x0940, 0x0ac0, 0x0ac0, 0x0d80,\n 0x0d80, 0x0004, 0x0940, 0x0940,\n 0x0d80, 0x0980, 0x0980, 0x0980,\n 0x0980, 0x0800, 0x0800, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0004,\n 0x0804, 0x0004, 0x0806, 0x0804,\n 0x0806, 0x0804, 0x0004, 0x0804,\n 0x0d86, 0x0004, 0x0004, 0x0004,\n 0x0980, 0x0940, 0x0980, 0x0d80,\n 0x0004, 0x0d86, 0x0d86, 0x0d86,\n 0x0d86, 0x0004, 0x0004, 0x0980,\n 0x0940, 0x0940, 0x0800, 0x0800,\n 0x0980, 0x0ac0, 0x0d80, 0x0d80,\n 0x0800, 0x0804, 0x0004, 0x0004,\n 0x0d86, 0x0004, 0x0004, 0x0800,\n 0x0804, 0x0800, 0x0800, 0x0940,\n 0x0004, 0x0004, 0x0806, 0x0804,\n 0x0bc0, 0x0bc0, 0x0bc0, 0x0a00,\n 0x0a00, 0x0d80, 0x0d80, 0x0a00,\n 0x0d80, 0x0bc0, 0x0a00, 0x0a00,\n 0x00c4, 0x00c4, 0x00c4, 0x03c4,\n 0x0204, 0x00c4, 0x00c4, 0x00c4,\n 0x03c4, 0x0204, 0x03c4, 0x0204,\n 0x0940, 0x0d80, 0x0800, 0x0800,\n 0x0c80, 0x0c80, 0x0800, 0x0d80,\n 0x0d80, 0x0d80, 0x0d88, 0x0d88,\n 0x0d88, 0x0d80, 0x1340, 0x1340,\n 0x1340, 0x1340, 0x00c4, 0x0800,\n 0x0800, 0x0800, 0x1004, 0x1004,\n 0x0800, 0x0800, 0x1580, 0x1580,\n 0x0800, 0x0800, 0x0800, 0x1580,\n 0x1580, 0x1580, 0x0800, 0x0800,\n 0x1000, 0x0800, 0x1000, 0x1000,\n 0x1000, 0x0800, 0x1000, 0x0800,\n 0x0800, 0x1580, 0x1580, 0x1580,\n 0x0d80, 0x0004, 0x0d80, 0x0d80,\n 0x0940, 0x0d80, 0x0c80, 0x0c80,\n 0x0c80, 0x0800, 0x0800, 0x0bc0,\n 0x0bc0, 0x15ce, 0x0dce, 0x0dce,\n 0x0dce, 0x15ce, 0x1800, 0x1800,\n 0x1800, 0x0800, 0x0d8e, 0x0d8e,\n 0x0d8e, 0x1800, 0x1800, 0x0d80,\n 0x0d8e, 0x180e, 0x180e, 0x1800,\n 0x1800, 0x180e, 0x180e, 0x1800,\n 0x1800, 0x100e, 0x1800, 0x100e,\n 0x100e, 0x100e, 0x100e, 0x1800,\n 0x0d8e, 0x0dce, 0x0dce, 0x0805,\n 0x0805, 0x0805, 0x0805, 0x15c0,\n 0x15ce, 0x15ce, 0x0dce, 0x15c0,\n 0x15c0, 0x15ce, 0x15ce, 0x15ce,\n 0x15ce, 0x15c0, 0x0dce, 0x0dce,\n 0x0dce, 0x15ce, 0x15ce, 0x15ce,\n 0x0dce, 0x15ce, 0x15ce, 0x0d8e,\n 0x0d8e, 0x0dce, 0x0dce, 0x15ce,\n 0x158e, 0x158e, 0x15ce, 0x15ce,\n 0x15ce, 0x15c4, 0x15c4, 0x15c4,\n 0x15c4, 0x158e, 0x15ce, 0x158e,\n 0x15ce, 0x15ce, 0x15ce, 0x158e,\n 0x158e, 0x158e, 0x15ce, 0x158e,\n 0x158e, 0x0d80, 0x0d80, 0x0d8e,\n 0x0d8e, 0x0dce, 0x15ce, 0x0dce,\n 0x0dce, 0x15ce, 0x0dce, 0x0c00,\n 0x0b40, 0x0b40, 0x0b40, 0x080e,\n 0x080e, 0x080e, 0x080e, 0x0d80,\n 0x0d80, 0x080e, 0x080e, 0x0d8e,\n 0x0d8e, 0x080e, 0x080e, 0x15ce,\n 0x15ce, 0x15ce, 0x0dc0, 0x15ce,\n 0x0dce, 0x0dce, 0x0800, 0x0800,\n 0x0803, 0x0004, 0x0803, 0x0803,\n 0x1800, 0x1800, 0x0800, 0x0800,\n];\n#[rustfmt::skip]\nconst GRAPHEME_JOIN_RULES: [[u32; 16]; 2] = [\n [\n 0b00111100111111111111110011111111,\n 0b11111111111111111111111111001111,\n 0b11111111111111111111111111111111,\n 0b11111111111111111111111111111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111010011111111,\n 0b00000000000000000000000011111100,\n 0b00111100000011000011110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00110000111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00001100111111111111110011111111,\n ],\n [\n 0b00111100111111111111110011111111,\n 0b11111111111111111111111111001111,\n 0b11111111111111111111111111111111,\n 0b11111111111111111111111111111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00000000000000000000000011111100,\n 0b00111100000011000011110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00111100111100001111110011111111,\n 0b00111100111100111111110011111111,\n 0b00110000111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00111100111111111111110011111111,\n 0b00001100111111111111110011111111,\n ],\n];\n#[rustfmt::skip]\nconst LINE_BREAK_JOIN_RULES: [u32; 25] = [\n 0b00000000001000110011111110111010,\n 0b00000000111111111111111111111111,\n 0b00000000000000000000000000010000,\n 0b00000000111111111111111111111111,\n 0b00000000001000110000111100010010,\n 0b00000000001000110011111110110010,\n 0b00000000111111111111111111111111,\n 0b00000000001001110011111100110010,\n 0b00000000001110110011111110111010,\n 0b00000000001110110011111110111010,\n 0b00000000011111110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000001000110011111110111010,\n 0b00000000111111111111111111111111,\n 0b00000000111111111111111111111111,\n 0b00000000111111111111111111111111,\n 0b00000000011111110011111110111010,\n 0b00000000011111111011111110111010,\n 0b00000000011001111111111110111010,\n 0b00000000111001111111111110111010,\n 0b00000000001111110011111110111010,\n 0b00000000011111111011111110111010,\n 0b00000000001010110011111110111010,\n 0b00000000000000000000000000000000,\n];\n#[inline(always)]\npub fn ucd_grapheme_cluster_lookup(cp: char) -> usize {\n unsafe {\n let cp = cp as usize;\n if cp < 0x80 {\n return STAGE3[cp] as usize;\n }\n let s = *STAGE0.get_unchecked(cp >> 11) as usize;\n let s = *STAGE1.get_unchecked(s + ((cp >> 5) & 63)) as usize;\n let s = *STAGE2.get_unchecked(s + ((cp >> 2) & 7)) as usize;\n *STAGE3.get_unchecked(s + (cp & 3)) as usize\n }\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_joins(state: u32, lead: usize, trail: usize) -> u32 {\n unsafe {\n let l = lead & 31;\n let t = trail & 31;\n let s = GRAPHEME_JOIN_RULES.get_unchecked(state as usize);\n (s[l] >> (t * 2)) & 3\n }\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_joins_done(state: u32) -> bool {\n state == 3\n}\n#[inline(always)]\npub fn ucd_grapheme_cluster_character_width(val: usize, ambiguous_width: usize) -> usize {\n let mut w = val >> 11;\n if w > 2 {\n cold_path();\n w = ambiguous_width;\n }\n w\n}\n#[inline(always)]\npub fn ucd_line_break_joins(lead: usize, trail: usize) -> bool {\n unsafe {\n let l = (lead >> 6) & 31;\n let t = (trail >> 6) & 31;\n let s = *LINE_BREAK_JOIN_RULES.get_unchecked(l);\n ((s >> t) & 1) != 0\n }\n}\n#[inline(always)]\npub fn ucd_start_of_text_properties() -> usize {\n 0x603\n}\n#[inline(always)]\npub fn ucd_tab_properties() -> usize {\n 0x963\n}\n#[inline(always)]\npub fn ucd_linefeed_properties() -> usize {\n 0x802\n}\n#[cold]\n#[inline(always)]\nfn cold_path() {}\n// END: Generated by grapheme-table-gen\n"], ["/edit/src/lib.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#![feature(\n allocator_api,\n breakpoint,\n cold_path,\n linked_list_cursors,\n maybe_uninit_fill,\n maybe_uninit_slice,\n maybe_uninit_uninit_array_transpose\n)]\n#![cfg_attr(\n target_arch = \"loongarch64\",\n feature(stdarch_loongarch, stdarch_loongarch_feature_detection, loongarch_target_feature),\n allow(clippy::incompatible_msrv)\n)]\n#![allow(clippy::missing_transmute_annotations, clippy::new_without_default, stable_features)]\n\n#[macro_use]\npub mod arena;\n\npub mod apperr;\npub mod base64;\npub mod buffer;\npub mod cell;\npub mod clipboard;\npub mod document;\npub mod framebuffer;\npub mod fuzzy;\npub mod hash;\npub mod helpers;\npub mod icu;\npub mod input;\npub mod oklab;\npub mod path;\npub mod simd;\npub mod sys;\npub mod tui;\npub mod unicode;\npub mod vt;\n"], ["/edit/src/arena/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Arena allocators. Small and fast.\n\n#[cfg(debug_assertions)]\nmod debug;\nmod release;\nmod scratch;\nmod string;\n\n#[cfg(all(not(doc), debug_assertions))]\npub use self::debug::Arena;\n#[cfg(any(doc, not(debug_assertions)))]\npub use self::release::Arena;\npub use self::scratch::{ScratchArena, init, scratch_arena};\npub use self::string::ArenaString;\n"], ["/edit/src/unicode/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Everything related to Unicode lives here.\n\nmod measurement;\nmod tables;\nmod utf8;\n\npub use measurement::*;\npub use utf8::*;\n"], ["/edit/src/sys/mod.rs", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//! Platform abstractions.\n\n#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n\n#[cfg(not(windows))]\npub use std::fs::canonicalize;\n\n#[cfg(unix)]\npub use unix::*;\n#[cfg(windows)]\npub use windows::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:51:55", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Perform a case-sensitive comparison of two ASCII byte sequences, reverting to case-insensitive evaluation upon encountering mismatched characters while preserving original ordering when case-folded equivalents match."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n let mut tiebreaker = None;\n for (a_byte, b_byte) in iter {\n let a_lower = a_byte.to_ascii_lowercase();\n let b_lower = b_byte.to_ascii_lowercase();\n match a_lower.cmp(&b_lower) {\n Ordering::Equal => {\n if a_byte != b_byte && tiebreaker.is_none() {\n tiebreaker = Some(a_byte.cmp(b_byte));\n }\n }\n other => return other,\n }\n }\n\n if let Some(tie) = tiebreaker {\n tie\n } else {\n[TASK_END]\n```", "inference_time": "2025-08-21 01-53-15"}, "editdistance_info": {"edit_distance": 12.069, "calculate_time": "2025-08-21 01:53:15", "true_code_clean": "while let Some((&a, &b)) = iter.next() {\n if a != b {\n let mut order = a.cmp(&b);\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n if la == lb {\n for (a, b) in iter {\n let la = a.to_ascii_lowercase();\n let lb = b.to_ascii_lowercase();\n if la != lb {\n order = la.cmp(&lb);\n break;\n }\n }\n }\n return order;\n }\n }", "predict_code_clean": "let mut tiebreaker = None;\n for (a_byte, b_byte) in iter {\n let a_lower = a_byte.to_ascii_lowercase();\n let b_lower = b_byte.to_ascii_lowercase();\n match a_lower.cmp(&b_lower) {\n Ordering::Equal => {\n if a_byte != b_byte && tiebreaker.is_none() {\n tiebreaker = Some(a_byte.cmp(b_byte));\n }\n }\n other => return other,\n }\n }\n if let Some(tie) = tiebreaker {\n tie\n } else {"}}