Build a standalone Windows desktop with opt-in project removal

This commit is contained in:
gloamxun committed 2026-12-02 18:20:38 +08:00
1 parent 2c5b9b5f10
commit 2c99cade7d
24 files changed
+1404 -168

No files matched your search

@@ -1,8 +1,12 @@
use super::*;
use std::ffi::{CString, c_int};
use std::mem::MaybeUninit;
use std::ops::Range;
use std::ptr;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[path = "pdf_match/glibc.rs"]
mod backend;
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
#[path = "pdf_match/portable.rs"]
mod backend;
#[derive(PartialEq, Eq)]
pub(super) struct PdfMatch {
@@ -26,7 +30,7 @@ pub enum RegexOutcome {
}
pub fn match_pdf_regex(request: &RegexRequest) -> Result<RegexOutcome, String> {
match search(
match backend::search(
request.pattern.clone(),
request.input.clone(),
request.count,
@@ -80,7 +84,7 @@ impl Executor {
self.check_cancellation()?;
let text = match result.map_err(|message| self.error(message, origin.span))? {
RegexOutcome::Match(captures) => {
let input = as_c_string(request.input).into_bytes();
let input = before_nul(request.input);
if captures
.iter()
.flatten()
@@ -114,106 +118,10 @@ enum SearchError {
Runtime(String),
}
struct CLocale {
active: libc::locale_t,
previous: libc::locale_t,
}
impl CLocale {
fn enter() -> Result<Self, SearchError> {
// The reference engine treats matching as C-locale byte processing.
// Changing only this thread leaves concurrent jobs and the host alone.
let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) };
if active.is_null() {
return Err(SearchError::Runtime("cannot create pdfTeX C locale".into()));
}
let previous = unsafe { libc::uselocale(active) };
if previous.is_null() {
unsafe { libc::freelocale(active) };
return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into()));
}
Ok(Self { active, previous })
}
}
impl Drop for CLocale {
fn drop(&mut self) {
// previous is the still-live locale returned by uselocale above.
unsafe {
libc::uselocale(self.previous);
libc::freelocale(self.active);
}
}
}
struct CompiledRegex(libc::regex_t);
impl Drop for CompiledRegex {
fn drop(&mut self) {
// This wrapper is created only after successful regcomp.
unsafe { libc::regfree(&mut self.0) };
}
}
fn regex_error(code: c_int) -> String {
// An error code can be described without referring to a compiled regex.
let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) };
let mut message = vec![0u8; length];
unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) };
message.pop();
String::from_utf8_lossy(&message).into_owned()
}
fn as_c_string(mut bytes: Vec<u8>) -> CString {
fn before_nul(mut bytes: Vec<u8>) -> Vec<u8> {
// pdfTeX's makecstring passes the prefix through the first NUL.
if let Some(end) = bytes.iter().position(|&byte| byte == 0) {
bytes.truncate(end);
}
CString::new(bytes).expect("regex bytes were truncated at the first NUL")
}
fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let _locale = CLocale::enter()?;
let pattern = as_c_string(pattern);
let input = as_c_string(input);
let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 };
let mut regex = MaybeUninit::uninit();
// regcomp initializes the regex storage on success. The pattern is
// NUL-terminated and valid throughout the call.
let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) };
if status != 0 {
return Err(SearchError::Pattern(regex_error(status)));
}
let regex = CompiledRegex(unsafe { regex.assume_init() });
// Group starts cannot outnumber pattern bytes. Requests beyond that
// bound are observable only as missing captures.
let count = requested.min(pattern.as_bytes().len() + 1);
let mut ranges = vec![
libc::regmatch_t {
rm_so: -1,
rm_eo: -1
};
count
];
// Both C strings and the initialized regex live through the call.
// A zero count asks regexec to skip writing capture positions.
let status = unsafe { libc::regexec(&regex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) };
if status != 0 {
return Ok(None);
}
let input = input.into_bytes();
let captures = ranges
.into_iter()
.map(|range| {
let start = usize::try_from(range.rm_so).ok()?;
let end = usize::try_from(range.rm_eo).ok()?;
(start <= end && end <= input.len()).then_some(start..end)
})
.collect();
Ok(Some(PdfMatch { input, captures }))
bytes
}
@@ -0,0 +1,104 @@
use super::{PdfMatch, SearchError, before_nul};
use std::ffi::{CString, c_int};
use std::mem::MaybeUninit;
use std::ptr;
fn as_c_string(bytes: Vec<u8>) -> CString {
CString::new(before_nul(bytes)).expect("regex bytes were truncated at the first NUL")
}
struct CLocale {
active: libc::locale_t,
previous: libc::locale_t,
}
impl CLocale {
fn enter() -> Result<Self, SearchError> {
// The reference engine treats matching as C-locale byte processing.
// Changing only this thread leaves concurrent jobs and the host alone.
let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) };
if active.is_null() {
return Err(SearchError::Runtime("cannot create pdfTeX C locale".into()));
}
let previous = unsafe { libc::uselocale(active) };
if previous.is_null() {
unsafe { libc::freelocale(active) };
return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into()));
}
Ok(Self { active, previous })
}
}
impl Drop for CLocale {
fn drop(&mut self) {
// previous is the still-live locale returned by uselocale above.
unsafe {
libc::uselocale(self.previous);
libc::freelocale(self.active);
}
}
}
struct CompiledRegex(libc::regex_t);
impl Drop for CompiledRegex {
fn drop(&mut self) {
// This wrapper is created only after successful regcomp.
unsafe { libc::regfree(&mut self.0) };
}
}
fn regex_error(code: c_int) -> String {
// An error code can be described without referring to a compiled regex.
let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) };
let mut message = vec![0u8; length];
unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) };
message.pop();
String::from_utf8_lossy(&message).into_owned()
}
pub(super) fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let _locale = CLocale::enter()?;
let pattern = as_c_string(pattern);
let input = as_c_string(input);
let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 };
let mut regex = MaybeUninit::uninit();
// regcomp initializes the regex storage on success. The pattern is
// NUL-terminated and valid throughout the call.
let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) };
if status != 0 {
return Err(SearchError::Pattern(regex_error(status)));
}
let regex = CompiledRegex(unsafe { regex.assume_init() });
// Group starts cannot outnumber pattern bytes. Requests beyond that
// bound are observable only as missing captures.
let count = requested.min(pattern.as_bytes().len() + 1);
let mut ranges = vec![
libc::regmatch_t {
rm_so: -1,
rm_eo: -1
};
count
];
// Both C strings and the initialized regex live through the call.
// A zero count asks regexec to skip writing capture positions.
let status = unsafe { libc::regexec(&regex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) };
if status != 0 {
return Ok(None);
}
let input = input.into_bytes();
let captures = ranges
.into_iter()
.map(|range| {
let start = usize::try_from(range.rm_so).ok()?;
let end = usize::try_from(range.rm_eo).ok()?;
(start <= end && end <= input.len()).then_some(start..end)
})
.collect();
Ok(Some(PdfMatch { input, captures }))
}
@@ -0,0 +1,112 @@
use super::{PdfMatch, SearchError, before_nul};
use revera::RegexBuilder;
pub(super) fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let pattern = before_nul(pattern);
let input = before_nul(input);
let count = requested.min(pattern.len() + 1);
if pattern.is_empty() {
let captures = (count > 0).then_some(Some(0..0)).into_iter().collect();
return Ok(Some(PdfMatch { input, captures }));
}
let pattern = encode_pattern(&pattern);
let subject: String = input.iter().copied().map(c_locale_byte).collect();
let regex = RegexBuilder::new(&pattern)
.case_insensitive(insensitive)
.build()
.map_err(|error| SearchError::Pattern(error.to_string()))?;
let Some(matches) = regex
.captures(&subject)
.map_err(|error| SearchError::Runtime(error.to_string()))?
else {
return Ok(None);
};
let starts: Vec<_> = subject
.char_indices()
.map(|(offset, _)| offset)
.chain(std::iter::once(subject.len()))
.collect();
let mut captures: Vec<_> = matches
.iter()
.take(count)
.map(|matched| {
let matched = matched?;
let start = starts.binary_search(&matched.start()).ok()?;
let end = starts.binary_search(&matched.end()).ok()?;
Some(start..end)
})
.collect();
captures.resize(count, None);
Ok(Some(PdfMatch { input, captures }))
}
fn c_locale_byte(byte: u8) -> char {
// Private-use code points preserve byte order above ASCII without
// giving high bytes Unicode case folds or character classifications.
if byte.is_ascii() {
char::from(byte)
} else {
char::from_u32(0xE000 + u32::from(byte)).unwrap()
}
}
fn encode_pattern(mut bytes: &[u8]) -> String {
let mut pattern = String::new();
while let Some((&next, remaining)) = bytes.split_first() {
bytes = remaining;
match next {
b'\\' if !bytes.is_empty() => {
let escaped = bytes[0];
bytes = &bytes[1..];
match escaped {
b'w' => pattern.push_str("[[:alnum:]_]"),
b'W' => pattern.push_str("[^[:alnum:]_]"),
b's' => pattern.push_str("[[:space:]]"),
b'S' => pattern.push_str("[^[:space:]]"),
_ => {
pattern.push('\\');
pattern.push(c_locale_byte(escaped));
}
}
}
b'[' => {
let end = bracket_end(bytes);
pattern.push('[');
pattern.extend(bytes[..end].iter().copied().map(c_locale_byte));
bytes = &bytes[end..];
}
_ => pattern.push(c_locale_byte(next)),
}
}
pattern
}
fn bracket_end(bytes: &[u8]) -> usize {
let mut position = usize::from(bytes.starts_with(b"^"));
if bytes.get(position) == Some(&b']') {
position += 1;
}
while let Some(&next) = bytes.get(position) {
position += 1;
if next == b']' {
break;
}
if next == b'['
&& let Some(delimiter @ (b'.' | b'=' | b':')) = bytes.get(position)
{
let closing = [*delimiter, b']'];
if let Some(end) = bytes[position + 1..]
.windows(2)
.position(|pair| pair == closing)
{
position += 3 + end;
}
}
}
position
}
@@ -466,7 +466,12 @@ impl ProjectSnapshot {
let mut links = 0;
while let Some(part) = queue.pop_front() {
match Path::new(&part).components().next().unwrap() {
Component::Prefix(_) => current.push(&part),
Component::Prefix(_) => {
// A Windows volume prefix only names a directory once
// its root component has been appended.
current.push(&part);
continue;
}
Component::RootDir => current.push(&part),
Component::CurDir => {}
Component::ParentDir => {