repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
amPerl/egui-phosphor
https://github.com/amPerl/egui-phosphor/blob/c33b60c40f703ffa3d40d252f1bc911cf531581d/examples/multiple_variants.rs
examples/multiple_variants.rs
use std::sync::Arc; use egui::ViewportBuilder; use egui_phosphor::{bold, fill, light, regular, thin}; fn main() { eframe::run_native( "egui-phosphor demo", eframe::NativeOptions { viewport: ViewportBuilder::default().with_inner_size((320.0, 755.0)), ..Default::default() }, Box::new(|cc| Ok(Box::new(Demo::new(cc)))), ) .unwrap(); } struct Demo {} impl Demo { fn new(cc: &eframe::CreationContext) -> Self { let mut fonts = egui::FontDefinitions::default(); fonts.font_data.insert( "phosphor-thin".into(), Arc::new(egui_phosphor::Variant::Thin.font_data()), ); fonts.families.insert( egui::FontFamily::Name("phosphor-thin".into()), vec!["Ubuntu-Light".into(), "phosphor-thin".into()], ); fonts.font_data.insert( "phosphor-light".into(), Arc::new(egui_phosphor::Variant::Light.font_data()), ); fonts.families.insert( egui::FontFamily::Name("phosphor-light".into()), vec!["Ubuntu-Light".into(), "phosphor-light".into()], ); fonts.font_data.insert( "phosphor".into(), Arc::new(egui_phosphor::Variant::Regular.font_data()), ); fonts.families.insert( egui::FontFamily::Name("phosphor".into()), vec!["Ubuntu-Light".into(), "phosphor".into()], ); fonts.font_data.insert( "phosphor-bold".into(), Arc::new(egui_phosphor::Variant::Bold.font_data()), ); fonts.families.insert( egui::FontFamily::Name("phosphor-bold".into()), vec!["Ubuntu-Light".into(), "phosphor-bold".into()], ); fonts.font_data.insert( "phosphor-fill".into(), Arc::new(egui_phosphor::Variant::Fill.font_data()), ); fonts.families.insert( egui::FontFamily::Name("phosphor-fill".into()), vec!["Ubuntu-Light".into(), "phosphor-fill".into()], ); cc.egui_ctx.set_fonts(fonts); Self {} } } impl eframe::App for Demo { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { egui::CentralPanel::default().show(ctx, |ui| { for (family, icon) in [ ("phosphor-thin", thin::FILE_CODE), ("phosphor-light", light::FILE_CODE), ("phosphor", regular::FILE_CODE), ("phosphor-bold", bold::FILE_CODE), ("phosphor-fill", fill::FILE_CODE), ] { ui.heading(family); egui::Frame::canvas(ui.style()).show(ui, |ui| { for size in [16.0, 32.0, 48.0] { let demo_text = format!("FILE_CODE {icon}"); ui.label( egui::RichText::new(&demo_text) .family(egui::FontFamily::Name(family.into())) .size(size), ); } }); } }); } }
rust
Apache-2.0
c33b60c40f703ffa3d40d252f1bc911cf531581d
2026-01-04T20:22:14.235772Z
false
amPerl/egui-phosphor
https://github.com/amPerl/egui-phosphor/blob/c33b60c40f703ffa3d40d252f1bc911cf531581d/examples/debug_alignment.rs
examples/debug_alignment.rs
fn main() { eframe::run_native( "egui-phosphor demo", Default::default(), Box::new(|cc| Ok(Box::new(Demo::new(cc)))), ) .unwrap(); } struct Demo {} impl Demo { fn new(cc: &eframe::CreationContext) -> Self { let mut fonts = egui::FontDefinitions::default(); egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); cc.egui_ctx.set_fonts(fonts); Self {} } } impl eframe::App for Demo { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { egui::CentralPanel::default().show(ctx, |ui| { for size in [16.0, 24.0, 32.0, 48.0, 64.0, 92.0] { let resp = ui.label( egui::RichText::new(format!("FILE_CODE {}", egui_phosphor::regular::FILE_CODE)) .size(size), ); ui.painter() .debug_rect(resp.rect, egui::Color32::RED, format!("{size}")); } for size in [16.0, 92.0] { let _ = ui.button( egui::RichText::new(format!("FILE_CODE {}", egui_phosphor::regular::FILE_CODE)) .size(size), ); } }); } }
rust
Apache-2.0
c33b60c40f703ffa3d40d252f1bc911cf531581d
2026-01-04T20:22:14.235772Z
false
amPerl/egui-phosphor
https://github.com/amPerl/egui-phosphor/blob/c33b60c40f703ffa3d40d252f1bc911cf531581d/examples/list_all.rs
examples/list_all.rs
fn main() { eframe::run_native( "egui-phosphor demo", Default::default(), Box::new(|cc| Ok(Box::new(Demo::new(cc)))), ) .unwrap(); } struct Demo {} impl Demo { fn new(cc: &eframe::CreationContext) -> Self { let mut fonts = egui::FontDefinitions::default(); egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); cc.egui_ctx.set_fonts(fonts); Self {} } } impl eframe::App for Demo { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { egui::CentralPanel::default().show(ctx, |ui| { egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { // Make sure normal text looks good ui.heading("The quick brown fox jumps over the lazy dog."); let mut icons = egui_phosphor::regular::ICONS.to_vec(); icons.sort_by_key(|(_, icon)| { let code = icon.chars().next().unwrap() as usize; format!("{code:#04X}") }); for (icon_name, icon) in icons { let code = icon.chars().next().unwrap() as usize; ui.label( egui::RichText::new(format!("{code:#04X} {icon_name} {icon}",)) .size(16.0), ); } }); }); } }
rust
Apache-2.0
c33b60c40f703ffa3d40d252f1bc911cf531581d
2026-01-04T20:22:14.235772Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/build.rs
build.rs
// For embedding application icons, in Windows. use std::{env, io}; use winresource::WindowsResource; fn main() -> io::Result<()> { if env::var_os("CARGO_CFG_WINDOWS").is_some() { WindowsResource::new() // This path can be absolute, or relative to your crate root. .set_icon("src/resources/icon.ico") .compile()?; } Ok(()) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/external_websites.rs
src/external_websites.rs
//! For opening the browser to NCBI BLAST, PDB etc. //! //! PDB Search API: https://search.rcsb.org/#search-api //! PDB Data API: https://data.rcsb.org/#data-api use bio_apis::ncbi; use crate::{Selection, state::State}; /// BLAST the selected Feature, primer, or selection. Prioritize the selection. /// This function handles extracting the sequence to BLAST from possible selections. pub fn blast(state: &State) { let data = &state.generic[state.active]; let val = match state.ui.text_selection { Some(sel) => { // Don't format sel directly, as we insert the bp count downstream for use with feature selections. Some(( sel.index_seq(&data.seq), format!("{}, {}..{}", data.metadata.plasmid_name, sel.start, sel.end), )) } None => match state.ui.selected_item { Selection::Feature(feat_i) => { if feat_i >= data.features.len() { eprintln!("Invalid selected feature"); None } else { let feature = &data.features[feat_i]; Some((feature.range.index_seq(&data.seq), feature.label.clone())) } } Selection::Primer(prim_i) => { if prim_i >= data.primers.len() { eprintln!("Invalid selected primer"); None } else { let primer = &data.primers[prim_i]; Some((Some(&primer.sequence[..]), primer.name.clone())) } } Selection::None => None, }, }; // todo: Handle reverse. if let Some((seq, name)) = val { if let Some(s) = seq { ncbi::open_blast(s, &name); } } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/solution_helper.rs
src/solution_helper.rs
//! This module contains code for assisting with mixing common solutions
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/ligation.rs
src/ligation.rs
use na_seq::restriction_enzyme::RestrictionEnzyme;
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/misc_types.rs
src/misc_types.rs
//! This module contains fundamental data structures, eg related to features, metadata, etc. use bincode::{Decode, Encode}; use na_seq::Nucleotide; use crate::{ Color, primer::PrimerDirection, util::{RangeIncl, match_subseq}, }; pub const MIN_SEARCH_LEN: usize = 3; #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum FeatureType { Generic, Gene, Ori, RibosomeBindSite, Promoter, AntibioticResistance, /// Note: This one behaves a bit different from the others; we use it here so we can share the feature /// overlay code. Primer, /// Ie, a gene. CodingRegion, LongTerminalRepeat, /// We don't draw these on the map or sequence views; found in GenBank formats (at least), these /// are the range of the entire sequence. Source, Exon, Transcript, /// Like Primer, this is not a real feature; we use it to draw the selection highlighted area. Selection, /// Ie operators. ProteinBind, Terminator, } impl Default for FeatureType { fn default() -> Self { Self::Generic } } impl FeatureType { /// For displaying in the UI pub fn to_string(self) -> String { match self { Self::Generic => "Generic", Self::Gene => "Gene", Self::Ori => "Origin of replication", Self::RibosomeBindSite => "Ribosome bind site", Self::Promoter => "Promoter", Self::AntibioticResistance => "Antibiotic resistance", Self::Primer => "Primer", Self::CodingRegion => "Coding region", Self::LongTerminalRepeat => "Long term repeat", Self::Source => "Source", Self::Exon => "Exon", Self::Transcript => "Transcript", Self::Selection => "", Self::ProteinBind => "Operator", Self::Terminator => "Terminator", } .to_owned() } pub fn color(&self) -> Color { match self { Self::Generic => (255, 0, 255), Self::Gene => (255, 128, 128), Self::Ori => (40, 200, 128), Self::RibosomeBindSite => (255, 204, 252), Self::Promoter => (240, 190, 70), Self::AntibioticResistance => (0, 200, 110), Self::Primer => (0, 0, 0), // N/A for now at least. Self::CodingRegion => (100, 200, 255), // N/A for now at least. Self::LongTerminalRepeat => (150, 200, 255), // N/A for now at least. Self::Source => (120, 70, 120), Self::Exon => (255, 255, 180), Self::Transcript => (180, 255, 180), Self::Selection => (255, 255, 0), Self::ProteinBind => (128, 110, 150), Self::Terminator => (255, 110, 150), } } /// Parse from a string; we use this for both SnapGene and GenBank. pub fn from_external_str(v: &str) -> Self { // todo: Update as required with more let v = &v.to_lowercase(); match v.as_ref() { "cds" => Self::CodingRegion, "gene" => Self::Gene, "rbs" => Self::RibosomeBindSite, "rep_origin" => Self::Ori, "promoter" => Self::Promoter, "primer_bind" => Self::Primer, // todo: This is a bit awk; genbank. "ltr" => Self::LongTerminalRepeat, "misc_feature" => Self::Generic, "source" => Self::Source, "exon" => Self::Exon, "transcript" => Self::Transcript, "protein_bind" => Self::ProteinBind, "terminator" => Self::Terminator, _ => Self::Generic, } } /// Create a string for use with SnapGene and GenBank formats. pub fn to_external_str(self) -> String { // todo: Update as required with more match self { Self::Generic => "misc_feature", Self::Gene => "gene", Self::Ori => "rep_origin", Self::RibosomeBindSite => "rbs", Self::Promoter => "promoter", Self::AntibioticResistance => "antibiotic resistance", // todo Self::Primer => "primer_bind", Self::CodingRegion => "cds", Self::LongTerminalRepeat => "ltr", Self::Source => "source", Self::Exon => "exon", Self::Transcript => "transcript", Self::Selection => "", Self::ProteinBind => "protein_bind", Self::Terminator => "terminator", } .to_string() } } #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum FeatureDirection { None, Forward, Reverse, } impl From<PrimerDirection> for FeatureDirection { fn from(value: PrimerDirection) -> Self { match value { PrimerDirection::Forward => Self::Forward, PrimerDirection::Reverse => Self::Reverse, } } } impl Default for FeatureDirection { fn default() -> Self { Self::None } } impl FeatureDirection { pub fn to_string(self) -> String { match self { Self::None => "None", Self::Forward => "Forward", Self::Reverse => "Reverse", } .to_owned() } } #[derive(Clone, Encode, Decode)] pub struct Feature { // pub range: (usize, usize), /// 1-based indexing, inclusive. (Note: Could also use the builtin RangeInclusive.) pub range: RangeIncl, pub feature_type: FeatureType, pub direction: FeatureDirection, pub label: String, /// By default, we display features using featuretype-specific color. Allow the user /// to override this. pub color_override: Option<Color>, pub notes: Vec<(String, String)>, } impl Default for Feature { fn default() -> Self { Self { range: RangeIncl::new(1, 1), feature_type: Default::default(), direction: Default::default(), label: Default::default(), color_override: Default::default(), notes: Default::default(), } } } impl Feature { pub fn label(&self) -> String { if self.label.is_empty() { self.feature_type.to_string() } else { self.label.clone() } } /// Get the color to draw; type color, unless overridden. pub fn color(&self) -> Color { match self.color_override { Some(c) => c, None => self.feature_type.color(), } } /// Get the feature len, in usize. pub fn len(&self, seq_len: usize) -> usize { if self.range.end > self.range.start { self.range.end - self.range.start + 1 } else { // ie a wrap through the origin self.range.end + seq_len - self.range.start + 1 } } /// Formats the indexes, and size of this feature. pub fn location_descrip(&self, seq_len: usize) -> String { format!( "{}..{} {} bp", self.range.start, self.range.end, self.len(seq_len) ) } } /// Contains sequence-level metadata. #[derive(Clone, Default, Encode, Decode)] pub struct Metadata { pub plasmid_name: String, pub comments: Vec<String>, pub references: Vec<Reference>, pub locus: String, // pub date: Option<NaiveDate>, /// We use this to prevent manual encode/decode for the whoel struct. pub date: Option<(i32, u8, u8)>, // Y M D pub definition: Option<String>, pub molecule_type: Option<String>, pub division: String, pub accession: Option<String>, pub version: Option<String>, // pub keywords: Vec<String>, pub keywords: Option<String>, // todo vec? pub source: Option<String>, pub organism: Option<String>, } /// Based on GenBank's reference format #[derive(Default, Clone, Encode, Decode)] pub struct Reference { pub description: String, pub authors: Option<String>, pub consortium: Option<String>, pub title: String, pub journal: Option<String>, pub pubmed: Option<String>, pub remark: Option<String>, } pub struct SearchMatch { /// 0-based indexing. pub range: RangeIncl, // todo: More A/R } // todo: Should this go to the `seq` library? /// Find exact matches in the target sequence of our search nucleotides. /// todo: Optionally support partial matches. /// todo: pub fn find_search_matches(seq: &[Nucleotide], search_seq: &[Nucleotide]) -> Vec<SearchMatch> { let (mut fwd, mut rev) = match_subseq(search_seq, seq); fwd.append(&mut rev); fwd.into_iter().map(|range| SearchMatch { range }).collect() }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/feature_db_load.rs
src/feature_db_load.rs
//! A library of known sequences we can use to automatically add features to a sequence. //! This will eventually load data from an online source. Currently, it includes some common items, //! and is stored in memory. //! //! Some common genes: https://en.vectorbuilder.com/search/gene.html use na_seq::{ Nucleotide, Seq, amino_acids::{AminoAcid, CodingResult}, seq_complement, seq_from_str, }; use crate::{ misc_types::{ Feature, FeatureDirection, FeatureType::{ self, AntibioticResistance, CodingRegion, Generic, Ori, Promoter, ProteinBind, RibosomeBindSite, Terminator, }, }, reading_frame::ReadingFrame, util::{RangeIncl, match_subseq}, }; struct FeatureMapItem { name: String, feature_type: FeatureType, seq: Seq, } impl FeatureMapItem { pub fn new(name: &str, feature_type: FeatureType, seq: Seq) -> Self { Self { name: name.to_string(), feature_type, seq, } } } /// Find 6x+ HIS tags in a sequence /// todo: Currently very similar to find_reading_frame_matches pub fn find_his_tags(seq: &[Nucleotide]) -> Vec<Feature> { let mut result = Vec::new(); let seq_len_full = seq.len(); if seq_len_full < 3 { return result; } for orf in [ ReadingFrame::Fwd0, ReadingFrame::Fwd1, ReadingFrame::Fwd2, ReadingFrame::Rev0, ReadingFrame::Rev1, ReadingFrame::Rev2, ] { let offset = orf.offset(); let seq_ = orf.arrange_seq(seq); let len = seq_.len(); let mut tag_open = None; // Inner: Start index. for i_ in 0..len / 3 { let i = i_ * 3; // The actual sequence index. let nts = &seq_[i..i + 3]; let mut matched = false; if let CodingResult::AminoAcid(aa) = CodingResult::from_codons(nts.try_into().unwrap()) { if aa == AminoAcid::His { matched = true; } } if tag_open.is_none() && matched { tag_open = Some(i); } else if tag_open.is_some() && !matched { let his_len = (i - tag_open.unwrap()) / 3; if his_len >= 6 { let range = match orf { ReadingFrame::Fwd0 | ReadingFrame::Fwd1 | ReadingFrame::Fwd2 => { // RangeIncl::new(tag_open.unwrap() + 1 + offset, i + 2 + offset) RangeIncl::new(tag_open.unwrap() + 1 + offset, i + offset) } _ => RangeIncl::new( seq_len_full - (i + 2 + offset), seq_len_full - (tag_open.unwrap() + offset) - 1, ), }; // todo: Likely you want the appropriate direction, determined by the reading frame. result.push(Feature { range, feature_type: CodingRegion, label: format!("{his_len}×His"), ..Default::default() }); } tag_open = None; } } } result } // todo: Map Aa sequences in addition to DNA seqs; more general. /// Find common promoters and Oris. /// The order of the written sequences matters: It determines direction. fn find_misc(seq: &[Nucleotide]) -> Vec<Feature> { let items = vec![ FeatureMapItem::new( "AmpR promoter", Promoter, seq_from_str( "cgcggaacccctatttgtttatttttctaaatacattcaaatatgtatccgctcatgagacaataaccctgataaatgcttcaataacattgaaaaaggaagagt", ), ), // Perhaps slightly different from the above AmpR promoter? FeatureMapItem::new( "AmpR promoter", Promoter, seq_from_str( "cgcggaacccctatttgtttatttttctaaatacattcaaatatgtatccgctcatgagacaataaccctgataaatgcttcaataatattgaaaaaggaagagt", ), ), FeatureMapItem::new("T3 promoter", Promoter, seq_from_str("aattaaccctcactaaagg")), FeatureMapItem::new( "lac promoter", Promoter, seq_from_str("tttacactttatgcttccggctcgtatgttg"), ), FeatureMapItem::new( "AmpR promoter", Promoter, seq_from_str( "actcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcg", ), ), FeatureMapItem::new( "ARA promoter", Promoter, seq_from_str("ctgacgctttttatcgcaactctctactg"), ), FeatureMapItem::new( "lac promoter", Promoter, seq_from_str("CAACATACGAGCCGGAAGCATAAAGTGTAAA"), ), FeatureMapItem::new( "cat promoter", Promoter, seq_from_str( "TGATCGGCACGTAAGAGGKTCCAACTTTCACCATAATGAAATAAGATCACTACCGGGCGTATTTTTTGAGTTRTCGAGATTTTCAGGAGCTAAGGAAGCTAAA", ), ), FeatureMapItem::new( "lacI promoter", Promoter, seq_from_str( "GACACCATCGAATGGCGCAAAACCTTTCGCGGTATGGCATGATAGCGCCCGGAAGAGAGTCAATTCAGGGTGGTGAAT", ), ), FeatureMapItem::new( "lacIq promoter", Promoter, seq_from_str( "gacaccatcgaatggtgcaaaacctttcgcggtatggcatgatagcgcccggaagagagtcaattcagggtggtgaat", ), ), FeatureMapItem::new( "tac promoter", Promoter, seq_from_str("TTGACAATTAATCATCGGCTCGTATAATG"), ), FeatureMapItem::new( "trc promoter", Promoter, seq_from_str("TTGACAATTAATCATCCGGCYCGTATAATG"), ), FeatureMapItem::new( "CMV promoter", Promoter, seq_from_str( "gtgatgcggttttggcagtacatcaatgggcgtggatagcggtttgactcacggggatttccaagtctccaccccattgacgtcaatgggagtttgttttggcaccaaaatcaacgggactttccaaaatgtcgtaacaactccgccccattgacgcaaatgggcggtaggcgtgtacggtgggaggtctatataagcagagct", ), ), FeatureMapItem::new( "T37 promoter", Promoter, seq_from_str("aattaaccctcactaaagg"), ), FeatureMapItem::new("T7 promoter", Promoter, seq_from_str("taatacgactcactatagg")), FeatureMapItem::new( "Cat promoter", Promoter, seq_complement(&seq_from_str( "tttagcttccttagctcctgaaaatctcgataactcaaaaaatacgcccggtagtgatcttatttcattatggtgaaagttggaacctcttacgtgccgatca", )), ), FeatureMapItem::new( "sacB promoter", Promoter, seq_from_str( "cacatatacctgccgttcactattatttagtgaaatgagatattatgatattttctgaattgtgattaaaaaggcaactttatgcccatgcaacagaaactataaaaaatacagagaatgaaaagaaacagatagattttttagttctttaggcccgtagtctgcaaatccttttatgattttctatcaaacaaaagaggaaaatagaccagttgcaatccaaacgagagtctaatagaatgaggtcgaaaagtaaatcgcgcgggtttgttactgataaagcaggcaagacctaaaatgtgtaaagggcaaagtgtatactttggcgtcaccccttacatattttaggtctttttttattgtgcgtaactaacttgccatcttcaaacaggagggctggaagaagcagaccgctaacacagtacataaaaaaggagacatgaacg", ), ), FeatureMapItem::new( "lacZα", CodingRegion, seq_complement(&seq_from_str( "CTATGCGGCATCAGAGCAGATTGTACTGAGAGTGCACCATATGCGGTGTGAAATACCGCACAGATGCGTAAGGAGAAAATACCGCATCAGGCGCCATTCGCCATTCAGGCTGCGCAACTGTTGGGAAGGGCGATCGGTGCGGGCCTCTTCGCTATTACGCCAGCTGGCGAAAGGGGGATGTGCTGCAAGGCGATTAAGTTGGGTAACGCCAGGGTTTTCCCAGTCACGACGTTGTAAAACGACGGCCAGTGAATTCGAGCTCGGTACCCGGGGATCCTCTAGAGTCGACCTGCAGGCATGCAAGCTTGGCGTAATCATGGTCAT", )), ), FeatureMapItem::new( "lacZα", CodingRegion, seq_from_str( "ctatgcggcatcagagcagattgtactgagagtgcaccatatgcggtgtgaaataccgcacagatgcgtaaggagaaaataccgcatcaggcgccattcgccattcaggctgcgcaactgttgggaagggcgatcggtgcgggcctcttcgctattacgccagctggcgaaagggggatgtgctgcaaggcgattaagttgggtaacgccagggttttcccagtcacgacgttgtaaaacgacggccagtgaattcgagctcggtacccggggatcctctagagtcgacctgcaggcatgcaagcttggcgtaatcatggtcat", ), ), FeatureMapItem::new( "lacZα", CodingRegion, seq_complement(&seq_from_str( "ctaatcaagttttttggggtcgaggtgccgtaaagcactaaatcggaaccctaaagggagcccccgatttagagcttgacggggaaagccggcgaacgtggcgagaaaggaagggaagaaagcgaaaggagcgggcgctagggcgctggcaagtgtagcggtcacgctgcgcgtaaccaccacacccgccgcgcttaatgcgccgctacagggcgcgtcccattcgccattcaggctgcgcaactgttgggaagggcgatcggtgcgggcctcttcgctattacgccagctggcgaaagggggatgtgctgcaaggcgattaagttgggtaacgccagggttttcccagtcacgacgttgtaaaacgacggccagtgagcgcgcgtaatacgactcactatagggcgaattgggtaccgggccccccctcgaggtcgacggtatcgataagcttgatatcgaattcctgcagcccgggggatccactagttctagagcggccgccaccgcggtggagctccagcttttgttccctttagtgagggttaattgcgcgcttggcgtaatcatggtcat", )), ), FeatureMapItem::new( "lacZα", CodingRegion, seq_from_str( "atgaccatgattacggattcactggccgtcgttttacaacgtcgtgactgggaaaaccctggcgttacccaacttaatcgccttgcagcacatccccctttcgccagctggcgtaatagcgaagaggcccgcaccgatcgcccttcccaacagttgcgcagcctgaatggcgaatggcgctttgcctggtttccggcaccagaagcggtgccggaaagctggctggagtgcgatcttcctgaggccgatactgtcgtcgtcccctcaaactggcagatgcacggttacgatgcgcccatctacaccaacgtaacctatcccattacggtcaatccgccgtttgttcccacggagaatccgacgggttgttactcgctcacatttaatgttgatgaaagctggctacaggaaggccagacgcgaattatttttgatggcgttggaatt", ), ), FeatureMapItem::new( "lacI", CodingRegion, seq_complement(&seq_from_str( "tcactgcccgctttccagtcgggaaacctgtcgtgccagctgcattaatgaatcggccaacgcgcggggagaggcggtttgcgtattgggcgccagggtggtttttcttttcaccagtgagacgggcaacagctgattgcccttcaccgcctggccctgagagagttgcagcaagcggtccacgctggtttgccccagcaggcgaaaatcctgtttgatggtggttaacggcgggatataacatgagctgtcttcggtatcgtcgtatcccactaccgagatgtccgcaccaacgcgcagcccggactcggtaatggcgcgcattgcgcccagcgccatctgatcgttggcaaccagcatcgcagtgggaacgatgccctcattcagcatttgcatggtttgttgaaaaccggacatggcactccagtcgccttcccgttccgctatcggctgaatttgattgcgagtgagatatttatgccagccagccagacgcagacgcgccgagacagaacttaatgggcccgctaacagcgcgatttgctggtgacccaatgcgaccagatgctccacgcccagtcgcgtaccgtcttcatgggagaaaataatactgttgatgggtgtctggtcagagacatcaagaaataacgccggaacattagtgcaggcagcttccacagcaatggcatcctggtcatccagcggatagttaatgatcagcccactgacgcgttgcgcgagaagattgtgcaccgccgctttacaggcttcgacgccgcttcgttctaccatcgacaccaccacgctggcacccagttgatcggcgcgagatttaatcgccgcgacaatttgcgacggcgcgtgcagggccagactggaggtggcaacgccaatcagcaacgactgtttgcccgccagttgttgtgccacgcggttgggaatgtaattcagctccgccatcgccgcttccactttttcccgcgttttcgcagaaacgtggctggcctggttcaccacgcgggaaacggtctgataagagacaccggcatactctgcgacatcgtataacgttactggtttcac", )), ), FeatureMapItem::new( "lacI", CodingRegion, seq_from_str( "gtgaaaccagtaacgttatacgatgtcgcagagtatgccggtgtctcttatcagaccgtttcccgcgtggtgaaccaggccagccacgtttctgcgaaaacgcgggaaaaagtggaagcggcgatggcggagctgaattacattcccaaccgcgtggcacaacaactggcgggcaaacagtcgttgctgattggcgttgccacctccagtctggccctgcacgcgccgtcgcaaattgtcgcggcgattaaatctcgcgccgatcaactgggtgccagcgtggtggtgtcgatggtagaacgaagcggcgtcgaagcctgtaaagcggcggtgcacaatcttctcgcgcaacgcgtcagtgggctgatcattaactatccgctggatgaccaggatgccattgctgtggaagctgcctgcactaatgttccggcgttatttcttgatgtctctgaccagacacccatcaacagtattattttctcccatgaagacggtacgcgactgggcgtggagcatctggtcgcattgggtcaccagcaaatcgcgctgttagcgggcccattaagttctgtctcggcgcgtctgcgtctggctggctggcataaatatctcactcgcaatcaaattcagccgatagcggaacgggaaggcgactggagtgccatgtccggttttcaacaaaccatgcaaatgctgaatgagggcatcgttcccactgcgatgctggttgccaacgatcagatggcgctgggcgcaatgcgcgccattaccgagtccgggctgcgcgttggtgcggatatctcggtagtgggatacgacgataccgaagacagctcatgttatatcccgccgttaaccaccatcaaacaggattttcgcctgctggggcaaaccagcgtggaccgcttgctgcaactctctcagggccaggcggtgaagggcaatcagctgttgcccgtctcactggtgaaaagaaaaaccaccctggcgcccaatacgcaaaccgcctctccccgcgcgttggccgattcattaatgcagctggcacgacaggtttcccgactggaaagcgggcagtga", ), ), FeatureMapItem::new( "lacI", CodingRegion, seq_from_str( "gtgaaaccagtaacgttatacgatgtcgcagagtatgccggtgtctcttatcagaccgtttcccgcgtggtgaaccaggccagccacgtttctgcgaaaacgcgggaaaaagtggaagcggcgatggcggagctgaattacattcccaaccgcgtggcacaacaactggcgggcaaacagtcgttgctgattggcgttgccacctccagtctggccctgcacgcgccgtcgcaaattgtcgcggcgattaaatctcgcgccgatcaactgggtgccagcgtggtggtgtcgatggtagaacgaagcggcgtcgaagcctgtaaagcggcggtgcacaatcttctcgcgcaacgcgtcagtgggctgatcattaactatccgctggatgaccaggatgccattgctgtggaagctgcctgcactaatgttccggcgttatttcttgatgtctctgaccagacacccatcaacagtattattttctcccatgaagacggtacgcgactgggcgtggagcatctggtcgcattgggtcaccagcaaatcgcgctgttagcgggcccattaagttctgtctcggcgcgtctgcgtctggctggctggcataaatatctcactcgcaatcaaattcagccgatagcggaacgggaaggcgactggagtgccatgtccggttttcaacaaaccatgcaaatgctgaatgagggcatcgttcccactgcgatgctggttgccaacgatcagatggcgctgggcgcaatgcgcgccattaccgagtccgggctgcgcgttggtgcggatatctcggtagtgggatacgacgataccgaagacagctcatgttatatcccgccgtcaaccaccatcaaacaggattttcgcctgctggggcaaaccagcgtggaccgcttgctgcaactctctcagggccaggcggtgaagggcaatcagctgttgcccgtctcactggtgaaaagaaaaaccaccctggcgcccaatacgcaaaccgcctctccccgcgcgttggccgattcattaatgcagctggcacgacaggtttcccgactggaaagcgggcagtga", ), ), FeatureMapItem::new( "araC", CodingRegion, seq_complement(&seq_from_str( "ttatgacaacttgacggctacatcattcactttttcttcacaaccggcacggaactcgctcgggctggccccggtgcattttttaaatacccgcgagaaatagagttgatcgtcaaaaccaacattgcgaccgacggtggcgataggcatccgggtggtgctcaaaagcagcttcgcctggctgatacgttggtcctcgcgccagcttaagacgctaatccctaactgctggcggaaaagatgtgacagacgcgacggcgacaagcaaacatgctgtgcgacgctggcgatatcaaaattgctgtctgccaggtgatcgctgatgtactgacaagcctcgcgtacccgattatccatcggtggatggagcgactcgttaatcgcttccatgcgccgcagtaacaattgctcaagcagatttatcgccagcagctccgaatagcgcccttccccttgcccggcgttaatgatttgcccaaacaggtcgctgaaatgcggctggtgcgcttcatccgggcgaaagaaccccgtattggcaaatattgacggccagttaagccattcatgccagtaggcgcgcggacgaaagtaaacccactggtgataccattcgcgagcctccggatgacgaccgtagtgatgaatctctcctggcgggaacagcaaaatatcacccggtcggcaaacaaattctcgtccctgatttttcaccaccccctgaccgcgaatggtgagattgagaatataacctttcattcccagcggtcggtcgataaaaaaatcgagataaccgttggcctcaatcggcgttaaacccgccaccagatgggcattaaacgagtatcccggcagcaggggatcattttgcgcttcagccat", )), ), FeatureMapItem::new( "lac operator", ProteinBind, seq_from_str("ttgtgagcggataacaa"), ), FeatureMapItem::new( "lac operator", ProteinBind, seq_from_str("ttgttatccgctcacaa"), ), FeatureMapItem::new( "RBS", RibosomeBindSite, seq_from_str("tttgtttaactttaagaaggaga"), ), FeatureMapItem::new( "T7 terminator", Terminator, seq_from_str("ctagcataaccccttggggcctctaaacgggtcttgaggggttttttg"), ), FeatureMapItem::new( "rrnB T1 terminator", Terminator, seq_from_str( "caaataaaacgaaaggctcagtcgaaagactgggcctttcgttttatctgttgtttgtcggtgaacgctctcctgagtaggacaaat", ), ), FeatureMapItem::new( "rrnB T2 terminator", Terminator, seq_from_str("agaaggccatcctgacggatggcctttt"), ), FeatureMapItem::new( "SV40 promoter", Promoter, seq_from_str( "ctgaggcggaaagaaccagctgtggaatgtgtgtcagttagggtgtggaaagtccccaggctccccagcaggcagaagtatgcaaagcatgcatctcaattagtcagcaaccaggtgtggaaagtccccaggctccccagcaggcagaagtatgcaaagcatgcatctcaattagtcagcaaccatagtcccgcccctaactccgcccatcccgcccctaactccgcccagttccgcccattctccgccccatggctgactaattttttttatttatgcagaggccgaggccgcctcggcctctgagctattccagaagtagtgaggaggcttttttggaggcctaggcttttgcaaa", ), ), FeatureMapItem::new( "CAP binding site", ProteinBind, seq_from_str("atgagtgagctaactcacatta"), ), FeatureMapItem::new( "CAP binding site", ProteinBind, seq_from_str("atgagtgagctaactcacatta"), ), FeatureMapItem::new( "pHluorin2", CodingRegion, seq_from_str( "ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGAGCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACGAGCACCTGGTGTACATCATGGCCGACAAGCAGAAGAACGGCACCAAGGCCATCTTCCAGGTGCACCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGCACACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCACGGCATGGACGAGCTGTACAAGTAA", ), ), FeatureMapItem::new( "SacB", CodingRegion, seq_from_str( "atgaacatcaaaaagtttgcaaaacaagcaacagtattaacctttactaccgcactgctggcaggaggcgcaactcaagcgtttgcgaaagaaacgaaccaaaagccatataaggaaacatacggcatttcccatattacacgccatgatatgctgcaaatccctgaacagcaaaaaaatgaaaaatataaagttcctgagttcgattcgtccacaattaaaaatatctcttctgcaaaaggcctggacgtttgggacagctggccattacaaaacactgacggcactgtcgcaaactatcacggctaccacatcgtctttgcattagccggagatcctaaaaatgcggatgacacatcgatttacatgttctatcaaaaagtcggcgaaacttctattgacagctggaaaaacgctggccgcgtctttaaagacagcgacaaattcgatgcaaatgattctatcctaaaagaccaaacacaagaatggtcaggttcagccacatttacatctgacggaaaaatccgtttattctacactgatttctccggtaaacattacggcaaacaaacactgacaactgcacaagttaacgtatcagcatcagacagctctttgaacatcaacggtgtagaggattataaatcaatctttgacggtgacggaaaaacgtatcaaaatgtacagcagttcatcgatgaaggcaactacagctcaggcgacaaccatacgctgagagatcctcactacgtagaagataaaggccacaaatacttagtatttgaagcaaacactggaactgaagatggctaccaaggcgaagaatctttatttaacaaagcatactatggcaaaagcacatcattcttccgtcaagaaagtcaaaaacttctgcaaagcgataaaaaacgcacggctgagttagcaaacggcgctctcggtatgattgagctaaacgatgattacacactgaaaaaagtgatgaaaccgctgattgcatctaacacagtaacagatgaaattgaacgcgcgaacgtctttaaaatgaacggcaaatggtacctgttcactgactcccgcggatcaaaaatgacgattgacggcattacgtctaacgatatttacatgcttggttatgtttctaattctttaactggcccatacaagccgctgaacaaaactggccttgtgttaaaaatggatcttgatcctaacgatgtaacctttacttactcacacttcgctgtacctcaagcgaaaggaaacaatgtcgtgattacaagctatatgacaaacagaggattctacgcagacaaacaatcaacgtttgcgcctagcttcctgctgaacatcaaaggcaagaaaacatctgttgtcaaagacagcatccttgaacaaggacaattaacagttaacaaataa", ), ), FeatureMapItem::new( "AmpR", AntibioticResistance, seq_complement(&seq_from_str( "gttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcat", )), ), FeatureMapItem::new( "AmpR", AntibioticResistance, seq_from_str( "atgagtattcaacatttccgtgtcgcccttattcccttttttgcggcattttgccttcctgtttttgctcacccagaaacgctggtgaaagtaaaagatgctgaagatcagttgggtgcacgagtgggttacatcgaactggatctcaacagcggtaagatccttgagagttttcgccccgaagaacgttttccaatgatgagcacttttaaagttctgctatgtggcgcggtattatcccgtattgacgccgggcaagagcaactcggtcgccgcatacactattctcagaatgacttggttgagtactcaccagtcacagaaaagcatcttacggatggcatgacagtaagagaattatgcagtgctgccataaccatgagtgataacactgcggccaacttacttctgacaacgatcggaggaccgaaggagctaaccgcttttttgcacaacatgggggatcatgtaactcgccttgatcgttgggaaccggagctgaatgaagccataccaaacgacgagcgtgacaccacgatgcctgtagcaatggcaacaacgttgcgcaaactattaactggcgaactacttactctagcttcccggcaacaattaatagactggatggaggcggataaagttgcaggaccacttctgcgctcggcccttccggctggctggtttattgctgataaatctggagccggtgagcgtgggtcgcgcggtatcattgcagcactggggccagatggtaagccctcccgtatcgtagttatctacacgacggggagtcaggcaactatggatgaacgaaatagacagatcgctgagataggtgcctcactgattaagcattggtaa", ), ), FeatureMapItem::new( "AmpR", AntibioticResistance, seq_from_str( "atgagtattcaacatttccgtgtcgcccttattcccttttttgcggcattttgccttcctgtttttgctcacccagaaacgctggtgaaagtaaaagatgctgaagatcagttgggtgcacgagtgggttacatcgaactggatctcaacagcggtaagatccttgagagttttcgccccgaagaacgttttccaatgatgagcacttttaaagttctgctatgtggcgcggtattatcccgtgttgacgccgggcaagagcaactcggtcgccgcatacactattctcagaatgacttggttgagtactcaccagtcacagaaaagcatcttacggatggcatgacagtaagagaattatgcagtgctgccataaccatgagtgataacactgcggccaacttacttctgacaacgatcggaggaccgaaggagctaaccgcttttttgcacaacatgggggatcatgtaactcgccttgatcgttgggaaccggagctgaatgaagccataccaaacgacgagcgtgacaccacgatgcctgcagcaatggcaacaacgttgcgcaaactattaactggcgaactacttactctagcttcccggcaacaattaatagactggatggaggcggataaagttgcaggaccacttctgcgctcggcccttccggctggctggtttattgctgataaatctggagccggtgagcgtgggtctcgcggtatcattgcagcactggggccagatggtaagccctcccgtatcgtagttatctacacgacggggagtcaggcaactatggatgaacgaaatagacagatcgctgagataggtgcctcactgattaagcattggtaa", ), ), FeatureMapItem::new( "AmpR", AntibioticResistance, seq_complement(&seq_from_str( "ttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctgcaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtg", )), ), FeatureMapItem::new( "KanR", AntibioticResistance, seq_from_str( "gttagaaaaactcatcgagcatcaaatgaaactgcaatttattcatatcaggattatcaataccatatttttgaaaaagccgtttctgtaatgaaggagaaaactcaccgaggcagttccataggatggcaagatcctggtatcggtctgcgattccgactcgtccaacatcaatacaacctattaatttcccctcgtcaaaaataaggttatcaagtgagaaatcaccatgagtgacgactgaatccggtgagaatggcaaaagtttatgcatttctttccagacttgttcaacaggccagccattacgctcgtcatcaaaatcactcgcatcaaccaaaccgttattcattcgtgattgcgcctgagcgagacgaaatacgcgatcgctgttaaaaggacaattacaaacaggaatcgaatgcaaccggcgcaggaacactgccagcgcatcaacaatattttcacctgaatcaggatattcttctaatacctggaatgctgttttcccagggatcgcagtggtgagtaaccatgcatcatcaggagtacggataaaatgcttgatggtcggaagaggcataaattccgtcagccagtttagtctgaccatctcatctgtaacatcattggcaacgctacctttgccatgtttcagaaacaactctggcgcatcgggcttcccatacaatcgatagattgtcgcacctgattgcccgacattatcgcgagcccatttatacccatataaatcagcatccatgttggaatttaatcgcggcctagagcaagacgtttcccgttgaatatggctcat", ), ), FeatureMapItem::new( "KanR", AntibioticResistance, seq_from_str( "atgagccatattcaacgggaaacgtcttgctctaggccgcgattaaattccaacatggatgctgatttatatgggtataaatgggctcgcgataatgtcgggcaatcaggtgcgacaatctatcgattgtatgggaagcccgatgcgccagagttgtttctgaaacatggcaaaggtagcgttgccaatgatgttacagatgagatggtcagactaaactggctgacggaatttatgcctcttccgaccatcaagcattttatccgtactcctgatgatgcatggttactcaccactgcgatccccgggaaaacagcattccaggtattagaagaatatcctgattcaggtgaaaatattgttgatgcgctggcagtgttcctgcgccggttgcattcgattcctgtttgtaattgtccttttaacagcgatcgcgtatttcgtctcgctcaggcgcaatcacgaatgaataacggtttggttgatgcgagtgattttgatgacgagcgtaatggctggcctgttgaacaagtctggaaagaaatgcataaacttttgccattctcaccggattcagtcgtcactcatggtgatttctcacttgataaccttatttttgacgaggggaaattaataggttgtattgatgttggacgagtcggaatcgcagaccgataccaggatcttgccatcctatggaactgcctcggtgagttttctccttcattacagaaacggctttttcaaaaatatggtattgataatcctgatatgaataaattgcagtttcatttgatgctcgatgagtttttctaa", ), ), FeatureMapItem::new( "CmR", AntibioticResistance, seq_complement(&seq_from_str( "attacgccccgccctgccactcatcgcagtactgttgtaattcattaagcattctgccgacatggaagccatcacaaacggcatgatgaacctgaatcgccagcggcatcagcaccttgtcgccttgcgtataatatttgcccatagtgaaaacgggggcgaagaagttgtccatattggccacgtttaaatcaaaactggtgaaactcacccagggattggctgagacgaaaaacatattctcaataaaccctttagggaaataggccaggttttcaccgtaacacgccacatcttgcgaatatatgtgtagaaactgccggaaatcgtcgtggtattcactccagagcgatgaaaacgtttcagtttgctcatggaaaacggtgtaacaagggtgaacactatcccatatcaccagctcaccgtctttcattgccatacggaactccggatgagcattcatcaggcgggcaagaatgtgaataaaggccggataaaacttgtgcttatttttctttacggtctttaaaaaggccgtaatatccagctgaacggtctggttataggtacattgagcaactgactgaaatgcctcaaaatgttctttacgatgccattgggatatatcaacggtggtatatccagtgatttttttctccat", )), ), FeatureMapItem::new( "CmR", AntibioticResistance, seq_complement(&seq_from_str( "ttacgccccgccctgccactcatcgcagtactgttgtaattcattaagcattctgccgacatggaagccatcacaaacggcatgatgaacctgaatcgccagcggcatcagcaccttgtcgccttgcgtataatatttgcccatagtgaaaacgggggcgaagaagttgtccatattggccacgtttaaatcaaaactggtgaaactcacccagggattggctgagacgaaaaacatattctcaataaaccctttagggaaataggccaggttttcaccgtaacacgccacatcttgcgaatatatgtgtagaaactgccggaaatcgtcgtggtattcactccagagcgatgaaaacgtttcagtttgctcatggaaaacggtgtaacaagggtgaacactatcccatatcaccagctcaccgtctttcattgccatacggaactccggatgagcattcatcaggcgggcaagaatgtgaataaaggccggataaaacttgtgcttatttttctttacggtctttaaaaaggccgtaatatccagctgaacggtctggttataggtacattgagcaactgactgaaatgcctcaaaatgttctttacgatgccattgggatatatcaacggtggtatatccagtgatttttttctccat", )), ), FeatureMapItem::new( "NeoR/KanR", AntibioticResistance, seq_from_str( "atgattgaacaagatggattgcacgcaggttctccggccgcttgggtggagaggctattcggctatgactgggcacaacagacaatcggctgctctgatgccgccgtgttccggctgtcagcgcaggggcgcccggttctttttgtcaagaccgacctgtccggtgccctgaatgaactgcaagacgaggcagcgcggctatcgtggctggccacgacgggcgttccttgcgcagctgtgctcgacgttgtcactgaagcgggaagggactggctgctattgggcgaagtgccggggcaggatctcctgtcatctcaccttgctcctgccgagaaagtatccatcatggctgatgcaatgcggcggctgcatacgcttgatccggctacctgcccattcgaccaccaagcgaaacatcgcatcgagcgagcacgtactcggatggaagccggtcttgtcgatcaggatgatctggacgaagagcatcaggggctcgcgccagccgaactgttcgccaggctcaaggcgagcatgcccgacggcgaggatctcgtcgtgacccatggcgatgcctgcttgccgaatatcatggtggaaaatggccgcttttctggattcatcgactgtggccggctgggtgtggcggaccgctatcaggacatagcgttggctacccgtgatattgctgaagagcttggcggcgaatgggctgaccgcttcctcgtgctttacggtatcgccgctcccgattcgcagcgcatcgccttctatcgccttcttgacgagttcttctga", ), ), FeatureMapItem::new( "CMV enhancer", CodingRegion, seq_from_str( "cgttacataacttacggtaaatggcccgcctggctgaccgcccaacgacccccgcccattgacgtcaataatgacgtatgttcccatagtaacgccaatagggactttccattgacgtcaatgggtggagtatttacggtaaactgcccacttggcagtacatcaagtgtatcatatgccaagtacgccccctattgacgtcaatgacggtaaatggcccgcctggcattatgcccagtacatgaccttatgggactttcctacttggcagtacatctacgtattagtcatcgctattaccatg", ), ), FeatureMapItem::new( "EGFP", CodingRegion, seq_from_str( "ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACAGCCACAACGTCTATATCATGGCCGACAAGCAGAAGAACGGCATCAAGGTGAACTTCAAGATCCGCCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGAGCACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCTCGGCATGGACGAGCTGTACAAGTAA", ), ), FeatureMapItem::new( "TcR", CodingRegion, seq_from_str( "atgaaatctaacaatgcgctcatcgtcatcctcggcaccgtcaccctggatgctgtaggcataggcttggttatgccggtactgccgggcctcttgcgggatatcgtccattccgacagcatcgccagtcactatggcgtgctgctagcgctatatgcgttgatgcaatttctatgcgcacccgttctcggagcactgtccgaccgctttggccgccgcccagtcctgctcgcttcgctacttggagccactatcgactacgcgatcatggcgaccacacccgtcctgtggatcctctacgccggacgcatcgtggccggcatcaccggcgccacaggtgcggttgctggcgcctatatcgccgacatcaccgatggggaagatcgggctcgccacttcgggctcatgagcgcttgtttcggcgtgggtatggtggcaggccccgtggccgggggactgttgggcgccatctccttgcatgcaccattccttgcggcggcggtgctcaacggcctcaacctactactgggctgcttcctaatgcaggagtcgcataagggagagcgtcgaccgatgcccttgagagccttcaacccagtcagctccttccggtgggcgcggggcatgactatcgtcgccgcacttatgactgtcttctttatcatgcaactcgtaggacaggtgccggcagcgctctgggtcattttcggcgaggaccgctttcgctggagcgcgacgatgatcggcctgtcgcttgcggtattcggaatcttgcacgccctcgctcaagccttcgtcactggtcccgccaccaaacgtttcggcgagaagcaggccattatcgccggcatggcggccgacgcgctgggctacgtcttgctggcgttcgcgacgcgaggctggatggccttccccattatgattcttctcgcttccggcggcatcgggatgcccgcgttgcaggccatgctgtccaggcaggtagatgacgaccatcagggacagcttcaaggatcgctcgcggctcttaccagcctaacttcgatcattggaccgctgatcgtcacggcgatttatgccgcctcggcgagcacatggaacgggttggcatggattgtaggcgccgccctataccttgtctgcctccccgcgttgcgtcgcggtgcatggagccgggccacctcgacctga", ), ), FeatureMapItem::new( "GST", CodingRegion, seq_from_str( "atgtcccctatactaggttattggaaaattaagggccttgtgcaacccactcgacttcttttggaatatcttgaagaaaaatatgaagagcatttgtatgagcgcgatgaaggtgataaatggcgaaacaaaaagtttgaattgggtttggagtttcccaatcttccttattatattgatggtgatgttaaattaacacagtctatggccatcatacgttatatagctgacaagcacaacatgttgggtggttgtccaaaagagcgtgcagagatttcaatgcttgaaggagcggttttggatattagatacggtgtttcgagaattgcatatagtaaagactttgaaactctcaaagttgattttcttagcaagctacctgaaatgctgaaaatgttcgaagatcgtttatgtcataaaacatatttaaatggtgatcatgtaacccatcctgacttcatgttgtatgacgctcttgatgttgttttatacatggacccaatgtgcctggatgcgttcccaaaattagtttgttttaaaaaacgtattgaagctatcccacaaattgataagtacttgaaatccagcaagtatatagcatggcctttgcagggctggcaagccacgtttggtggtggcgaccatcctccaaaa", ), ), // todo: How general is this? FeatureMapItem::new( "Ori", Ori, seq_complement(&seq_from_str( "ttttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaa", )), ), FeatureMapItem::new( "Ori", Ori, seq_complement(&seq_from_str( "tttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaa", )), ), FeatureMapItem::new( "f1 ori", Ori, seq_from_str(
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
true
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/melting_temp_calcs.rs
src/melting_temp_calcs.rs
#![allow(non_snake_case)] //! Primer melting temperature calculations. Modified from [BioPython's module here](https://github.com/biopython/biopython/blob/master/Bio/SeqUtils/MeltingTemp.py) //! We use an approach that calculates enthalpy and entropy of neighbors basd on empirical data, //! and apply salt corrections based on user input concentrations of ions and primers. //! //! The calculations are based primarily on [SantaLucia & Hicks (2004)](https://pubmed.ncbi.nlm.nih.gov/15139820/) //! //! [This calculator from NorthWestern](http://biotools.nubic.northwestern.edu/OligoCalc.html) may be used //! for QC TM, weight, and other properties. It includes detailed sources and methods. use na_seq::{ Nucleotide::{self, A, C, G, T}, calc_gc, }; use crate::primer::{IonConcentrations, MIN_PRIMER_LEN}; const R: f32 = 1.987; // Universal gas constant (Cal/C * Mol) /// Enthalpy (dH) and entropy (dS) tables based on terminal missmatch fn _dH_dS_tmm(nts: (Nucleotide, Nucleotide)) -> Option<(f32, f32)> { match nts { (A, A) => Some((-7.6, -21.3)), (A, T) => Some((-7.2, -20.4)), (T, A) => Some((-7.2, -21.3)), (C, A) => Some((-8.5, -22.7)), (C, G) => Some((-10.6, -27.2)), (G, A) => Some((-8.2, -22.2)), (G, C) => Some((-9.8, -24.4)), (G, T) => Some((-8.4, -22.4)), (G, G) => Some((-8.0, -19.9)), _ => None, } // # Terminal mismatch table (DNA) // # SantaLucia & Peyret (2001) Patent Application WO 01/94611 // DNA_TMM1 = { // "AA/TA": (-3.1, -7.8), // "TA/AA": (-2.5, -6.3), // "CA/GA": (-4.3, -10.7), // "GA/CA": (-8.0, -22.5), // "AC/TC": (-0.1, 0.5), // "TC/AC": (-0.7, -1.3), // "CC/GC": (-2.1, -5.1), // "GC/CC": (-3.9, -10.6), // "AG/TG": (-1.1, -2.1), // "TG/AG": (-1.1, -2.7), // "CG/GG": (-3.8, -9.5), // "GG/CG": (-0.7, -19.2), // "AT/TT": (-2.4, -6.5), // "TT/AT": (-3.2, -8.9), // "CT/GT": (-6.1, -16.9), // "GT/CT": (-7.4, -21.2), // "AA/TC": (-1.6, -4.0), // "AC/TA": (-1.8, -3.8), // "CA/GC": (-2.6, -5.9), // "CC/GA": (-2.7, -6.0), // "GA/CC": (-5.0, -13.8), // "GC/CA": (-3.2, -7.1), // "TA/AC": (-2.3, -5.9), "TC/AA": (-2.7, -7.0), // "AC/TT": (-0.9, -1.7), "AT/TC": (-2.3, -6.3), "CC/GT": (-3.2, -8.0), // "CT/GC": (-3.9, -10.6), "GC/CT": (-4.9, -13.5), "GT/CC": (-3.0, -7.8), // "TC/AT": (-2.5, -6.3), "TT/AC": (-0.7, -1.2), // "AA/TG": (-1.9, -4.4), "AG/TA": (-2.5, -5.9), "CA/GG": (-3.9, -9.6), // "CG/GA": (-6.0, -15.5), "GA/CG": (-4.3, -11.1), "GG/CA": (-4.6, -11.4), // "TA/AG": (-2.0, -4.7), "TG/AA": (-2.4, -5.8), // "AG/TT": (-3.2, -8.7), "AT/TG": (-3.5, -9.4), "CG/GT": (-3.8, -9.0), // "CT/GG": (-6.6, -18.7), "GG/CT": (-5.7, -15.9), "GT/CG": (-5.9, -16.1), // "TG/AT": (-3.9, -10.5), "TT/AG": (-3.6, -9.8)} } /// Enthalpy (dH) and entropy (dS) tables based on internal missmatch fn _dH_dS_imm(nts: (Nucleotide, Nucleotide)) -> Option<(f32, f32)> { match nts { (A, A) => Some((-7.6, -21.3)), (A, T) => Some((-7.2, -20.4)), (T, A) => Some((-7.2, -21.3)), (C, A) => Some((-8.5, -22.7)), (C, G) => Some((-10.6, -27.2)), (G, A) => Some((-8.2, -22.2)), (G, C) => Some((-9.8, -24.4)), (G, T) => Some((-8.4, -22.4)), (G, G) => Some((-8.0, -19.9)), _ => None, } // # Internal mismatch and inosine table (DNA) // # Allawi & SantaLucia (1997), Biochemistry 36: 10581-10594 // # Allawi & SantaLucia (1998), Biochemistry 37: 9435-9444 // # Allawi & SantaLucia (1998), Biochemistry 37: 2170-2179 // # Allawi & SantaLucia (1998), Nucl Acids Res 26: 2694-2701 // # Peyret et al. (1999), Biochemistry 38: 3468-3477 // # Watkins & SantaLucia (2005), Nucl Acids Res 33: 6258-6267 // DNA_IMM1 = { // "AG/TT": (1.0, 0.9), "AT/TG": (-2.5, -8.3), "CG/GT": (-4.1, -11.7), // "CT/GG": (-2.8, -8.0), "GG/CT": (3.3, 10.4), "GG/TT": (5.8, 16.3), // "GT/CG": (-4.4, -12.3), "GT/TG": (4.1, 9.5), "TG/AT": (-0.1, -1.7), // "TG/GT": (-1.4, -6.2), "TT/AG": (-1.3, -5.3), "AA/TG": (-0.6, -2.3), // "AG/TA": (-0.7, -2.3), "CA/GG": (-0.7, -2.3), "CG/GA": (-4.0, -13.2), // "GA/CG": (-0.6, -1.0), "GG/CA": (0.5, 3.2), "TA/AG": (0.7, 0.7), // "TG/AA": (3.0, 7.4), // "AC/TT": (0.7, 0.2), "AT/TC": (-1.2, -6.2), "CC/GT": (-0.8, -4.5), // "CT/GC": (-1.5, -6.1), "GC/CT": (2.3, 5.4), "GT/CC": (5.2, 13.5), // "TC/AT": (1.2, 0.7), "TT/AC": (1.0, 0.7), // "AA/TC": (2.3, 4.6), "AC/TA": (5.3, 14.6), "CA/GC": (1.9, 3.7), // "CC/GA": (0.6, -0.6), "GA/CC": (5.2, 14.2), "GC/CA": (-0.7, -3.8), // "TA/AC": (3.4, 8.0), "TC/AA": (7.6, 20.2), // "AA/TA": (1.2, 1.7), "CA/GA": (-0.9, -4.2), "GA/CA": (-2.9, -9.8), // "TA/AA": (4.7, 12.9), "AC/TC": (0.0, -4.4), "CC/GC": (-1.5, -7.2), // "GC/CC": (3.6, 8.9), "TC/AC": (6.1, 16.4), "AG/TG": (-3.1, -9.5), // "CG/GG": (-4.9, -15.3), "GG/CG": (-6.0, -15.8), "TG/AG": (1.6, 3.6), // "AT/TT": (-2.7, -10.8), "CT/GT": (-5.0, -15.8), "GT/CT": (-2.2, -8.4), // "TT/AT": (0.2, -1.5), // "AI/TC": (-8.9, -25.5), "TI/AC": (-5.9, -17.4), "AC/TI": (-8.8, -25.4), // "TC/AI": (-4.9, -13.9), "CI/GC": (-5.4, -13.7), "GI/CC": (-6.8, -19.1), // "CC/GI": (-8.3, -23.8), "GC/CI": (-5.0, -12.6), // "AI/TA": (-8.3, -25.0), "TI/AA": (-3.4, -11.2), "AA/TI": (-0.7, -2.6), // "TA/AI": (-1.3, -4.6), "CI/GA": (2.6, 8.9), "GI/CA": (-7.8, -21.1), // "CA/GI": (-7.0, -20.0), "GA/CI": (-7.6, -20.2), // "AI/TT": (0.49, -0.7), "TI/AT": (-6.5, -22.0), "AT/TI": (-5.6, -18.7), // "TT/AI": (-0.8, -4.3), "CI/GT": (-1.0, -2.4), "GI/CT": (-3.5, -10.6), // "CT/GI": (0.1, -1.0), "GT/CI": (-4.3, -12.1), // "AI/TG": (-4.9, -15.8), "TI/AG": (-1.9, -8.5), "AG/TI": (0.1, -1.8), // "TG/AI": (1.0, 1.0), "CI/GG": (7.1, 21.3), "GI/CG": (-1.1, -3.2), // "CG/GI": (5.8, 16.9), "GG/CI": (-7.6, -22.0), // "AI/TI": (-3.3, -11.9), "TI/AI": (0.1, -2.3), "CI/GI": (1.3, 3.0), // "GI/CI": (-0.5, -1.3)} } /// Enthalpy (dH) and entropy (dS) tables based on dangling ends. fn _dH_dS_de(nts: (Nucleotide, Nucleotide)) -> Option<(f32, f32)> { match nts { (A, A) => Some((0.2, 2.3)), (A, T) => Some((-7.2, -20.4)), (T, A) => Some((-7.2, -21.3)), (C, A) => Some((-8.5, -22.7)), (C, G) => Some((-10.6, -27.2)), (G, A) => Some((-8.2, -22.2)), (G, C) => Some((-9.8, -24.4)), (G, T) => Some((-8.4, -22.4)), (G, G) => Some((-8.0, -19.9)), _ => None, } // # Dangling ends table (DNA) // # Bommarito et al. (2000), Nucl Acids Res 28: 1929-1934 // DNA_DE1 = { // "AA/.T": (0.2, 2.3), "AC/.G": (-6.3, -17.1), "AG/.C": (-3.7, -10.0), // "AT/.A": (-2.9, -7.6), "CA/.T": (0.6, 3.3), "CC/.G": (-4.4, -12.6), // "CG/.C": (-4.0, -11.9), "CT/.A": (-4.1, -13.0), "GA/.T": (-1.1, -1.6), // "GC/.G": (-5.1, -14.0), "GG/.C": (-3.9, -10.9), "GT/.A": (-4.2, -15.0), // "TA/.T": (-6.9, -20.0), "TC/.G": (-4.0, -10.9), "TG/.C": (-4.9, -13.8), // "TT/.A": (-0.2, -0.5), // ".A/AT": (-0.7, -0.8), ".C/AG": (-2.1, -3.9), ".G/AC": (-5.9, -16.5), // ".T/AA": (-0.5, -1.1), ".A/CT": (4.4, 14.9), ".C/CG": (-0.2, -0.1), // ".G/CC": (-2.6, -7.4), ".T/CA": (4.7, 14.2), ".A/GT": (-1.6, -3.6), // ".C/GG": (-3.9, -11.2), ".G/GC": (-3.2, -10.4), ".T/GA": (-4.1, -13.1), // ".A/TT": (2.9, 10.4), ".C/TG": (-4.4, -13.1), ".G/TC": (-5.2, -15.0), // ".T/TA": (-3.8, -12.6)} } /// Enthalpy (dH) and entropy (dS) based on nearest neighbors. /// SantaLucia & Hicks, 2004, Table 1. Value are in kcal/Mol. /// /// `neighbors` refers to the values between adjacent pairs of NTs. /// To interpret this table, and come up with this result, search it in these /// two manners: /// A: Left to right, left of the slash /// B: Right to left, right of the slash /// You will find exactly one match using this approach. fn dH_dS_neighbors(neighbors: (Nucleotide, Nucleotide)) -> (f32, f32) { match neighbors { (A, A) | (T, T) => (-7.6, -21.3), (A, T) => (-7.2, -20.4), (T, A) => (-7.2, -21.3), (C, A) | (T, G) => (-8.5, -22.7), (G, T) | (A, C) => (-8.4, -22.4), (C, T) | (A, G) => (-7.8, -21.0), (G, A) | (T, C) => (-8.2, -22.2), (C, G) => (-10.6, -27.2), (G, C) => (-9.8, -24.4), (G, G) | (C, C) => (-8.0, -19.9), } } /// Calculate a Tm correction term due to salt ions. /// https://github.com/biopython/biopython/blob/master/Bio/SeqUtils/MeltingTemp.py#L475 fn salt_correction(seq: &[Nucleotide], ion: &IonConcentrations) -> Option<f32> { // todo: Using Some casual defaults for now. // These are millimolar concentration of respective ions. let method = 5; // todo? let tris = 0.; // todo: Do we want this? if (5..=7).contains(&method) && seq.is_empty() { // return Err("sequence is missing (is needed to calculate GC content or sequence length).".into()); return None; } let mut corr = 0.0; if method == 0 { return Some(corr); } // It appears that this section modifies the monovalent concentration with divalent values. let mut mon = ion.monovalent + tris / 2.0; let mon_molar = mon * 1e-3; let mg_molar = ion.divalent * 1e-3; if (ion.monovalent > 0.0 || ion.divalent > 0.0 || tris > 0.0 || ion.dntp > 0.0) && method != 7 && ion.dntp < ion.divalent { mon += 120.0 * (ion.divalent - ion.dntp).sqrt(); } if (1..=6).contains(&method) && mon_molar == 0.0 { // return Err("Total ion concentration of zero is not allowed in this method.".into()); return None; } match method { 1 => corr = 16.6 * mon_molar.log10(), 2 => corr = 16.6 * (mon_molar / (1.0 + 0.7 * mon_molar)).log10(), 3 => corr = 12.5 * mon_molar.log10(), 4 => corr = 11.7 * mon_molar.log10(), 5 => { corr = 0.368 * (seq.len() as f32 - 1.0) * mon_molar.ln(); } 6 => { let gc_fraction = calc_gc(seq); corr = ((4.29 * gc_fraction - 3.95) * 1e-5 * mon_molar.ln()) + 9.40e-6 * mon_molar.ln().powi(2); } 7 => { let (mut a, b, c, mut d, e, f, mut g) = (3.92, -0.911, 6.26, 1.42, -48.2, 52.5, 8.31); let mut mg_free = mg_molar; if ion.dntp > 0.0 { let dntps_molar = ion.dntp * 1e-3; let ka = 3e4; // Free Mg2+ calculation mg_free = (-(ka * dntps_molar - ka * mg_free + 1.0) + ((ka * dntps_molar - ka * mg_free + 1.0).powi(2) + 4.0 * ka * mg_free) .sqrt()) / (2.0 * ka); } if mon > 0.0 { let r = (mg_free).sqrt() / mon_molar; if r < 0.22 { let gc_fraction = calc_gc(seq); corr = (4.29 * gc_fraction - 3.95) * 1e-5 * mon_molar.ln() + 9.40e-6 * mon_molar.ln().powi(2); return Some(corr); } else if r < 6.0 { a = 3.92 * (0.843 - 0.352 * mon_molar.sqrt() * mon_molar.ln()); d = 1.42 * (1.279 - 4.03e-3 * mon_molar.ln() - 8.03e-3 * mon_molar.ln().powi(2)); g = 8.31 * (0.486 - 0.258 * mon_molar.ln() + 5.25e-3 * mon_molar.ln().powi(3)); } let gc_fraction = calc_gc(seq); corr = (a + b * mg_free.ln() + gc_fraction * (c + d * mg_free.ln()) + (1.0 / (2.0 * (seq.len() as f32 - 1.0))) * (e + f * mg_free.ln() + g * mg_free.ln().powi(2))) * 1e-5; } } _ => return None, } Some(corr) } pub fn calc_tm(seq: &[Nucleotide], ion_concentrations: &IonConcentrations) -> Option<f32> { if seq.len() < MIN_PRIMER_LEN { return None; } // Inititial values. (S&H, Table 1) let mut dH = 0.2; let mut dS = -5.7; // If no GC content, apply additional values. (Table 1) if calc_gc(seq) < 0.001 { dH += 2.2; dS += 6.9; } // Add to dH and dS based on the terminal pair. { let term_pair = vec![seq[0], seq[seq.len() - 1]]; let mut at_term_count = 0; // Constants for the CG term are 0, so we don't need it. for nt in term_pair { if nt == A || nt == T { at_term_count += 1; } } dH += 2.2 * at_term_count as f32; dS += 6.9 * at_term_count as f32; } for (i, nt) in seq.iter().enumerate() { if i + 1 >= seq.len() { break; } let neighbors = (*nt, seq[i + 1]); let (dH_nn, dS_nn) = dH_dS_neighbors(neighbors); dH += dH_nn; dS += dS_nn; } let C_T = ion_concentrations.primer * 1.0e-9; // println!("\n\ndH: {dH} dS: {dS}"); if let Some(sc) = salt_correction(seq, ion_concentrations) { // Hard-coded for salt-correction method 5. dS += sc; // result += sc; // for saltcorr 6/7: // result = 1. / (1. / (result + 273.15) + sc) - 273.15 } else { eprintln!("Error calculating salt correction."); } // SantaLucia and Hicks, Equation 3. Note the C_T / 2 vice / 4, due to double-stranded concentration. let result = (1_000. * dH) / (dS + R * (C_T / 2.).ln()) - 273.15; Some(result) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/alignment.rs
src/alignment.rs
use bio::alignment::{ Alignment, distance::simd::{bounded_levenshtein, hamming, levenshtein}, pairwise::Aligner, }; use na_seq::{AminoAcid, Nucleotide, Seq, seq_aa_to_u8_lower, seq_to_u8_lower}; #[derive(Clone, Copy, PartialEq)] pub enum AlignmentMode { Dna, AminoAcid, } impl Default for AlignmentMode { fn default() -> Self { Self::Dna } } #[derive(Default)] pub struct AlignmentState { pub seq_a: Seq, pub seq_b: Seq, pub seq_aa_a: Vec<AminoAcid>, pub seq_aa_b: Vec<AminoAcid>, // todo: Perhaps these inputs are better fit for State_ui. pub seq_a_input: String, pub seq_b_input: String, pub alignment_result: Option<Alignment>, pub dist_result: Option<u64>, pub text_display: String, // Ie `AlignmentResult::pretty`. pub mode: AlignmentMode, } #[derive(Clone, Copy)] /// Use Hamming Distance if: /// Sequences are of the same length. /// You're only looking for substitutions and the sequences are already aligned. /// Fast, low-complexity calculations are a priority. /// Use Levenshtein Distance if: /// Sequences vary in length. /// Insertions, deletions, and substitutions are all meaningful for your comparison. /// You need a precise measure of distance for downstream processing. /// Use Bounded Levenshtein Distance if: /// You have a known tolerance or threshold for "closeness." /// You want to filter out sequences that are too different without computing the full distance. /// Speed and scalability are critical considerations. pub enum DistanceType { Hamming, Levenshtein, /// Inner: u32 BoundedLevenshtein(u32), } // todo: Which dist algo? bounded_levenshtein, hamming, levenshtein? /// Accepts UTF-8 byte representation of letters. fn distance(alpha: &[u8], beta: &[u8]) -> u64 { let dist_type = if alpha.len() == beta.len() { DistanceType::Hamming } else { DistanceType::Levenshtein }; match dist_type { DistanceType::Hamming => hamming(&alpha, &beta), DistanceType::Levenshtein => levenshtein(&alpha, &beta) as u64, DistanceType::BoundedLevenshtein(k) => { bounded_levenshtein(&alpha, &beta, k).unwrap() as u64 } } } pub fn distance_nt(alpha: &[Nucleotide], beta: &[Nucleotide]) -> u64 { let alpha_ = seq_to_u8_lower(alpha); let beta_ = seq_to_u8_lower(beta); distance(&alpha_, &beta_) } pub fn distance_aa(alpha: &[AminoAcid], beta: &[AminoAcid]) -> u64 { let alpha_ = seq_aa_to_u8_lower(alpha); let beta_ = seq_aa_to_u8_lower(beta); distance(&alpha_, &beta_) } fn align_pairwise(seq_0: &[u8], seq_1: &[u8]) -> (Alignment, String) { // todo: Lots of room to configure this. let score = |a: u8, b: u8| if a == b { 1i32 } else { -1i32 }; let mut aligner = Aligner::with_capacity(seq_0.len(), seq_1.len(), -5, -1, &score); // todo: Global? Semiglobal? Local? let result = aligner.semiglobal(seq_0, seq_1); let text = result.pretty(seq_0, seq_1, 120); (result, text) } pub fn align_pairwise_nt(seq_0: &[Nucleotide], seq_1: &[Nucleotide]) -> (Alignment, String) { // todo: Lots of room to configure this. let seq_0_ = seq_to_u8_lower(seq_0); let seq_1_ = seq_to_u8_lower(seq_1); align_pairwise(&seq_0_, &seq_1_) } pub fn align_pairwise_aa(seq_0: &[AminoAcid], seq_1: &[AminoAcid]) -> (Alignment, String) { // todo: Lots of room to configure this. let seq_0_ = seq_aa_to_u8_lower(seq_0); let seq_1_ = seq_aa_to_u8_lower(seq_1); align_pairwise(&seq_0_, &seq_1_) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/state.rs
src/state.rs
//! Data structures relalted to general state. use std::{ io, path::{Path, PathBuf}, time::Instant, }; use bio_files::SeqRecordAb1; use copypasta::{ClipboardContext, ClipboardProvider}; use eframe::egui::Context; use na_seq::{ Nucleotide, Seq, insert_into_seq, ligation::LigationFragment, re_lib::load_re_library, restriction_enzyme::{ReMatch, RestrictionEnzyme, find_re_matches}, seq_to_str_lower, }; use crate::{ PREFS_SAVE_INTERVAL, Selection, StateUi, alignment::AlignmentState, backbones::{Backbone, load_backbone_library}, cloning::CloningState, file_io::{ GenericData, save::{DEFAULT_PREFS_FILE, PrefsToSave, StateToSave, load, load_import, save}, }, gui, gui::navigation::Tab, misc_types::{MIN_SEARCH_LEN, SearchMatch, find_search_matches}, pcr::PcrParams, portions::PortionsState, primer::IonConcentrations, protein::{Protein, proteins_from_seq, sync_cr_orf_matches}, reading_frame::{ReadingFrame, ReadingFrameMatch, find_orf_matches}, tags::TagMatch, util::RangeIncl, }; impl eframe::App for State { /// This is the GUI's event loop. This also handles periodically saving preferences to disk. /// Note that preferences are only saved if the window is active, ie mouse movement in it or similar. fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { // Note that if the window is static mut LAST_PREF_SAVE: Option<Instant> = None; let now = Instant::now(); unsafe { if let Some(last_save) = LAST_PREF_SAVE { if (now - last_save).as_secs() > PREFS_SAVE_INTERVAL { LAST_PREF_SAVE = Some(now); self.update_save_prefs() } } else { // Initialize LAST_PREF_SAVE the first time it's accessed LAST_PREF_SAVE = Some(now); } } gui::draw(self, ctx); } } /// Note: use of serde traits here and on various sub-structs are for saving and loading. pub struct State { pub ui: StateUi, /// Ie tab, file etc. pub active: usize, // todo: Consider grouping generic, path_loaded, portions, and similar in a single vec. // todo: Do that after your initial tab approach works. /// Data that is the most fundamental to persistent state, and shared between save formats. /// Index corresponds to `active`. pub generic: Vec<GenericData>, /// Index corresponds to `active`. pub ab1_data: Vec<SeqRecordAb1>, // Used to determine which file to save to, if applicable. // file_active: Option<Tab>, /// Index corresponds to `active`. pub tabs_open: Vec<Tab>, /// Index corresponds to `active`. pub portions: Vec<PortionsState>, /// Index corresponds to `active`. pub volatile: Vec<StateVolatile>, /// Used for PCR. // todo: YOu may need to go back to per-tab ion concentrations. // ion_concentrations: Vec<IonConcentrations>, pub ion_concentrations: IonConcentrations, pub pcr: PcrParams, pub restriction_enzyme_lib: Vec<RestrictionEnzyme>, // Does not need to be saved pub backbone_lib: Vec<Backbone>, pub reading_frame: ReadingFrame, pub search_seq: Seq, pub cloning: CloningState, pub alignment: AlignmentState, } impl Default for State { fn default() -> Self { let mut result = Self { ui: Default::default(), active: Default::default(), generic: vec![Default::default()], ab1_data: vec![Default::default()], tabs_open: vec![Default::default()], portions: vec![Default::default()], // ion_concentrations: vec![Default::default()], ion_concentrations: Default::default(), pcr: Default::default(), restriction_enzyme_lib: Default::default(), backbone_lib: Default::default(), reading_frame: Default::default(), volatile: vec![Default::default()], search_seq: Default::default(), cloning: Default::default(), alignment: Default::default(), }; // Load the RE lib before prefs, because prefs may include loading of previously-opened files, // which then trigger RE match syncs. result.restriction_enzyme_lib = load_re_library(); result.backbone_lib = load_backbone_library(); result } } impl State { /// Add a default-settings tab, and open it. pub fn add_tab(&mut self) { self.generic.push(Default::default()); // self.ion_concentrations.push(Default::default()); // self.tabs_open.push(Default::default()); self.portions.push(Default::default()); self.volatile.push(Default::default()); self.ab1_data.push(Default::default()); self.active = self.generic.len() - 1; // todo: DRY with reset self.ui.cursor_pos = None; self.ui.cursor_seq_i = None; self.ui.text_cursor_i = Some(0); self.ui.seq_input = String::new(); // Sync items that aren't stored as part of tabs. self.sync_re_sites(); self.sync_reading_frame(); // println!("Saving prefs"); // self.save_prefs() } pub fn remove_tab(&mut self, i: usize) { let n = self.generic.len(); if n == 1 { // We are closing the last tab; replace it with a blank slate. self.reset(); return; } if i >= n { return; } self.generic.remove(i); self.ab1_data.remove(i); // self.ion_concentrations.remove(i); self.tabs_open.remove(i); self.portions.remove(i); self.volatile.remove(i); let mut tab_i_removed = None; for (j, tab) in self.ui.re.tabs_selected.iter().enumerate() { if *tab == i { tab_i_removed = Some(j); } } if let Some(j) = tab_i_removed { self.ui.re.tabs_selected.remove(j); } // Don't let the active tab overflow to the right; move it to the left if it would. // And, don't move the active tab left only if it would underflow; this effectively moves it right. if (self.active > 0 && self.active <= i && n > 1) || self.active + 1 >= n { self.active -= 1; } // So these tabs don't open on the next program run. self.update_save_prefs() } /// Convenience function, since we call this so frequently. pub fn get_seq(&self) -> &[Nucleotide] { &self.generic[self.active].seq } /// Reset data; we currently use this for making "new" data. pub fn reset(&mut self) { self.generic[self.active] = Default::default(); self.tabs_open[self.active] = Default::default(); self.portions[self.active] = Default::default(); self.volatile[self.active] = Default::default(); // todo: Ideally we reset the window title here, but we've having trouble with variable // todo scope in the input function. self.ui.cursor_pos = None; self.ui.cursor_seq_i = None; self.ui.text_cursor_i = Some(0); // todo: For now; having trouble with cursor on empty seq self.ui.seq_input = String::new(); } /// Load UI and related data not related to a specific sequence. /// This will also open all files specified in the saved preferences. pub fn load_prefs(&mut self, path: &Path) { let prefs_loaded: io::Result<PrefsToSave> = load(path); if let Ok(prefs) = prefs_loaded { let (ui, tabs_open, ion_concentrations) = prefs.to_state(); self.ui = ui; self.ion_concentrations = ion_concentrations; for tab in &tabs_open { if let Some(path) = &tab.path { if let Some(loaded) = load_import(path) { self.load(&loaded); } } } } } pub fn update_save_prefs(&self) { if let Err(e) = save( &PathBuf::from(DEFAULT_PREFS_FILE), &PrefsToSave::from_state(&self.ui, &self.tabs_open, &self.ion_concentrations), ) { eprintln!("Error saving prefs: {e}"); } } /// Runs the match search between primers and sequences. Run this when primers and sequences change. pub fn sync_primer_matches(&mut self, primer_i: Option<usize>) { let seq = &self.generic[self.active].seq.clone(); // todo; Not ideal to clone. let primers = match primer_i { Some(i) => &mut self.generic[self.active].primers[i..=i], // Run on all primers. None => &mut self.generic[self.active].primers, }; for primer in primers { primer.volatile.matches = primer.match_to_seq(&seq); } } pub fn sync_pcr(&mut self) { self.pcr = PcrParams::new(&self.ui.pcr); } /// Identify restriction enzyme sites in the sequence. pub fn sync_re_sites(&mut self) { if self.active >= self.volatile.len() { eprintln!("Error: Volatile len too short for RE sync."); return; } self.volatile[self.active].restriction_enzyme_matches = Vec::new(); self.volatile[self.active] .restriction_enzyme_matches .append(&mut find_re_matches( &self.generic[self.active].seq, &self.restriction_enzyme_lib, )); // This sorting aids in our up/down label alternation in the display. self.volatile[self.active] .restriction_enzyme_matches .sort_by(|a, b| a.seq_index.cmp(&b.seq_index)); } pub fn sync_reading_frame(&mut self) { self.volatile[self.active].reading_frame_matches = find_orf_matches(self.get_seq(), self.reading_frame); } pub fn sync_search(&mut self) { if self.search_seq.len() >= MIN_SEARCH_LEN { self.volatile[self.active].search_matches = find_search_matches(self.get_seq(), &self.search_seq); } else { self.volatile[self.active].search_matches = Vec::new(); } } pub fn sync_portions(&mut self) { for sol in &mut self.portions[self.active].solutions { sol.calc_amounts(); } } pub fn sync_primer_metrics(&mut self) { for primer in &mut self.generic[self.active].primers { // primer.run_calcs(&self.ion_concentration[self.active]); primer.run_calcs(&self.ion_concentrations); // // primer.volatile[self.active].sequence_input = seq_to_str(&primer.sequence); // // // if let Some(metrics) = &mut primer.volatile[self.active].metrics { // let dual_ended = match primer.volatile[self.active].tune_setting { // TuneSetting::Both(_) => true, // _ => false, // }; // // metrics.update_scores(dual_ended); // } // if primer.volatile[self.active].metrics.is_none() { // primer.run_calcs(&self.ion_concentrations); // } } } /// Upddate this sequence by inserting a sequence of interest. Shifts features based on the insert. pub fn insert_nucleotides(&mut self, insert: &[Nucleotide], insert_loc: usize) { insert_into_seq(&mut self.generic[self.active].seq, insert, insert_loc).ok(); let insert_i = insert_loc - 1; // 1-based indexing. // Now, you have to update features affected by this insertion, shifting them right A/R. for feature in &mut self.generic[self.active].features { if feature.range.start > insert_i { feature.range.start += insert.len(); } if feature.range.end > insert_i { feature.range.end += insert.len(); } } self.sync_seq_related(None); } /// One-based indexing. Similar to `insert_nucleotides`. pub fn remove_nucleotides(&mut self, range: RangeIncl) { let seq = &mut self.generic[self.active].seq; if range.end + 1 > seq.len() { return; } let count = range.len(); seq.drain(range.start..=range.end); // Now, you have to update features affected by this insertion, shifting them left A/R. for feature in &mut self.generic[self.active].features { if feature.range.start > range.end { feature.range.start -= count; } if feature.range.end > range.end { feature.range.end -= count; } } self.sync_seq_related(None); } /// Run this when the sequence changes. pub fn sync_seq_related(&mut self, primer_i: Option<usize>) { self.sync_primer_matches(primer_i); // We have removed RE sync here for now, because it is slow. Call when able. // self.sync_re_sites(); self.sync_reading_frame(); self.sync_search(); sync_cr_orf_matches(self); self.volatile[self.active].proteins = proteins_from_seq( self.get_seq(), &self.generic[self.active].features, &self.volatile[self.active].cr_orf_matches, ); self.ui.seq_input = seq_to_str_lower(self.get_seq()); } pub fn reset_selections(&mut self) { self.ui.text_selection = None; self.ui.selected_item = Selection::None; } /// Load a single tab from file. pub fn load(&mut self, loaded: &StateToSave) { let gen_ = &self.generic[self.active]; // Check if the current tab is a new file. If so, don't add a new tab. if !gen_.seq.is_empty() || !gen_.features.is_empty() || !gen_.primers.is_empty() || !self.portions[self.active].solutions.is_empty() || !self.ab1_data[self.active].sequence.is_empty() { self.add_tab(); self.tabs_open.push(Default::default()); } // todo: Fix this for AB1 loading. let ab1 = !loaded.ab1_data.sequence.is_empty(); let tab = Tab { path: loaded.path_loaded.clone(), ab1, }; self.generic[self.active].clone_from(&loaded.generic); // self.ion_concentrations[self.active].clone_from(&loaded.ion_concentrations); self.portions[self.active].clone_from(&loaded.portions); self.ab1_data[self.active].clone_from(&loaded.ab1_data); self.tabs_open[self.active] = tab; self.volatile[self.active] = Default::default(); self.sync_pcr(); self.sync_primer_metrics(); self.sync_seq_related(None); self.sync_re_sites(); self.ui.seq_input = seq_to_str_lower(self.get_seq()); self.sync_portions(); self.reset_selections(); // So these tabs opens on a new program run. self.update_save_prefs(); // Save opened tabs. } /// Copy the sequence of the selected text selection, feature or primer to the clipboard, if applicable. pub fn copy_seq(&self) { // Text selection takes priority. if let Some(selection) = &self.ui.text_selection { if let Some(seq) = selection.index_seq(self.get_seq()) { let mut ctx = ClipboardContext::new().unwrap(); ctx.set_contents(seq_to_str_lower(seq)).unwrap(); } return; } match self.ui.selected_item { Selection::Feature(i) => { if i >= self.generic[self.active].features.len() { eprintln!("Invalid feature in selection"); return; } let feature = &self.generic[self.active].features[i]; if let Some(seq) = feature.range.index_seq(self.get_seq()) { let mut ctx = ClipboardContext::new().unwrap(); ctx.set_contents(seq_to_str_lower(seq)).unwrap(); } } Selection::Primer(i) => { let primer = &self.generic[self.active].primers[i]; let mut ctx = ClipboardContext::new().unwrap(); ctx.set_contents(seq_to_str_lower(&primer.sequence)) .unwrap(); } _ => (), } } } /// This struct contains state that does not need to persist between sessesions or saves, but is not /// a good fit for `StateUi`. This is, generally, calculated data from persistent staet. #[derive(Default)] pub struct StateVolatile { pub restriction_enzyme_matches: Vec<ReMatch>, pub re_digestion_products: Vec<LigationFragment>, pub reading_frame_matches: Vec<ReadingFrameMatch>, pub tag_matches: Vec<TagMatch>, pub search_matches: Vec<SearchMatch>, /// Used for automatically determining which reading frame to use, and the full frame, /// for a given coding-region feature. pub cr_orf_matches: Vec<(usize, ReadingFrameMatch)>, pub proteins: Vec<Protein>, }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/primer.rs
src/primer.rs
//! This module contains code related to primer (oglionucleotide) design and QC. use bincode::{Decode, Encode}; use eframe::egui::Color32; use na_seq::{Nucleotide, Seq, seq_complement, seq_from_str, seq_to_str_lower, seq_weight}; use crate::{ gui::{PRIMER_FWD_COLOR, PRIMER_REV_COLOR, primer_table::DEFAULT_TRIM_AMT}, primer_metrics::PrimerMetrics, state::State, util::{RangeIncl, match_subseq}, }; // If a primer length is below this, many calculations will be disabled for it. pub const MIN_PRIMER_LEN: usize = 10; pub const TM_TARGET: f32 = 59.; // Also used as a default for PCR GUI. // These lenghts should be long enough for reasonablely high-length primers, should that be // required for optimal characteristics. const UNTRIMMED_LEN_INSERT: usize = 30; const UNTRIMMED_LEN_VECTOR: usize = 32; // todo: Sort out your types. #[derive(Clone, Debug, Encode, Decode)] pub struct PrimerMatch { pub direction: PrimerDirection, /// This range is in the forward direction for both primers. pub range: RangeIncl, } /// These are also relevant for FastCloning. pub struct SlicPrimers { pub vector_fwd: Primer, pub vector_rev: Primer, pub insert_fwd: Primer, pub insert_rev: Primer, } /// These are also relevant for FastCloning. pub struct AmplificationPrimers { pub fwd: Primer, pub rev: Primer, } #[derive(Clone, Copy, Debug, PartialEq, Encode, Decode)] pub enum PrimerDirection { Forward, Reverse, } impl PrimerDirection { pub fn color(&self) -> Color32 { match self { Self::Forward => PRIMER_FWD_COLOR, Self::Reverse => PRIMER_REV_COLOR, } } } #[derive(Default, Clone, Encode, Decode)] pub struct Primer { pub sequence: Seq, pub name: String, pub description: Option<String>, // todo: Display this. /// Data that is dynamically regenerated, and generally not important for saving and loading to files. pub volatile: PrimerData, } impl Primer { /// Match this primer to a sequence. Check both directions. /// Returns direction, and start and end indexes of the sequence. If direction is reversed, /// the indexs matches to the reversed index. pub fn match_to_seq(&self, seq: &[Nucleotide]) -> Vec<PrimerMatch> { let mut result = Vec::new(); // This check prevents spurious small-sequence matches, which may be numerous otherwise. if self.sequence.len() < MIN_PRIMER_LEN { return result; } let (matches_fwd, matches_rev) = match_subseq(&self.sequence, seq); for range in matches_fwd { result.push(PrimerMatch { direction: PrimerDirection::Forward, range, }); } for range in matches_rev { result.push(PrimerMatch { direction: PrimerDirection::Reverse, range, }); } result } /// Formats the indexes, and size of this feature. pub fn location_descrip(&self) -> String { self.volatile .matches .iter() .map(|match_| format!("{}..{}", match_.range.start, match_.range.end)) .collect::<Vec<String>>() .join("; ") } /// Automatically select primer length based on quality score. pub fn tune(&mut self, ion: &IonConcentrations) { match self.volatile.tune_setting { TuneSetting::Both(_) => self.tune_both_ends(ion), TuneSetting::Disabled => (), _ => self.tune_single_end(ion), } } /// Note: In its current form, this assumes only one end is tunable, prior to calling this function. fn tune_single_end(&mut self, ion: &IonConcentrations) { // todo: Using the seq_input as the only way we store total len feels janky. let len_untrimmed = self.volatile.sequence_input.len(); if len_untrimmed <= MIN_PRIMER_LEN { return; } let mut best_val = 0; let mut best_score = 0.; let num_vals = len_untrimmed - MIN_PRIMER_LEN; // When this function is called, exactly one of these ends must be enabled. // let (i) = match &mut self.volatile.tune_setting { // TuneSetting::Only5(v) => v, // TuneSetting::Only3(v) => v, // _ => return, // }; for val in 0..num_vals { // We need to have this assignment in the loop to prevent borrow errors. let i = match &mut self.volatile.tune_setting { TuneSetting::Only5(v) => v, TuneSetting::Only3(v) => v, _ => return, }; *i = val; self.run_calcs(ion); if let Some(metrics) = &self.volatile.metrics { if metrics.quality_score > best_score { best_val = val; best_score = metrics.quality_score; } } } let i = match &mut self.volatile.tune_setting { TuneSetting::Only5(v) => v, TuneSetting::Only3(v) => v, _ => return, }; *i = best_val; self.run_calcs(ion); } fn tune_both_ends(&mut self, ion: &IonConcentrations) { // todo: Using the seq_input as the only way we store total len feels janky. let len_untrimmed = self.volatile.sequence_input.len(); // We need the min primer length on both sides of the anchor. if len_untrimmed <= MIN_PRIMER_LEN * 2 { return; } let mut best_val = (0, 0); let mut best_score = 0.; // As for single-ended, we assume this function only runs when both ends are marked tunable. let (anchor, _, _) = match self.volatile.tune_setting { TuneSetting::Both(v) => v, _ => return, }; // We ensure we have the min primer len on either side of the anchor. let num_vals_5p = if anchor < MIN_PRIMER_LEN { 0 } else { anchor - MIN_PRIMER_LEN }; let num_vals_3p = if anchor < MIN_PRIMER_LEN { 0 } else { if len_untrimmed > anchor { let lhs = len_untrimmed - anchor; if lhs > MIN_PRIMER_LEN { (len_untrimmed - anchor) - MIN_PRIMER_LEN } else { 0 } } else { 0 } }; // A nested loop: Try all combinations. for val5 in 0..num_vals_5p { for val3 in 0..num_vals_3p { // As for single-ended, we assume this function only runs when both ends are marked tunable. let (_, i_5p, i_3p) = match &mut self.volatile.tune_setting { TuneSetting::Both(v) => v, _ => return, }; *i_5p = val5; *i_3p = val3; self.run_calcs(ion); if let Some(metrics) = &self.volatile.metrics { if metrics.quality_score > best_score { best_val = (val5, val3); best_score = metrics.quality_score; } } } } let (_, i_5p, i_3p) = match &mut self.volatile.tune_setting { TuneSetting::Both(v) => v, _ => return, }; *i_5p = best_val.0; *i_3p = best_val.1; self.run_calcs(ion); } /// Perform calculations on primer quality and related data. Run this when the sequence changes, /// the tuning values change etc. /// /// This also syncs the active sequence based on the tune settings, and calculates primer weight. pub fn run_calcs(&mut self, ion_concentrations: &IonConcentrations) { self.volatile.weight = seq_weight(&self.sequence); let full_len = self.volatile.sequence_input.len(); let mut start = 0; let mut end = full_len; // if let TuneSetting::Enabled(i) = self.volatile.tunable_5p { if let Some(i) = self.volatile.tune_setting.val_5p_mut() { start = *i; } // if let TuneSetting::Enabled(i) = self.volatile.tunable_3p { if let Some(i) = self.volatile.tune_setting.val_3p_mut() { end = if *i > full_len { // Prevents an overrun. 0 } else { full_len - *i }; } if start > end || start + 1 > self.volatile.sequence_input.len() { start = 0; end = full_len } self.sequence = seq_from_str(&self.volatile.sequence_input[start..end]); self.volatile.metrics = self.calc_metrics(ion_concentrations); self.volatile.sequence_input[..start].clone_into(&mut self.volatile.seq_removed_5p); self.volatile.sequence_input[end..].clone_into(&mut self.volatile.seq_removed_3p); } } pub fn design_slic_fc_primers( seq_vector: &Seq, seq_insert: &Seq, mut insert_loc: usize, ) -> Option<SlicPrimers> { if insert_loc == 0 { eprintln!("Error when making SLIC primers: Insert loc is 0"); return None; } let seq_len_vector = seq_vector.len(); let seq_len_insert = seq_insert.len(); // todo: This likely doesn't handle the off-by-one dynamic. insert_loc = insert_loc % seq_len_vector; // Wrap around the origin (circular plasmids) let vector_reversed = seq_complement(seq_vector); let insert_reversed = seq_complement(seq_insert); let insert_loc_reversed = seq_len_vector - insert_loc + 1; let (seq_vector_fwd, seq_vector_rev) = { let end = (insert_loc + UNTRIMMED_LEN_VECTOR) % seq_len_vector; let end_reversed = (insert_loc_reversed + UNTRIMMED_LEN_VECTOR) % seq_len_vector; ( seq_vector[insert_loc - 1..end].to_owned(), vector_reversed[insert_loc_reversed..end_reversed].to_owned(), ) }; let (seq_insert_fwd, seq_insert_rev) = { let mut insert_end = UNTRIMMED_LEN_INSERT; insert_end = insert_end.clamp(0, seq_len_insert); let mut insert_end_reversed = UNTRIMMED_LEN_INSERT; insert_end_reversed = insert_end_reversed.clamp(0, seq_len_insert); // We will combine these with vector seqs for the final insert primers. let insert_only_seq_fwd = &seq_insert[..insert_end]; let insert_only_seq_rev = &insert_reversed[..insert_end_reversed]; let mut fwd = seq_complement(&seq_vector_rev); fwd.extend(insert_only_seq_fwd); let mut rev = seq_complement(&seq_vector_fwd); rev.extend(insert_only_seq_rev); (fwd, rev) }; // We tune downstream. Some(SlicPrimers { vector_fwd: Primer { sequence: seq_vector_fwd, name: "Vector fwd".to_owned(), description: Some( "SLIC cloning primer, Vector forward. Amplifies the entire vector.".to_owned(), ), volatile: Default::default(), }, vector_rev: Primer { sequence: seq_vector_rev, name: "Vector rev".to_owned(), description: Some( "SLIC cloning primer, Vector reverse. Amplifies the entire vector.".to_owned(), ), volatile: Default::default(), }, insert_fwd: Primer { sequence: seq_insert_fwd, name: "Insert fwd".to_owned(), description: Some( "SLIC cloning primer, Insert forward. Overlaps with the vector.".to_owned(), ), volatile: Default::default(), }, insert_rev: Primer { sequence: seq_insert_rev, name: "Insert rev".to_owned(), description: Some( "SLIC cloning primer, Insert forward. Overlaps with the vector.".to_owned(), ), volatile: Default::default(), }, }) } // todo: Use this A/R, called from the UI page. pub fn design_amplification_primers(seq: &[Nucleotide]) -> Option<AmplificationPrimers> { // These lenghts should be long enough for reasonablely high-length primers, should that be // required for optimal characteristics. const UNTRIMMED_LEN: usize = 32; let seq_len = seq.len(); let reversed = seq_complement(seq); let (seq_fwd, seq_rev) = { let mut end = UNTRIMMED_LEN; end = end.clamp(0, seq_len); let mut end_reversed = UNTRIMMED_LEN; end_reversed = end_reversed.clamp(0, seq_len); (seq[..end].to_owned(), reversed[..end_reversed].to_owned()) }; // We tune downstream. Some(AmplificationPrimers { fwd: Primer { sequence: seq_fwd, name: "Amplification fwd".to_owned(), description: Some("Amplification primer, forward.".to_owned()), volatile: Default::default(), }, rev: Primer { sequence: seq_rev, name: "Amplification rev".to_owned(), description: Some("Amplification primer, reverse.".to_owned()), volatile: Default::default(), }, }) } #[derive(Default, Clone, Encode, Decode)] pub struct PrimerData { /// Editing is handled using this string; we convert the string to our nucleotide sequence as needed. /// This includes nts past the tuning offsets. pub sequence_input: String, pub metrics: Option<PrimerMetrics>, // tunable_end: TunableEnd, /// These fields control if a given primer end is fixed (Eg marking the start of an insert, /// marking the insert point in a vector etc) or if we can tune its length to optimize the primer. pub tune_setting: TuneSetting, /// These seq_removed fields are redundant with primer and tune settings. We use them to cache /// the actual sequences that are removed for display purposes. pub seq_removed_5p: String, pub seq_removed_3p: String, /// todo: Which direction is the range, if the direction is reverse? pub matches: Vec<PrimerMatch>, /// Primer weight, in Daltons. pub weight: f32, } impl PrimerData { pub fn new(seq: &[Nucleotide]) -> Self { let mut result = Self::default(); result.sequence_input = seq_to_str_lower(seq); result } } // #[derive(Clone, Copy, PartialEq, Debug, Encode, Decode)] // pub enum TuneSetting { // Disabled, // /// Inner: Offset index; this marks the distance from the respective ends that the sequence is attentuated to. // Enabled(usize), // } #[derive(Clone, Copy, PartialEq, Debug, Encode, Decode)] pub enum TuneSetting { /// Inner: Offset index; this marks the distance from the respective ends that the sequence is attentuated to. /// The 3' end is the anchor. Only5(usize), /// The 5' end is the anchor. Only3(usize), /// There is a central anchor, and both ends are tuanble. We use this for the insert primers of /// SLIC and FC. Both((usize, usize, usize)), // (Anchor from 5', 5p, 3p) Disabled, // Enabled(usize), } impl Default for TuneSetting { fn default() -> Self { Self::Disabled } } impl TuneSetting { pub fn toggle_5p(&mut self) { *self = match self { Self::Only5(_) => Self::Disabled, Self::Only3(_) => Self::Both((0, 10, 0)), // todo: 20? Hmm. Self::Both(_) => Self::Only3(0), Self::Disabled => Self::Only5(0), } } pub fn toggle_3p(&mut self) { *self = match self { Self::Only3(_) => Self::Disabled, Self::Only5(_) => Self::Both((0, 10, 0)), // todo: 20? Hmm. Self::Both(_) => Self::Only5(0), Self::Disabled => Self::Only3(0), } } /// If the 5p end is tunable, get its valu. pub fn val_5p(&self) -> Option<usize> { match self { Self::Only5(v) => Some(*v), Self::Both(v) => Some(v.1), _ => None, } } /// If the 5p end is tunable, get its value. pub fn val_3p(&self) -> Option<usize> { match self { Self::Only3(v) => Some(*v), Self::Both(v) => Some(v.2), _ => None, } } /// If the 5p end is tunable, get its value, mutably. pub fn val_5p_mut(&mut self) -> Option<&mut usize> { match self { Self::Only5(v) => Some(v), Self::Both(v) => Some(&mut v.1), _ => None, } } /// If the 5p end is tunable, get its value, mutably. pub fn val_3p_mut(&mut self) -> Option<&mut usize> { match self { Self::Only3(v) => Some(v), Self::Both(v) => Some(&mut v.2), _ => None, } } pub fn tunable(&self) -> bool { !matches!(self, Self::Disabled) } } /// We run this to generate cloning primers when clicking the button /// Make sure to do this before inserting the insert into the sequence. pub fn make_cloning_primers(state: &mut State) { let seq_vector = &state.generic[state.active].seq; let seq_insert = &state.ui.cloning_insert.seq_insert; if let Some(mut primers) = design_slic_fc_primers(seq_vector, seq_insert, state.cloning.insert_loc) { let sequence_input = seq_to_str_lower(&primers.insert_fwd.sequence); let insert_fwd_data = PrimerData { sequence_input, // Both ends are tunable, since this glues the insert to the vector tune_setting: TuneSetting::Both(( UNTRIMMED_LEN_INSERT, DEFAULT_TRIM_AMT, DEFAULT_TRIM_AMT, )), // todo: TIe the anchor to the const ..Default::default() }; let sequence_input = seq_to_str_lower(&primers.insert_rev.sequence); let insert_rev_data = PrimerData { sequence_input, // Both ends are tunable, since this glues the insert to the vector tune_setting: TuneSetting::Both(( UNTRIMMED_LEN_VECTOR, DEFAULT_TRIM_AMT, DEFAULT_TRIM_AMT, )), // todo: QC ..Default::default() }; let sequence_input = seq_to_str_lower(&primers.vector_fwd.sequence); let vector_fwd_data = PrimerData { sequence_input, // 5' is non-tunable: This is the insert location. tune_setting: TuneSetting::Only3(DEFAULT_TRIM_AMT), ..Default::default() }; let sequence_input = seq_to_str_lower(&primers.vector_rev.sequence); let vector_rev_data = PrimerData { sequence_input, // tunable_5p: TuneSetting::Disabled, // 3' is non-tunable: This is the insert location. tune_setting: TuneSetting::Only3(DEFAULT_TRIM_AMT), // todo: Which one?? // tunable_3p: TuneSetting::Enabled(DEFAULT_TRIM_AMT), ..Default::default() }; primers.insert_fwd.volatile = insert_fwd_data; primers.insert_rev.volatile = insert_rev_data; primers.vector_fwd.volatile = vector_fwd_data; primers.vector_rev.volatile = vector_rev_data; // Note: If we don't run `run_calcs` before tune here, we get unexpected beavhior culminating // in a crash after attempting to tune primers. This is likely related to syncing the tuned-out // part of the primers. primers .insert_fwd // .run_calcs(&state.ion_concentrations[state.active]); .run_calcs(&state.ion_concentrations); primers .insert_rev // .run_calcs(&state.ion_concentrations[state.active]); .run_calcs(&state.ion_concentrations); primers .vector_fwd // .run_calcs(&state.ion_concentrations[state.active]); .run_calcs(&state.ion_concentrations); primers .vector_rev // .run_calcs(&state.ion_concentrations[state.active]); .run_calcs(&state.ion_concentrations); primers .insert_fwd // .tune(&state.ion_concentrations[state.active]); .tune(&state.ion_concentrations); primers .insert_rev // .tune(&state.ion_concentrations[state.active]); .tune(&state.ion_concentrations); primers .vector_fwd // .tune(&state.ion_concentrations[state.active]); .tune(&state.ion_concentrations); primers .vector_rev // .tune(&state.ion_concentrations[state.active]); .tune(&state.ion_concentrations); state.generic[state.active].primers.extend([ primers.insert_fwd, primers.insert_rev, primers.vector_fwd, primers.vector_rev, ]); state.sync_primer_matches(None); } } pub fn make_amplification_primers(state: &mut State) { if let Some(mut primers) = design_amplification_primers(state.get_seq()) { let sequence_input = seq_to_str_lower(&primers.fwd.sequence); let primer_fwd_data = PrimerData { sequence_input, tune_setting: TuneSetting::Only3(DEFAULT_TRIM_AMT), // tunable_5p: TuneSetting::Disabled, // tunable_3p: TuneSetting::Enabled(DEFAULT_TRIM_AMT), ..Default::default() }; let sequence_input = seq_to_str_lower(&primers.rev.sequence); let primer_rev_data = PrimerData { sequence_input, tune_setting: TuneSetting::Only3(DEFAULT_TRIM_AMT), // tunable_5p: TuneSetting::Disabled, // tunable_3p: TuneSetting::Enabled(DEFAULT_TRIM_AMT), ..Default::default() }; primers.fwd.volatile = primer_fwd_data; primers.rev.volatile = primer_rev_data; // primers.fwd.tune(&state.ion_concentrations[state.active]); primers.fwd.tune(&state.ion_concentrations); // primers.rev.tune(&state.ion_concentrations[state.active]); primers.rev.tune(&state.ion_concentrations); state.generic[state.active] .primers .extend([primers.fwd, primers.rev]); state.sync_primer_matches(None); // note: Not requried to run on all primers. } } #[derive(Clone, Encode, Decode)] /// Concentrations of common ions in the oglio solution. Affects melting temperature (TM). /// All values are in milliMolar. pub struct IonConcentrations { /// Na+ or K+ pub monovalent: f32, /// Mg2+ pub divalent: f32, pub dntp: f32, /// Primer concentration, in nM. pub primer: f32, } impl Default for IonConcentrations { fn default() -> Self { // todo: Adjust A/R Self { monovalent: 50., divalent: 1.5, dntp: 0.2, primer: 25., } } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/protein.rs
src/protein.rs
//! Data related to proteins, eg derived from coding region features, in conjunction with //! reading frames. use bincode::{Decode, Encode}; use bio_apis::rcsb::PdbData; use na_seq::{ Nucleotide, amino_acids::{AminoAcid, CodingResult, hydropathy_doolittle}, }; use crate::{ misc_types::{Feature, FeatureType}, reading_frame::{ReadingFrame, ReadingFrameMatch, find_orf_matches}, state::State, }; pub const WATER_WEIGHT: f32 = 18.015; // g/mol. We subtract these when calculating a protein's weight. // todo: Adjust A/R. Ideally, let the user customize it. pub const HYDROPATHY_WINDOW_SIZE: usize = 9; #[derive(Encode, Decode)] pub struct Protein { pub feature: Feature, // todo: Consider how you want to do this. Index? Only used for creation? pub reading_frame_match: ReadingFrameMatch, pub aa_seq: Vec<AminoAcid>, pub aa_seq_precoding: Vec<AminoAcid>, pub aa_seq_postcoding: Vec<AminoAcid>, pub weight: f32, pub weight_with_prepost: f32, // window center, value. /// This type is for storing graphable data used by egui_plot. // pub hydropath_data: Vec<[f64; 2]>, pub hydropath_data: Vec<(usize, f32)>, pub pdb_data: Vec<PdbData>, // Note: This is more of a UI functionality; here for now. pub show_hydropath: bool, } pub fn proteins_from_seq( seq: &[Nucleotide], features: &[Feature], cr_orf_matches: &[(usize, ReadingFrameMatch)], ) -> Vec<Protein> { let mut result = Vec::new(); for (i, feature) in features.iter().enumerate() { if feature.feature_type != FeatureType::CodingRegion { continue; } for (j, om) in cr_orf_matches { if *j == i { if let Some(seq_orf_match_dna) = om.range.index_seq(seq) { // todo: DRy with feature_db_load. let len = seq_orf_match_dna.len(); let mut aa_seq = Vec::new(); // We also render AAs included in the reading frame, but not specified in the coding region feature. let mut aa_seq_precoding = Vec::new(); let mut aa_seq_postcoding = Vec::new(); for i_ in 0..len / 3 { let i = i_ * 3; // The ORF-modified sequence index. let i_actual = i + om.range.start; let nts = &seq_orf_match_dna[i..i + 3]; // Note: We are ignoring stop codons here. if let CodingResult::AminoAcid(aa) = CodingResult::from_codons(nts.try_into().unwrap()) { if i_actual < feature.range.start { aa_seq_precoding.push(aa); } else if i_actual > feature.range.end { aa_seq_postcoding.push(aa); } else { aa_seq.push(aa); } } } // todo: Def cache these weights. let weight = protein_weight(&aa_seq); let weight_with_prepost = weight + protein_weight(&aa_seq_precoding) + protein_weight(&aa_seq_postcoding); let hydropath_data = hydropathy_doolittle(&aa_seq, HYDROPATHY_WINDOW_SIZE); // Convert to a format accepted by our plotting lib. // let mut hydropath_data = Vec::new(); // for (i, val) in hydropath_data_ { // hydropath_data.push([i as f64, val as f64]); // } result.push(Protein { feature: feature.clone(), reading_frame_match: om.clone(), aa_seq, aa_seq_precoding, aa_seq_postcoding, hydropath_data, weight, weight_with_prepost, show_hydropath: true, pdb_data: Vec::new(), }) } } } } result } /// The TANGO algorithm predicts beta-sheet formation propensity, which is associated with aggregation. /// It considers factors like amino acid sequence, solvent accessibility, and secondary structure. pub fn tango_aggregation(seq: &[AminoAcid]) {} /// Predicts aggregation-prone regionis by calculating an aggregation score for each AA. /// todo: Look this up. pub fn aggrescan(seq: &[AminoAcid]) {} // todo: Look up SLIDER aggregation tool as well. // todo: Visualize hydrophobic and aggreg-prone regions. // todo: Move this somewhere more appropriate, then store in state_volatile. /// Find the most likely reading frame for each coding region. pub fn sync_cr_orf_matches(state: &mut State) { state.volatile[state.active].cr_orf_matches = Vec::new(); // These matches are for all frames. let mut region_matches = Vec::new(); for orf in [ ReadingFrame::Fwd0, ReadingFrame::Fwd1, ReadingFrame::Fwd2, ReadingFrame::Rev0, ReadingFrame::Rev1, ReadingFrame::Rev2, ] { let mut regions = find_orf_matches(state.get_seq(), orf); region_matches.append(&mut regions); } for (i, feature) in state.generic[state.active].features.iter().enumerate() { if feature.feature_type != FeatureType::CodingRegion { continue; } // Don't show binding tags. let label_lower = feature.label.to_lowercase().replace(' ', ""); if label_lower.contains("xhis") || label_lower.contains("×his") { continue; } // Find the best reading frame match, if there is one. let mut orf_match = None; let mut smallest_match = usize::MAX; for rm in &region_matches { if !rm.range.contains(feature.range.start) || !rm.range.contains(feature.range.end) { continue; } // If multiple matches contain the range, choose the smallest one. if rm.range.len() < smallest_match { smallest_match = rm.range.len(); orf_match = Some(rm.clone()); } } if let Some(m) = orf_match { state.volatile[state.active] .cr_orf_matches .push((i, m.clone())); } } } /// calculate protein weight in kDa. pub fn protein_weight(seq: &[AminoAcid]) -> f32 { if seq.is_empty() { return 0.; // Avoids underflow. } let mut result = 0.; for aa in seq { result += aa.weight(); } (result - WATER_WEIGHT * (seq.len() - 1) as f32) / 1_000. }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/util.rs
src/util.rs
use std::{cmp::min, collections::HashSet, fmt, io, io::ErrorKind, path::Path}; use bincode::{Decode, Encode}; use eframe::egui::{Pos2, pos2}; use na_seq::{ Nucleotide, ligation::{filter_multiple_seqs, filter_unique_cutters, find_common_res}, restriction_enzyme::RestrictionEnzyme, seq_complement, }; use crate::{ Color, ReUi, file_io::save::QUICKSAVE_FILE, gui::{ WINDOW_TITLE, sequence::seq_view::{NT_WIDTH_PX, SEQ_ROW_SPACING_PX, TEXT_X_START, TEXT_Y_START}, }, misc_types::Feature, state::{State, StateVolatile}, }; const FEATURE_ANNOTATION_MATCH_THRESH: f32 = 0.95; /// A replacement for std::RangeInclusive, but copy type, and directly-accessible (mutable) fields. /// An official replacement is eventually coming, but not for a while likely. #[derive(Clone, Copy, Debug, PartialEq, Encode, Decode)] pub struct RangeIncl { pub start: usize, pub end: usize, } impl RangeIncl { pub fn new(start: usize, end: usize) -> Self { Self { start, end } } pub fn contains(&self, val: usize) -> bool { val >= self.start && val <= self.end } /// This function handles both the +1 nature of our range indexing, /// and error handling for out of bounds. (The latter of which panics at runtime) pub fn index_seq<'a, T: Clone>(&self, seq: &'a [T]) -> Option<&'a [T]> { // todo: If end > len, wrap, and handle as circular. // if self.start < 1 || self.end > seq.len() { if self.start < 1 || self.end > seq.len() || self.start > self.end { return None; } // todo: This unfortunately doesn't work due to borrow rules. // We assume a circular sequence, for now. todo: Add as a parameter. // if self.start > self.end { // let part1 = &seq[self.start - 1..]; // let part2 = &seq[..self.end - 1]; // Some(&[part1, part2].concat()) // } else { // Some(&seq[self.start - 1..=self.end - 1]) // } Some(&seq[self.start - 1..=self.end - 1]) } /// A wrap-based extension to `index_seq`. pub fn index_seq_wrap<T: Clone>(&self, seq: &[T]) -> Option<Vec<T>> { if self.start < 1 || self.end > seq.len() || self.start <= self.end { return None; } let part1 = seq[self.start - 1..].to_vec(); // Todo: Not sure why we're including the end here without -1. Using for PCR to get it to come out right. let part2 = seq[..self.end].to_vec(); let mut result = part1; result.extend(part2); Some(result) } pub fn len(&self) -> usize { if self.end < self.start { return 0; } self.end - self.start + 1 } } impl fmt::Display for RangeIncl { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}..{} {}bp", self.start, self.end, self.len()) } } /// We use this for dividing a nucleotied sequence into rows, for display in a canvas UI. /// Each range is a nucleotide index, using our 1-based system. pub fn get_row_ranges(len: usize, chars_per_row: usize) -> Vec<RangeIncl> { // todo: Round etc instead of adding 1? let num_rows = len / chars_per_row + 1; // todo: +/-1 etc? let mut result = Vec::with_capacity(num_rows); for row_i in 0..num_rows { let end = row_i * chars_per_row + chars_per_row; // let end = min(end, len + 1); let end = min(end, len); // Adjustments are per our 1-based indexing system. result.push(RangeIncl::new(row_i * chars_per_row + 1, end)); } result } // todo: We currently don't use this as a standalone fn; wrap back into `seq_i_to_pixel` a/r. /// Maps sequence index, as displayed on a manually-wrapped UI display, to row and column indices. fn seq_i_to_col_row(seq_i: usize, row_ranges: &[RangeIncl]) -> (usize, usize) { let mut row = 0; let mut row_range = RangeIncl::new(0, 10); for (row_, range) in row_ranges.iter().enumerate() { if range.contains(seq_i) { row = row_; row_range = *range; break; } } let col = seq_i - row_range.start; (col, row) } /// Maps sequence index, as displayed on a manually-wrapped UI display, to the relative pixel. pub fn seq_i_to_pixel(seq_i: usize, row_ranges: &[RangeIncl]) -> Pos2 { let (col, row) = seq_i_to_col_row(seq_i, row_ranges); // This adjustment is used for placing the cursor at position 0; prior to the first nucleotide. let col = if seq_i == 0 { -1. } else { col as f32 }; pos2( TEXT_X_START + col * NT_WIDTH_PX, TEXT_Y_START + row as f32 * SEQ_ROW_SPACING_PX, ) } pub fn pixel_to_seq_i(pixel: Pos2, row_ranges: &[RangeIncl]) -> Option<usize> { let row = ((pixel.y - TEXT_Y_START) / SEQ_ROW_SPACING_PX) as usize; let col = ((pixel.x - TEXT_X_START) / NT_WIDTH_PX) as usize; // todo: Index vice loop? for (row_, range) in row_ranges.iter().enumerate() { if row_ == row { return Some(range.start + col); } } None } // todo; Move to Util A/R pub fn remove_duplicates<T: Eq + std::hash::Hash>(vec: Vec<T>) -> Vec<T> { let set: HashSet<_> = vec.into_iter().collect(); let vec: Vec<_> = set.into_iter().collect(); vec } // /// For the sequence editor. Given an index range of a feature, return sequence ranges for each row the feature occupies, that /// contain the sequence. This, after converting to pixels, corresponds to how we draw features and primers. /// This is used to draw overlays over the sequence that line up with a given index range. pub fn get_feature_ranges( feature_rng: &RangeIncl, all_ranges: &[RangeIncl], seq_len: usize, ) -> Vec<RangeIncl> { let mut result = Vec::new(); // If the feature range wraps the origin, divide it into two ranges, and match both. let feature_ranges = if feature_rng.end < feature_rng.start { vec![ RangeIncl::new(1, feature_rng.end), RangeIncl::new(feature_rng.start, seq_len), ] } else { vec![*feature_rng] }; for ft_rng in &feature_ranges { for range in all_ranges { if range.end < range.start || range.end == 0 { eprintln!("Error with all ranges when finding a feature range: {range}"); return result; } if range.contains(ft_rng.start) { // Contains start only, or start and end. let end = min(range.end, ft_rng.end); // result.push(ft_rng.start..end - 1); result.push(RangeIncl::new(ft_rng.start, end)); } else if range.contains(ft_rng.end) { // Contains end only. result.push(RangeIncl::new(range.start, ft_rng.end)); } else if ft_rng.start < range.start && ft_rng.end > range.end { // Include this entire row result.push(RangeIncl::new(range.start, range.end)); } // If none of the above, this row doesn't contain any of the sequence of interest. } } result } pub fn color_from_hex(hex: &str) -> io::Result<Color> { let hex = &hex[1..]; // Remove the leading # if hex.len() < 6 { return Err(io::Error::new(ErrorKind::InvalidData, "Invalid color")); } let r = u8::from_str_radix(&hex[0..2], 16) .map_err(|_| io::Error::new(ErrorKind::InvalidData, "Invalid color radix"))?; let g = u8::from_str_radix(&hex[2..4], 16) .map_err(|_| io::Error::new(ErrorKind::InvalidData, "Invalid color radix"))?; let b = u8::from_str_radix(&hex[4..6], 16) .map_err(|_| io::Error::new(ErrorKind::InvalidData, "Invalid color radix"))?; Ok((r, g, b)) } pub fn color_to_hex(color: Color) -> String { format!("#{:x}{:x}{:x}", color.0, color.1, color.2) } /// Change the origin. This involves updating the sequence, and all features. pub fn change_origin(state: &mut State) { let origin = &state.ui.new_origin; // Note the 1-based indexing logic we use. if *origin < 1 || *origin > state.get_seq().len() { return; } state.generic[state.active].seq.rotate_left(origin - 1); let seq_len = state.get_seq().len(); for feature in &mut state.generic[state.active].features { // Convert to i32 to prevent an underflow on crash if we wrap. Use `rem_euclid`, // as Rust has unexpected behavior when using modulus on negatives. feature.range = RangeIncl::new( (feature.range.start as i32 + 1 - *origin as i32).rem_euclid(seq_len as i32) as usize, (feature.range.end as i32 + 1 - *origin as i32).rem_euclid(seq_len as i32) as usize, ) } // todo: What else to update? state.sync_seq_related(None); } /// Find indexes where a subsequence matches a larger one, in both directions. Can be used to match primers, /// known sequences etc. Range indicies are relative to the forward direction. /// todo: Partial matches as well. pub fn match_subseq(subseq: &[Nucleotide], seq: &[Nucleotide]) -> (Vec<RangeIncl>, Vec<RangeIncl>) { let mut result = (Vec::new(), Vec::new()); // Forward, reverse let seq_len = seq.len(); let subseq_len = subseq.len(); let complement = seq_complement(seq); for seq_start in 0..seq_len { // Note: This approach handles sequence wraps, eg [circular] plasmids. let seq_iter = seq.iter().cycle().skip(seq_start).take(subseq_len); // let seq_iter: Vec<Nucleotide> = seq.iter().cycle().skip(seq_start).take(subseq_len).map(|nt| *nt).collect(); // let similarity = seq_similarity(&seq_iter, subseq); // if similarity > FEATURE_ANNOTATION_MATCH_THRESH { // let seq_end = (seq_start + subseq_len) % seq_len; // result.0.push(RangeIncl::new(seq_start, seq_end)); // } // println!("Similarity: {:?}", similarity); if subseq.iter().eq(seq_iter) { let seq_end = (seq_start + subseq_len) % seq_len; result.0.push(RangeIncl::new(seq_start + 1, seq_end)); } } for seq_start in 0..seq_len { let seq_iter = complement.iter().cycle().skip(seq_start).take(subseq_len); // let seq_iter: Vec<Nucleotide> = complement.iter().cycle().skip(seq_start).take(subseq_len).map(|nt| *nt).collect(); // let similarity = seq_similarity(&seq_iter, subseq); // if similarity > FEATURE_ANNOTATION_MATCH_THRESH { // let seq_end = (seq_start + subseq_len) % seq_len; // result.0.push(RangeIncl::new(seq_start, seq_end)); // } // if subseq.iter().eq(seq_iter) { let seq_end = (seq_start + subseq_len) % seq_len; if seq_end < 1 { continue; } result .1 .push(RangeIncl::new(seq_len - seq_end + 1, seq_len - seq_start)); } } result } /// Find the similarity between the two sequences, on a scale of 0 to 1. Assumes same direction. /// Note: This does not have a good way of handling length mismatches. pub fn _seq_similarity(seq_a: &[Nucleotide], seq_b: &[Nucleotide]) -> f32 { // Using seq_a's len has consequences let mut matches = 0; for i in 0..seq_a.len() { if seq_a[i] == seq_b[i] { matches += 1; } } matches as f32 / seq_a.len() as f32 } /// Merge a new set into an existing one. Don't add duplicates. pub fn merge_feature_sets(existing: &mut Vec<Feature>, new: &[Feature]) { for feature_new in new { let mut exists = false; for feature_existing in &mut *existing { if feature_new.range == feature_existing.range { exists = true; } } if !exists { existing.push(feature_new.clone()); } } } // use std::env::current_exe; // use winreg::enums::HKEY_CURRENT_USER; // use winreg::RegKey; // // /// Associate file extensions in Windows. Requires the program to be run as an administrator. // fn associate_windows_file_extension() -> io::Result<()> { // let hkcu = RegKey::predef(HKEY_CURRENT_USER); // // let extension_key = hkcu.create_subkey(r"Software\Classes\.pcad")?; // extension_key.set_value("", &"pcadfile")?; // // let file_type_key = hkcu.create_subkey(r"Software\Classes\pcadfile")?; // file_type_key.set_value("", &"My PCAD File")?; // // let exe_path = current_exe()?.to_str().unwrap().to_string(); // // let command_key = hkcu.create_subkey(r"Software\Classes\pcadfile\shell\open\command")?; // command_key.set_value("", &format!("\"{}\" \"%1\"", exe_path))?; // // Ok(()) // } /// Get the title to be displayed in the windows tilebar. pub fn get_window_title(path: &Path) -> String { let filename = path .file_name() .and_then(|name| name.to_str()) .map(|name_str| name_str.to_string()) .unwrap(); if filename == QUICKSAVE_FILE { WINDOW_TITLE.to_owned() } else { filename } } /// We filter for restriction enzymes based on preferences set. We do this in several stages. /// Note that this function includes filter characteristics that inolve matches across /// multiple opened tabs (sequences). pub fn filter_res<'a>( data: &ReUi, volatile: &[StateVolatile], lib: &'a [RestrictionEnzyme], ) -> Vec<&'a RestrictionEnzyme> { let mut re_match_set = Vec::new(); // By tab for active in &data.tabs_selected { re_match_set.push(&volatile[*active].restriction_enzyme_matches); } let mut result = find_common_res(&re_match_set, lib, data.sticky_ends_only); if data.multiple_seqs { filter_multiple_seqs(&mut result, &re_match_set, lib); } // If `unique_cutters_only` is selected, each RE must be unique in each sequence. If it's two or more times in any given sequence, don't // add it. if data.unique_cutters_only { filter_unique_cutters(&mut result, &re_match_set, lib); } result }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/backbones.rs
src/backbones.rs
//! This module contains data structures and related for vector backbones, used for cloning. It also pulls data from Addgene. //! [Popular AddGene Bacterial expression backbones](https://www.addgene.org/search/catalog/plasmids/?sticky=no&q=empty+backbone&page_size=20&expression=Bacterial+Expression&requests=100%2B+requests) //! //! [AddGene Backbone page](https://www.addgene.org/collections/empty-backbones/) // todo: Add more of those. use std::{fmt, fmt::Formatter}; use na_seq::{SeqTopology, seq_complement, seq_from_str}; use strum_macros::EnumIter; // todo: Consider auto-inferring the T7 and other promoter site instead of hard-coding. use crate::{ Seq, cloning::RBS_BUFFER, file_io::GenericData, misc_types::{Feature, FeatureType}, util::RangeIncl, }; use crate::{ cloning::RBS_BUFFER_MAX, feature_db_load::find_features, primer::{ PrimerDirection::{self, *}, make_cloning_primers, }, util::merge_feature_sets, }; #[derive(Clone, Copy, PartialEq, EnumIter)] pub enum AntibioticResistance { /// Or carbenecillin Ampicillin, Kanamycin, Chloramphenicol, // todo: A/R } impl fmt::Display for AntibioticResistance { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let val = match self { Self::Ampicillin => "Ampicillin", Self::Kanamycin => "Kanamycin", Self::Chloramphenicol => "Chloramphenicol", }; write!(f, "{val}") } } #[derive(Clone, Copy, PartialEq, EnumIter)] pub enum ExpressionHost { Bacterial, Yeast, Mamallian, } impl fmt::Display for ExpressionHost { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let val = match self { Self::Bacterial => "Bacterial", Self::Yeast => "Yeast", Self::Mamallian => "Mamallian", }; write!(f, "{val}") } } #[derive(Clone, Copy, PartialEq, EnumIter)] pub enum CopyNumber { Unknown, High, Low, } impl fmt::Display for CopyNumber { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let val = match self { Self::Unknown => "Unknown", Self::High => "High", Self::Low => "Low", }; write!(f, "{val}") } } #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq, EnumIter)] pub enum ExpressionSystem { None, T7, pGex, pBad, // todo A/R } impl fmt::Display for ExpressionSystem { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let val = match self { Self::None => "None", Self::T7 => "T7", Self::pGex => "pGex", Self::pBad => "pBad", }; write!(f, "{val}") } } impl Default for ExpressionSystem { fn default() -> Self { Self::None } } #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq)] pub enum BackboneGene { Gfp, Egfp, Luciferase, /// Glutathione S-transferase Gst, SacB, } #[derive(Clone, Copy, PartialEq)] pub enum CloningTechnique { RestrictionEnzyme, Pcr, } pub struct Backbone { pub name: String, pub addgene_id: Option<u32>, pub seq: Seq, // pub features: Vec<Feature>, pub promoter: Option<RangeIncl>, pub terminator: Option<RangeIncl>, /// The ribosome bind site is generally present on expression vectors, and absent on "cloning" /// vectors. /// todo: Make rbs and promoter sub-enum variants of ExpressionSystem? pub rbs: Option<RangeIncl>, pub antibiotic_resistance: AntibioticResistance, // pub expression_hosts: Vec<ExpressionHost>, // todo: For now, bacterial for all // todo: Data on ORI and related, // todo: tags etc pub expression_system: ExpressionSystem, pub genes_included: Vec<BackboneGene>, pub copy_number: CopyNumber, /// Note: This only refers to a His tag on the vector; not the insert. pub his_tag: Option<RangeIncl>, pub seq_topology: SeqTopology, /// For expression features. pub direction: PrimerDirection, // pub kozak_sequence: i8, // todo: Important for mamallian expression /// This contains duplicated information from above, and is created at init. We use it /// to display linear sequences, and for building cloning products. pub data: GenericData, } impl Backbone { pub fn from_opened(data: &GenericData) -> Self { let direction = Forward; // todo temp let mut promoter = None; let mut terminator = None; let mut rbs = None; let mut his_tag = None; // todo: This chooses the first feature of the correct type; this may not be correct. for feature in &data.features { match feature.feature_type { FeatureType::Promoter => promoter = Some(feature.range), FeatureType::Terminator => terminator = Some(feature.range), FeatureType::RibosomeBindSite => rbs = Some(feature.range), _ => (), } // todo: Handle His tags. } let mut result = Backbone { name: data.metadata.plasmid_name.clone(), addgene_id: None, seq: data.seq.clone(), // features: data.features.clone(), promoter, terminator, rbs, antibiotic_resistance: AntibioticResistance::Ampicillin, // Unused in this application. expression_system: ExpressionSystem::None, // Unused in this application. genes_included: Vec::new(), copy_number: CopyNumber::Unknown, his_tag, seq_topology: data.topology, direction, data: Default::default(), }; result.data = result.make_generic_data(); result } /// Find the vector insertion point, using data on tags, the RBS, and other information in the backbone. /// Currently designed for expression. pub fn insert_loc(&self, technique: CloningTechnique) -> Option<usize> { match technique { CloningTechnique::RestrictionEnzyme => None, CloningTechnique::Pcr => { let mut loc = match self.rbs { Some(rbs) => { rbs.end + RBS_BUFFER - 1 // todo: Why -1 ? } None => { // todo: Consider how to do this. For now, just place it downstream of the promoter, if that's // todo present. match self.promoter { Some(p) => { p.end + RBS_BUFFER // todo: Kludge. } None => return None, } } }; // If a His tag is present, choose a location that's in-frame. match self.his_tag { Some(his) => { if his.start < loc { eprintln!("Error: His tag start is before location for {}", self.name); return None; } let mut best_primer_composite = 0.; let mut best_primer_i = loc; // Try different locations in frame with the His tag. Choose the one // that results in the best primers // todo: Apply this logic when no tag is present too. for i in loc..loc + RBS_BUFFER_MAX as usize { if (his.start - i) % 3 != 0 { continue; } // let primers = make_cloning_primers() } while (his.start - loc) % 3 != 0 { if loc == self.seq.len() - 1 { loc = 1; // Wrap around origin. } else { loc += 1; } } Some(loc) } None => Some(loc), } } } } pub fn addgene_url(&self) -> Option<String> { self.addgene_id .map(|id| format!("https://www.addgene.org/{id}/")) } /// Used for constructing new generic/baseline data. fn make_generic_data(&self) -> GenericData { let mut features = Vec::new(); if let Some(promoter) = self.promoter { features.push(Feature { range: promoter, feature_type: FeatureType::Promoter, direction: Default::default(), // todo label: "Promoter".to_string(), color_override: None, notes: vec![], }); } if let Some(rbs) = self.rbs { features.push(Feature { range: rbs, feature_type: FeatureType::RibosomeBindSite, direction: Default::default(), // todo label: "RBS".to_string(), color_override: None, notes: vec![], }); } if let Some(his) = self.his_tag { features.push(Feature { range: his, feature_type: FeatureType::CodingRegion, direction: Default::default(), // todo label: "His tag".to_string(), color_override: None, notes: vec![], }) } // Note: We have likely duplicates between the annotation above, and this auto-annotation. let features_annotated = find_features(&self.seq); merge_feature_sets(&mut features, &features_annotated); GenericData { seq: self.seq.clone(), topology: self.seq_topology, // todo: You may need to pass features as a param, or store them with the backbone fields directly, // todo to support fields we don't enforce or use. // todo: Ie, we should include Ori, AB resistance etc. features, primers: Vec::new(), metadata: Default::default(), // todo: A/R } } } #[derive(Default)] pub struct BackboneFilters { pub host: Option<ExpressionHost>, pub antibiotic_resistance: Option<AntibioticResistance>, pub expression_system: Option<ExpressionSystem>, pub copy_number: Option<CopyNumber>, pub his_tagged: bool, } impl<'a> BackboneFilters { pub fn apply(&self, backbones: &'a [Backbone]) -> Vec<&'a Backbone> { let mut result = Vec::new(); for bb in backbones { // todo: A/R if let Some(host) = self.host {} if let Some(es) = self.expression_system { if es != bb.expression_system { continue; } } if let Some(es) = self.antibiotic_resistance { if es != bb.antibiotic_resistance { continue; } } if let Some(cn) = self.copy_number { if cn != bb.copy_number { continue; } } if self.his_tagged && !bb.his_tag.is_some() { continue; } result.push(bb); } result } } /// Load this at program init. pub fn load_backbone_library() -> Vec<Backbone> { // Mut to populate data below. let mut result = vec![ Backbone { name: "pET His6 LIC cloning vector (2Bc-T)".to_owned(), addgene_id: Some(37_236), seq: seq_from_str( "ttcttgaagacgaaagggcctcgtgatacgcctatttttataggttaatgtcatgataataatggtttcttagacgtcaggtggcacttttcggggaaatgtgcgcggaacccctatttgtttatttttctaaatacattcaaatatgtatccgctcatgagacaataaccctgataaatgcttcaataacattgaaaaaggaagagtatgagtattcaacatttccgtgtcgcccttattcccttttttgcggcattttgccttcctgtttttgctcacccagaaacgctggtgaaagtaaaagatgctgaagatcagttgggtgcacgagtgggttacatcgaactggatctcaacagcggtaagatccttgagagttttcgccccgaagaacgttttccaatgatgagcacttttaaagttctgctatgtggcgcggtattatcccgtgttgacgccgggcaagagcaactcggtcgccgcatacactattctcagaatgacttggttgagtactcaccagtcacagaaaagcatcttacggatggcatgacagtaagagaattatgcagtgctgccataaccatgagtgataacactgcggccaacttacttctgacaacgatcggaggaccgaaggagctaaccgcttttttgcacaacatgggggatcatgtaactcgccttgatcgttgggaaccggagctgaatgaagccataccaaacgacgagcgtgacaccacgatgcctgcagcaatggcaacaacgttgcgcaaactattaactggcgaactacttactctagcttcccggcaacaattaatagactggatggaggcggataaagttgcaggaccacttctgcgctcggcccttccggctggctggtttattgctgataaatctggagccggtgagcgtgggtctcgcggtatcattgcagcactggggccagatggtaagccctcccgtatcgtagttatctacacgacggggagtcaggcaactatggatgaacgaaatagacagatcgctgagataggtgcctcactgattaagcattggtaactgtcagaccaagtttactcatatatactttagattgatttaaaacttcatttttaatttaaaaggatctaggtgaagatcctttttgataatctcatgaccaaaatcccttaacgtgagttttcgttccactgagcgtcagaccccgtagaaaagatcaaaggatcttcttgagatcctttttttctgcgcgtaatctgctgcttgcaaacaaaaaaaccaccgctaccagcggtggtttgtttgccggatcaagagctaccaactctttttccgaaggtaactggcttcagcagagcgcagataccaaatactgtccttctagtgtagccgtagttaggccaccacttcaagaactctgtagcaccgcctacatacctcgctctgctaatcctgttaccagtggctgctgccagtggcgataagtcgtgtcttaccgggttggactcaagacgatagttaccggataaggcgcagcggtcgggctgaacggggggttcgtgcacacagcccagcttggagcgaacgacctacaccgaactgagatacctacagcgtgagctatgagaaagcgccacgcttcccgaagggagaaaggcggacaggtatccggtaagcggcagggtcggaacaggagagcgcacgagggagcttccagggggaaacgcctggtatctttatagtcctgtcgggtttcgccacctctgacttgagcgtcgatttttgtgatgctcgtcaggggggcggagcctatggaaaaacgccagcaacgcggcctttttacggttcctggccttttgctggccttttgctcacatgttctttcctgcgttatcccctgattctgtggataaccgtattaccgcctttgagtgagctgataccgctcgccgcagccgaacgaccgagcgcagcgagtcagtgagcgaggaagcggaagagcgcctgatgcggtattttctccttacgcatctgtgcggtatttcacaccgcatatatggtgcactctcagtacaatctgctctgatgccgcatagttaagccagtatacactccgctatcgctacgtgactgggtcatggctgcgccccgacacccgccaacacccgctgacgcgccctgacgggcttgtctgctcccggcatccgcttacagacaagctgtgaccgtctccgggagctgcatgtgtcagaggttttcaccgtcatcaccgaaacgcgcgaggcagctgcggtaaagctcatcagcgtggtcgtgaagcgattcacagatgtctgcctgttcatccgcgtccagctcgttgagtttctccagaagcgttaatgtctggcttctgataaagcgggccatgttaagggcggttttttcctgtttggtcactgatgcctccgtgtaagggggatttctgttcatgggggtaatgataccgatgaaacgagagaggatgctcacgatacgggttactgatgatgaacatgcccggttactggaacgttgtgagggtaaacaactggcggtatggatgcggcgggaccagagaaaaatcactcagggtcaatgccagcgcttcgttaatacagatgtaggtgttccacagggtagccagcagcatcctgcgatgcagatccggaacataatggtgcagggcgctgacttccgcgtttccagactttacgaaacacggaaaccgaagaccattcatgttgttgctcaggtcgcagacgttttgcagcagcagtcgcttcacgttcgctcgcgtatcggtgattcattctgctaaccagtaaggcaaccccgccagcctagccgggtcctcaacgacaggagcacgatcatgcgcacccgtggccaggacccaacgctgcccgagatgcgccgcgtgcggctgctggagatggcggacgcgatggatatgttctgccaagggttggtttgcgcattcacagttctccgcaagaattgattggctccaattcttggagtggtgaatccgttagcgaggtgccgccggcttccattcaggtcgaggtggcccggctccatgcaccgcgacgcaacgcggggaggcagacaaggtatagggcggcgcctacaatccatgccaacccgttccatgtgctcgccgaggcggcataaatcgccgtgacgatcagcggtccagtgatcgaagttaggctggtaagagccgcgagcgatccttgaagctgtccctgatggtcgtcatctacctgcctggacagcatggcctgcaacgcgggcatcccgatgccgccggaagcgagaagaatcataatggggaaggccatccagcctcgcgtcgcgaacgccagcaagacgtagcccagcgcgtcggccgccatgccggcgataatggcctgcttctcgccgaaacgtttggtggcgggaccagtgacgaaggcttgagcgagggcgtgcaagattccgaataccgcaagcgacaggccgatcatcgtcgcgctccagcgaaagcggtcctcgccgaaaatgacccagagcgctgccggcacctgtcctacgagttgcatgataaagaagacagtcataagtgcggcgacgatagtcatgccccgcgcccaccggaaggagctgactgggttgaaggctctcaagggcatcggtcgacgctctcccttatgcgactcctgcattaggaagcagcccagtagtaggttgaggccgttgagcaccgccgccgcaaggaatggtgcatgcaaggagatggcgcccaacagtcccccggccacggggcctgccaccatacccacgccgaaacaagcgctcatgagcccgaagtggcgagcccgatcttccccatcggtgatgtcggcgatataggcgccagcaaccgcacctgtggcgccggtgatgccggccacgatgcgtccggcgtagaggatcgagatctcgatcccgcgaaattaatacgactcactatagggagaccacaacggtttccctctagtgccggctccggagagctctttaattaagcggccgccctgcaggactcgagttctagaaataattttgtttaactttaagaaggagatatagttaacctctacttccaatccggctctcatcaccatcaccatcactaataaccaactccataaggatccgcgatcgcggcgcgccacctggtggccggccggtaccacgcgtgcgcgctgatccggctgctaacaaagcccgaaaggaagctgagttggctgctgccaccgctgagcaataactagcataaccccttggggcctctaaacgggtcttgaggggttttttgctgaaaggaggaactatatccggacatccacaggacgggtgtggtcgccatgatcgcgtagtcgatagtggctccaagtagcgaagcgagcaggactgggcggcggccaaagcggtcggacagtgctccgagaacgggtgcgcatagaaattgcatcaacgcatatagcgctagcagcacgccatagtgactggcgatgctgtcggaatggacgacatcccgcaagaggcccggcagtaccggcataaccaagcctatgcctacagcatccagggtgacggtgccgaggatgacgatgagcgcattgttagatttcatacacggtgcctgactgcgttagcaatttaactgtgataaactaccgcattaaagcttatcgatgataagctgtcaaacatgagaa", ), // features: Vec::new(), promoter: Some(RangeIncl::new(4010, 4029)), terminator: Some(RangeIncl::new(4_326, 4_373)), rbs: Some(RangeIncl::new(4117, 4139)), antibiotic_resistance: AntibioticResistance::Ampicillin, expression_system: ExpressionSystem::T7, genes_included: Vec::new(), copy_number: CopyNumber::Low, his_tag: Some(RangeIncl::new(4171, 4188)), seq_topology: SeqTopology::Circular, direction: Forward, data: Default::default(), }, Backbone { name: "pET LIC cloning vector (2A-T)".to_owned(), addgene_id: Some(29_665), seq: seq_from_str( "ttcttgaagacgaaagggcctcgtgatacgcctatttttataggttaatgtcatgataataatggtttcttagacgtcaggtggcacttttcggggaaatgtgcgcggaacccctatttgtttatttttctaaatacattcaaatatgtatccgctcatgagacaataaccctgataaatgcttcaataacattgaaaaaggaagagtatgagtattcaacatttccgtgtcgcccttattcccttttttgcggcattttgccttcctgtttttgctcacccagaaacgctggtgaaagtaaaagatgctgaagatcagttgggtgcacgagtgggttacatcgaactggatctcaacagcggtaagatccttgagagttttcgccccgaagaacgttttccaatgatgagcacttttaaagttctgctatgtggcgcggtattatcccgtgttgacgccgggcaagagcaactcggtcgccgcatacactattctcagaatgacttggttgagtactcaccagtcacagaaaagcatcttacggatggcatgacagtaagagaattatgcagtgctgccataaccatgagtgataacactgcggccaacttacttctgacaacgatcggaggaccgaaggagctaaccgcttttttgcacaacatgggggatcatgtaactcgccttgatcgttgggaaccggagctgaatgaagccataccaaacgacgagcgtgacaccacgatgcctgcagcaatggcaacaacgttgcgcaaactattaactggcgaactacttactctagcttcccggcaacaattaatagactggatggaggcggataaagttgcaggaccacttctgcgctcggcccttccggctggctggtttattgctgataaatctggagccggtgagcgtgggtctcgcggtatcattgcagcactggggccagatggtaagccctcccgtatcgtagttatctacacgacggggagtcaggcaactatggatgaacgaaatagacagatcgctgagataggtgcctcactgattaagcattggtaactgtcagaccaagtttactcatatatactttagattgatttaaaacttcatttttaatttaaaaggatctaggtgaagatcctttttgataatctcatgaccaaaatcccttaacgtgagttttcgttccactgagcgtcagaccccgtagaaaagatcaaaggatcttcttgagatcctttttttctgcgcgtaatctgctgcttgcaaacaaaaaaaccaccgctaccagcggtggtttgtttgccggatcaagagctaccaactctttttccgaaggtaactggcttcagcagagcgcagataccaaatactgtccttctagtgtagccgtagttaggccaccacttcaagaactctgtagcaccgcctacatacctcgctctgctaatcctgttaccagtggctgctgccagtggcgataagtcgtgtcttaccgggttggactcaagacgatagttaccggataaggcgcagcggtcgggctgaacggggggttcgtgcacacagcccagcttggagcgaacgacctacaccgaactgagatacctacagcgtgagctatgagaaagcgccacgcttcccgaagggagaaaggcggacaggtatccggtaagcggcagggtcggaacaggagagcgcacgagggagcttccagggggaaacgcctggtatctttatagtcctgtcgggtttcgccacctctgacttgagcgtcgatttttgtgatgctcgtcaggggggcggagcctatggaaaaacgccagcaacgcggcctttttacggttcctggccttttgctggccttttgctcacatgttctttcctgcgttatcccctgattctgtggataaccgtattaccgcctttgagtgagctgataccgctcgccgcagccgaacgaccgagcgcagcgagtcagtgagcgaggaagcggaagagcgcctgatgcggtattttctccttacgcatctgtgcggtatttcacaccgcatatatggtgcactctcagtacaatctgctctgatgccgcatagttaagccagtatacactccgctatcgctacgtgactgggtcatggctgcgccccgacacccgccaacacccgctgacgcgccctgacgggcttgtctgctcccggcatccgcttacagacaagctgtgaccgtctccgggagctgcatgtgtcagaggttttcaccgtcatcaccgaaacgcgcgaggcagctgcggtaaagctcatcagcgtggtcgtgaagcgattcacagatgtctgcctgttcatccgcgtccagctcgttgagtttctccagaagcgttaatgtctggcttctgataaagcgggccatgttaagggcggttttttcctgtttggtcactgatgcctccgtgtaagggggatttctgttcatgggggtaatgataccgatgaaacgagagaggatgctcacgatacgggttactgatgatgaacatgcccggttactggaacgttgtgagggtaaacaactggcggtatggatgcggcgggaccagagaaaaatcactcagggtcaatgccagcgcttcgttaatacagatgtaggtgttccacagggtagccagcagcatcctgcgatgcagatccggaacataatggtgcagggcgctgacttccgcgtttccagactttacgaaacacggaaaccgaagaccattcatgttgttgctcaggtcgcagacgttttgcagcagcagtcgcttcacgttcgctcgcgtatcggtgattcattctgctaaccagtaaggcaaccccgccagcctagccgggtcctcaacgacaggagcacgatcatgcgcacccgtggccaggacccaacgctgcccgagatgcgccgcgtgcggctgctggagatggcggacgcgatggatatgttctgccaagggttggtttgcgcattcacagttctccgcaagaattgattggctccaattcttggagtggtgaatccgttagcgaggtgccgccggcttccattcaggtcgaggtggcccggctccatgcaccgcgacgcaacgcggggaggcagacaaggtatagggcggcgcctacaatccatgccaacccgttccatgtgctcgccgaggcggcataaatcgccgtgacgatcagcggtccagtgatcgaagttaggctggtaagagccgcgagcgatccttgaagctgtccctgatggtcgtcatctacctgcctggacagcatggcctgcaacgcgggcatcccgatgccgccggaagcgagaagaatcataatggggaaggccatccagcctcgcgtcgcgaacgccagcaagacgtagcccagcgcgtcggccgccatgccggcgataatggcctgcttctcgccgaaacgtttggtggcgggaccagtgacgaaggcttgagcgagggcgtgcaagattccgaataccgcaagcgacaggccgatcatcgtcgcgctccagcgaaagcggtcctcgccgaaaatgacccagagcgctgccggcacctgtcctacgagttgcatgataaagaagacagtcataagtgcggcgacgatagtcatgccccgcgcccaccggaaggagctgactgggttgaaggctctcaagggcatcggtcgacgctctcccttatgcgactcctgcattaggaagcagcccagtagtaggttgaggccgttgagcaccgccgccgcaaggaatggtgcatgcaaggagatggcgcccaacagtcccccggccacggggcctgccaccatacccacgccgaaacaagcgctcatgagcccgaagtggcgagcccgatcttccccatcggtgatgtcggcgatataggcgccagcaaccgcacctgtggcgccggtgatgccggccacgatgcgtccggcgtagaggatcgagatctcgatcccgcgaaattaatacgactcactatagggagaccacaacggtttccctctagtgccggctccggagagctctttaattaagcggccgccctgcaggactcgagttctagaaataattttgtttaactttaagaaggagatatagatatcccaactccataaggatccgcgatcgcggcgcgccacctggtggccggccggtaccacgcgtgcgcgctgatccggctgctaacaaagcccgaaaggaagctgagttggctgctgccaccgctgagcaataactagcataaccccttggggcctctaaacgggtcttgaggggttttttgctgaaaggaggaactatatccggacatccacaggacgggtgtggtcgccatgatcgcgtagtcgatagtggctccaagtagcgaagcgagcaggactgggcggcggccaaagcggtcggacagtgctccgagaacgggtgcgcatagaaattgcatcaacgcatatagcgctagcagcacgccatagtgactggcgatgctgtcggaatggacgacatcccgcaagaggcccggcagtaccggcataaccaagcctatgcctacagcatccagggtgacggtgccgaggatgacgatgagcgcattgttagatttcatacacggtgcctgactgcgttagcaatttaactgtgataaactaccgcattaaagcttatcgatgataagctgtcaaacatgagaa", ), // features: Vec::new(), promoter: Some(RangeIncl::new(4010, 4029)), terminator: Some(RangeIncl::new(4_281, 4_328)), rbs: Some(RangeIncl::new(4117, 4139)), antibiotic_resistance: AntibioticResistance::Ampicillin, expression_system: ExpressionSystem::T7, genes_included: Vec::new(), copy_number: CopyNumber::Low, his_tag: None, seq_topology: SeqTopology::Circular, direction: Forward, data: Default::default(), }, // https://www.snapgene.com/plasmids/pet_and_duet_vectors_(novagen)/pET-21(%2B) Backbone { name: "pET-21(+)".to_owned(), addgene_id: None, // seq: seq_from_str("atccggatatagttcctcctttcagcaaaaaacccctcaagacccgtttagaggccccaaggggttatgctagttattgctcagcggtggcagcagccaactcagcttcctttcgggctttgttagcagccggatctcagtggtggtggtggtggtgctcgagtgcggccgcaagcttgtcgacggagctcgaattcggatcctagaggggaattgttatccgctcacaattcccctatagtgagtcgtattaatttcgcgggatcgagatctcgatcctctacgccggacgcatcgtggccggcatcaccggcgccacaggtgcggttgctggcgcctatatcgccgacatcaccgatggggaagatcgggctcgccacttcgggctcatgagcgcttgtttcggcgtgggtatggtggcaggccccgtggccgggggactgttgggcgccatctccttgcatgcaccattccttgcggcggcggtgctcaacggcctcaacctactactgggctgcttcctaatgcaggagtcgcataagggagagcgtcgagatcccggacaccatcgaatggcgcaaaacctttcgcggtatggcatgatagcgcccggaagagagtcaattcagggtggtgaatgtgaaaccagtaacgttatacgatgtcgcagagtatgccggtgtctcttatcagaccgtttcccgcgtggtgaaccaggccagccacgtttctgcgaaaacgcgggaaaaagtggaagcggcgatggcggagctgaattacattcccaaccgcgtggcacaacaactggcgggcaaacagtcgttgctgattggcgttgccacctccagtctggccctgcacgcgccgtcgcaaattgtcgcggcgattaaatctcgcgccgatcaactgggtgccagcgtggtggtgtcgatggtagaacgaagcggcgtcgaagcctgtaaagcggcggtgcacaatcttctcgcgcaacgcgtcagtgggctgatcattaactatccgctggatgaccaggatgccattgctgtggaagctgcctgcactaatgttccggcgttatttcttgatgtctctgaccagacacccatcaacagtattattttctcccatgaagacggtacgcgactgggcgtggagcatctggtcgcattgggtcaccagcaaatcgcgctgttagcgggcccattaagttctgtctcggcgcgtctgcgtctggctggctggcataaatatctcactcgcaatcaaattcagccgatagcggaacgggaaggcgactggagtgccatgtccggttttcaacaaaccatgcaaatgctgaatgagggcatcgttcccactgcgatgctggttgccaacgatcagatggcgctgggcgcaatgcgcgccattaccgagtccgggctgcgcgttggtgcggatatctcggtagtgggatacgacgataccgaagacagctcatgttatatcccgccgttaaccaccatcaaacaggattttcgcctgctggggcaaaccagcgtggaccgcttgctgcaactctctcagggccaggcggtgaagggcaatcagctgttgcccgtctcactggtgaaaagaaaaaccaccctggcgcccaatacgcaaaccgcctctccccgcgcgttggccgattcattaatgcagctggcacgacaggtttcccgactggaaagcgggcagtgagcgcaacgcaattaatgtaagttagctcactcattaggcaccgggatctcgaccgatgcccttgagagccttcaacccagtcagctccttccggtgggcgcggggcatgactatcgtcgccgcacttatgactgtcttctttatcatgcaactcgtaggacaggtgccggcagcgctctgggtcattttcggcgaggaccgctttcgctggagcgcgacgatgatcggcctgtcgcttgcggtattcggaatcttgcacgccctcgctcaagccttcgtcactggtcccgccaccaaacgtttcggcgagaagcaggccattatcgccggcatggcggccccacgggtgcgcatgatcgtgctcctgtcgttgaggacccggctaggctggcggggttgccttactggttagcagaatgaatcaccgatacgcgagcgaacgtgaagcgactgctgctgcaaaacgtctgcgacctgagcaacaacatgaatggtcttcggtttccgtgtttcgtaaagtctggaaacgcggaagtcagcgccctgcaccattatgttccggatctgcatcgcaggatgctgctggctaccctgtggaacacctacatctgtattaacgaagcgctggcattgaccctgagtgatttttctctggtcccgccgcatccataccgccagttgtttaccctcacaacgttccagtaaccgggcatgttcatcatcagtaacccgtatcgtgagcatcctctctcgtttcatcggtatcattacccccatgaacagaaatcccccttacacggaggcatcagtgaccaaacaggaaaaaaccgcccttaacatggcccgctttatcagaagccagacattaacgcttctggagaaactcaacgagctggacgcggatgaacaggcagacatctgtgaatcgcttcacgaccacgctgatgagctttaccgcagctgcctcgcgcgtttcggtgatgacggtgaaaacctctgacacatgcagctcccggagacggtcacagcttgtctgtaagcggatgccgggagcagacaagcccgtcagggcgcgtcagcgggtgttggcgggtgtcggggcgcagccatgacccagtcacgtagcgatagcggagtgtatactggcttaactatgcggcatcagagcagattgtactgagagtgcaccatatatgcggtgtgaaataccgcacagatgcgtaaggagaaaataccgcatcaggcgctcttccgcttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggataacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctcagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatctaaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctgcaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgcacatttccccgaaaagtgccacctgaaattgtaaacgttaatattttgttaaaattcgcgttaaatttttgttaaatcagctcattttttaaccaataggccgaaatcggcaaaatcccttataaatcaaaagaatagaccgagatagggttgagtgttgttccagtttggaacaagagtccactattaaagaacgtggactccaacgtcaaagggcgaaaaaccgtctatcagggcgatggcccactacgtgaaccatcaccctaatcaagttttttggggtcgaggtgccgtaaagcactaaatcggaaccctaaagggagcccccgatttagagcttgacggggaaagccggcgaacgtggcgagaaaggaagggaagaaagcgaaaggagcgggcgctagggcgctggcaagtgtagcggtcacgctgcgcgtaaccaccacacccgccgcgcttaatgcgccgctacagggcgcgtcccattcgcca"), seq: seq_complement(&seq_from_str(
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
true
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/alignment_map.rs
src/alignment_map.rs
//! Data structures and related code for BAM and SAM alignment map data. //! [SAM/BAM spec document, CAO Nov 2024](https://samtools.github.io/hts-specs/SAMv1.pdf) //! //! BAM format is little endian. use std::{ fs::File, io, io::{BufRead, ErrorKind, Read}, path::Path, }; use bgzip::{BGZFError, BGZFReader, index::BGZFIndex, read::IndexedBGZFReader}; use flate2::read::{GzDecoder, MultiGzDecoder}; /// Syntax helper for parsing multi-byte fields into primitives. /// /// Example: `parse_le!(bytes, i32, 5..9);` #[macro_export] macro_rules! parse_le { ($bytes:expr, $t:ty, $range:expr) => {{ <$t>::from_le_bytes($bytes[$range].try_into().unwrap()) }}; } const MAGIC: [u8; 4] = [b'B', b'A', b'M', 1]; #[derive(Debug)] struct RefSeq { pub name: String, pub l_ref: u32, } impl RefSeq { /// Deserialize from BAM. pub fn from_buf(buf: &[u8]) -> io::Result<Self> { let l_name = parse_le!(buf, u32, 0..4); let name_end = 4 + l_name as usize; Ok(Self { // todo: Don't unwrap this string parsing; map the error // name_end - 1: Don't parse the trailing NUL char. (In the spec, this is a null-terminated string) name: String::from_utf8(buf[4..name_end - 1].to_vec()).unwrap(), l_ref: parse_le!(buf, u32, name_end..name_end + 4), }) } /// Serialize to BAM. pub fn to_buf(&self) -> Vec<u8> { Vec::new() } } #[derive(Debug)] struct AuxData { pub tag: [u8; 2], pub val_type: u8, /// corresponds to val_type. pub value: Vec<u8>, // todo: Placeholder } #[derive(Debug)] struct Alignment { /// Size of the entire alignment packet, *except the 4-byte block size*. Includes aux data. pub block_size: u32, pub ref_id: i32, pub pos: i32, pub mapq: u8, pub bin: u16, pub n_cigar_op: u16, pub flag: u16, pub next_ref_id: i32, pub next_pos: i32, pub tlen: i32, pub read_name: String, pub cigar: Vec<u32>, pub seq: Vec<u8>, // 4-bit encoded pub qual: String, // todo: Vec<u8>? pub aux_data: Vec<AuxData>, } impl Alignment { /// Deserialize from BAM. pub fn from_buf(buf: &[u8]) -> io::Result<Self> { if buf.len() < 36 { return Err(io::Error::new( ErrorKind::InvalidData, "Buffer is too small to contain a valid Alignment record", )); } let block_size = parse_le!(buf, u32, 0..4); println!("Block size: {:?}", block_size); let ref_id = parse_le!(buf, i32, 4..8); let pos = parse_le!(buf, i32, 8..12); let l_read_name = buf[12] as usize; let mapq = buf[13]; let bin = parse_le!(buf, u16, 14..16); let n_cigar_op = parse_le!(buf, u16, 16..18); let flag = parse_le!(buf, u16, 18..20); let l_seq = parse_le!(buf, u32, 20..24) as usize; let next_ref_id = parse_le!(buf, i32, 24..28); let next_pos = parse_le!(buf, i32, 28..32); let tlen = parse_le!(buf, i32, 32..36); let mut i = 36; // -1: Ommit the trailing null. println!("Len read name: {:?}", l_read_name); let read_name = String::from_utf8(buf[i..i + l_read_name - 1].to_vec()) .map_err(|e| io::Error::new(ErrorKind::InvalidData, e))?; i += l_read_name; let cigar_len = n_cigar_op as usize; let mut cigar = Vec::new(); for _ in 0..cigar_len { let cigar_op = parse_le!(buf, u32, i..i + 4); cigar.push(cigar_op); i += 4; } // todo: Figure out how this is actually handled, and set the struct type A/R. let seq_len = (l_seq + 1) / 2; // Each nucleotide is 4 bits let seq = buf[i..i + seq_len].to_vec(); i += seq_len; let qual = buf[i..i + l_seq].to_vec(); i += l_seq; let aux_data = Vec::new(); // todo: Parse auxiliary data from the remaining bytes. Ok(Self { block_size, ref_id, pos, mapq, bin, n_cigar_op, flag, next_ref_id, next_pos, tlen, read_name, cigar, seq, qual: String::new(), // Placeholder until auxiliary data parsing aux_data, }) } /// Serialize to BAM. pub fn to_buf_(&self) -> Vec<u8> { // todo: If desired. Vec::new() } } #[derive(Debug)] /// Represents BAM or SAM data. See the spec document, section 4.2. This maps directly to the BAM format. /// Fields, and their types, here and in sub-structs are taken directly from this table. pub struct AlignmentMap { pub l_text: u32, pub text: String, pub n_ref: u32, pub refs: Vec<RefSeq>, pub alignments: Vec<Alignment>, } impl AlignmentMap { /// Deserialize an alignment record from a buffer containing BAM data. pub fn from_buf(buf: &[u8]) -> io::Result<Self> { if buf.len() < 12 { return Err(io::Error::new( ErrorKind::InvalidData, "Buffer is too small to contain a valid header", )); } let l_text = parse_le!(buf, u32, 4..8); let text_end = 8 + l_text as usize; let n_ref = parse_le!(buf, u32, text_end..text_end + 4); let refs_start = text_end + 4; let mut i = refs_start; let mut refs = Vec::new(); for _ in 0..n_ref { let ref_seq = RefSeq::from_buf(buf[i..].try_into().unwrap())?; i += 9 + ref_seq.name.len(); refs.push(ref_seq); } let mut alignments = Vec::new(); while i + 1 < buf.len() { let alignment = Alignment::from_buf(buf[i..].try_into().unwrap())?; println!("\n\n Alignment: {:?}", alignment); i += 4 + alignment.block_size as usize; alignments.push(alignment); } if buf[0..4] != MAGIC { return Err(io::Error::new( ErrorKind::InvalidData, "Incorrect BAM magic.".to_string(), )); } Ok(Self { l_text, // todo: Map the error; don't unwrap. text: String::from_utf8(buf[8..text_end].to_vec()).unwrap(), n_ref, refs, alignments, }) } /// Serialize to BAM. pub fn to_buf(&self) -> Vec<u8> { Vec::new() } } pub fn import(path: &Path) -> io::Result<AlignmentMap> { let file = File::open(path)?; let mut decoder = GzDecoder::new(file); // let mut decoder = MultiGzDecoder::new(file); println!("Decoding file..."); let mut buf = Vec::new(); // let mut buf = [0; 80_000]; decoder.read_to_end(&mut buf)?; println!("Decode complete. Reading..."); let header = AlignmentMap::from_buf(&buf); header // AlignmentMap::from_buf(&buf) } // pub fn import(path: &Path) -> io::Result<AlignmentMap> { // let file = File::open(path)?; // // let mut reader = // BGZFReader::new(file).unwrap(); // todo: Map error. // // // let index = BGZFIndex::from_reader(reader)?; // // // println!("Index entries: {:?}", index.entries()); // // // let mut reader = // // IndexedBGZFReader::new(reader, index).unwrap(); // todo: Map error. // // // println!("Voffset A: {:?}", reader.bgzf_pos()); // // reader.bgzf_seek(0).unwrap(); // todo: Map error. // // reader.seek(0).unwrap(); // todo: Map error. // // // let mut buf = Vec::new(); // let mut buf = vec![0; 80_000]; // // // reader.read_to_end(&mut buf).unwrap(); // todo: Map error. // reader.read(&mut buf).unwrap(); // todo: Map error. // // println!("Voffset: {:?}", reader.bgzf_pos()); // // println!("BUf contents: {:?}", &buf[13180..13220]); // // AlignmentMap::from_buf(&buf) // } // /// todo: Move to `file_io` A/R. // /// Note: BAM files are compressed using BGZF, and are therefore split into blocks no larger than 64kb. // pub fn import(path: &Path) -> io::Result<AlignmentMap> { // let mut file = File::open(path)?; // let mut decompressed_data = Vec::new(); // // // todo: Organize this A/R. // // loop { // println!("BAM block...\n"); // // Read BGZF block header (18 bytes) // let mut block_header = [0u8; 18]; // if let Err(e) = file.read_exact(&mut block_header) { // if e.kind() == ErrorKind::UnexpectedEof { // break; // Reached end of file // } // return Err(e); // } // // // Parse block size (last 2 bytes of header, little-endian) // let block_size = u16::from_le_bytes([block_header[16], block_header[17]]) as usize; // // println!("Block size: {:?}", block_size); // // if block_size < 18 { // return Err(io::Error::new( // ErrorKind::InvalidData, // "Invalid BGZF block size", // )); // } // // // Read the block data // let mut block_data = vec![0u8; block_size - 18]; // file.read_exact(&mut block_data)?; // // // Decompress the block // let mut decoder = GzDecoder::new(&block_data[..]); // let mut decompressed_block = Vec::new(); // decoder.read_to_end(&mut decompressed_block)?; // // // Append to the full decompressed buffer // decompressed_data.extend_from_slice(&decompressed_block); // } // // AlignmentMap::from_buf(&decompressed_data) // } /// Calculate bin given an alignment covering [beg, end) (zero-based, half-closed-half-open) /// This is adapted from C code in the spec document. fn reg_to_bin(beg: i32, end: i32) -> i32 { let end = end - 1; // Adjust end to be inclusive if beg >> 14 == end >> 14 { return ((1 << 15) - 1) / 7 + (beg >> 14); } if beg >> 17 == end >> 17 { return ((1 << 12) - 1) / 7 + (beg >> 17); } if beg >> 20 == end >> 20 { return ((1 << 9) - 1) / 7 + (beg >> 20); } if beg >> 23 == end >> 23 { return ((1 << 6) - 1) / 7 + (beg >> 23); } if beg >> 26 == end >> 26 { return ((1 << 3) - 1) / 7 + (beg >> 26); } 0 } /// Calculate the list of bins that may overlap with region [beg, end) (zero-based) /// This is adapted from C code in the spec document. fn reg_to_bins(beg: i32, end: i32, list: &mut Vec<u16>) -> usize { let end = end - 1; // Adjust end to be inclusive list.push(0); for k in (1 + (beg >> 26))..=(1 + (end >> 26)) { list.push(k as u16); } for k in (9 + (beg >> 23))..=(9 + (end >> 23)) { list.push(k as u16); } for k in (73 + (beg >> 20))..=(73 + (end >> 20)) { list.push(k as u16); } for k in (585 + (beg >> 17))..=(585 + (end >> 17)) { list.push(k as u16); } for k in (4681 + (beg >> 14))..=(4681 + (end >> 14)) { list.push(k as u16); } list.len() }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/toxic_proteins.rs
src/toxic_proteins.rs
//! Contains code related to identifying toxic proteins. use na_seq::{ Nucleotide, amino_acids::{AminoAcid, CodingResult}, }; use crate::protein::proteins_from_seq; const GLN_TRACT_SCAN_FRAME: usize = 35; const GLN_MAX_PORTION: f32 = 0.75; #[derive(Clone, Copy, PartialEq)] enum ToxicStatus { Pass, Fail, } // #[derive(Clone, Copy)] // enum Host { // Ecoli, // Aav, // } /// Identify tracts, in all reading frames, of long sequences of Glutamine; this may lead to aggregation, /// and therefor toxicity. Sequences of 35 Gln in a row are a good indicator of this. fn check_glu_tracts(seq: &[Nucleotide]) -> ToxicStatus { let len = seq.len(); let mut seq_rev = seq.to_vec(); seq_rev.reverse(); // For each reading frame, create a Vec of amino acids. for seq_ in &[seq, &seq_rev] { for rf_offset in 0..2 { let mut aa_seq = Vec::new(); for i_ in 0..len / 3 { let i = i_ * 3 + rf_offset; // The ORF-modified sequence index. if i + 3 >= len { break; } let nts = &seq_[i..i + 3]; // let mut matched = false; if let CodingResult::AminoAcid(aa) = CodingResult::from_codons(nts.try_into().unwrap()) { // Note: We are ignoring stop codons here. aa_seq.push(aa) } } // Now that we have a set of AA for this reading frame, scan for Glu tracts. // If we find any, return the failure state. for start_i in 0..aa_seq.len() - GLN_TRACT_SCAN_FRAME { let mut num_gln = 0; for i in start_i..start_i + aa_seq.len() { if aa_seq[i] == AminoAcid::Gln { num_gln += 1; } } if num_gln as f32 / GLN_TRACT_SCAN_FRAME as f32 > GLN_MAX_PORTION { return ToxicStatus::Fail; } } } } ToxicStatus::Pass }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/pcr.rs
src/pcr.rs
//! This module assists in identifying PCR parameters use bincode::{Decode, Encode}; use na_seq::Seq; use crate::{ gui::navigation::{Page, PageSeq, Tab}, primer::{Primer, TM_TARGET}, state::State, util::RangeIncl, }; #[derive(Clone, Encode, Decode)] /// Variables for UI fields, for determining PCR parameters. pub struct PcrUi { pub primer_tm: f32, pub product_len: usize, pub polymerase_type: PolymeraseType, pub num_cycles: u16, /// Index from primer data for the load-from-primer system. For storing dropdown state. pub primer_selected: usize, /// These are for the PCR product generation pub primer_fwd: usize, pub primer_rev: usize, } impl Default for PcrUi { fn default() -> Self { Self { primer_tm: TM_TARGET, product_len: 1_000, polymerase_type: Default::default(), num_cycles: 30, primer_selected: 0, primer_fwd: 0, primer_rev: 0, } } } /// This is a common pattern for PCR parameters #[derive(Default, Encode, Decode)] pub struct TempTime { /// In °C pub temp: f32, /// In seconds pub time: u16, } impl TempTime { pub fn new(temp: f32, time: u16) -> Self { Self { temp, time } } } #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum PolymeraseType { NormalFidelity, /// Eg Phusion; results in a shorter extension time. HighFidelity, } impl Default for PolymeraseType { fn default() -> Self { Self::NormalFidelity } } impl PolymeraseType { pub fn extension_time(&self, product_len: usize) -> u16 { match self { Self::NormalFidelity => (60 * product_len / 1_000) as u16, // 15 - 30. 15 recommended in FastCloning guide. PHusion manual: 15-30s/kb. Self::HighFidelity => (15 * product_len / 1_000) as u16, // } } pub fn denaturation(&self) -> TempTime { match self { Self::NormalFidelity => TempTime::new(94., 30), Self::HighFidelity => TempTime::new(98., 10), // pHusion manual: 5-10s. } } pub fn denaturation_initial(&self) -> TempTime { match self { Self::NormalFidelity => TempTime::new(94., 120), Self::HighFidelity => TempTime::new(98., 30), } } pub fn to_str(self) -> String { match self { Self::NormalFidelity => "Normal fidelity", Self::HighFidelity => "High fidelity (eg Phusion)", } .to_owned() } } #[derive(Default, Encode, Decode)] pub struct PcrParams { pub initial_denaturation: TempTime, pub denaturation: TempTime, pub annealing: TempTime, pub extension: TempTime, pub final_extension: TempTime, pub num_cycles: u16, } impl PcrParams { pub fn new(data: &PcrUi) -> Self { Self { initial_denaturation: data.polymerase_type.denaturation_initial(), denaturation: data.polymerase_type.denaturation(), // Alternative: Ta = 0.3 x Tm(primer) + 0.7 Tm(product) – 14.9. // 15-60s. How do we choose?. Phusion manual: 10-30s. annealing: TempTime::new(data.primer_tm - 5., 30), // 72 is good if Taq, and Phusion. extension: TempTime::new(72., data.polymerase_type.extension_time(data.product_len)), // Alternatively: 5-10 mins? Perhaps 30s per 1kb?) Phusion manual: 5-10m. final_extension: TempTime::new(72., 60 * 6), num_cycles: data.num_cycles, } } } /// Create a new tab containing of the PCR amplicon. pub fn make_amplicon_tab( state: &mut State, product_seq: Seq, range: RangeIncl, fwd_primer: Primer, rev_primer: Primer, ) { let mut product_features = Vec::new(); for feature in &state.generic[state.active].features { // todo: Handle circle wraps etc. if range.start < feature.range.start && range.end > feature.range.end { let mut product_feature = feature.clone(); // Find the indexes in the new product sequence. product_feature.range.start -= range.start - 1; product_feature.range.end -= range.start - 1; product_features.push(product_feature); } } state.add_tab(); state.tabs_open.push(Default::default()); // if let Some(seq) = range_combined.index_seq(&state.generic.seq) { state.generic[state.active].seq = product_seq; // Include the primers used for PCR, and features that are included in the new segment. // note that the feature indexes will need to change. let product_primers = vec![fwd_primer, rev_primer]; state.generic[state.active].features = product_features; state.generic[state.active].primers = product_primers; state.generic[state.active].metadata.plasmid_name = "PCR amplicon".to_owned(); state.sync_seq_related(None); // state.sync_primer_metrics(); state.ui.page = Page::Sequence; state.ui.page_seq = PageSeq::View; }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/tags.rs
src/tags.rs
//! This module contains info related to tags, like the 6x HIS tag. use std::ops::RangeInclusive; use na_seq::Nucleotide; pub struct TagMatch { pub lib_index: usize, // todo: Experimenting with ranges vice (usize, usize) /// 0-based indexing. pub seq: RangeInclusive<usize>, } pub struct Tag { pub name: String, // From the 5' end. // pub seq: Seq, // todo: You may eventually need Vec<NucleotideGeneral>. } impl Tag { pub fn new(name: &str) -> Self { Self { name: name.to_owned(), } } } // T7 promoter: TAATACGACTCACTATAG // T7 term: GCTAGTTATTGCTCAGCGG // T7 term take 2: ctagcataaccccttggggcctctaaacgggtcttgaggggttttttg pub fn _find_tag_matches(seq: &[Nucleotide], lib: &[Tag]) -> Vec<TagMatch> { let mut result = Vec::new(); result } /// Load a set of common Restriction enzymes. Call this at program start, to load into a state field. pub fn _load_tag_library() -> Vec<Tag> { vec![ // todo: Hisx6+x, // todo: T7 promoter // Tag::new("AatII", vec![G, A, C, G, T, C], 4), ] }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/portions.rs
src/portions.rs
//! Code related to mixing portions. Used for performing quick mixing volume calculations. // todo: Consider including pKa info, and including tools to balance pH. use std::fmt::Display; use bincode::{Decode, Encode}; #[derive(Clone, Encode, Decode)] pub struct PortionsState { pub solutions: Vec<Solution>, pub media_input: MediaPrepInput, pub media_result: MediaPrep, } impl Default for PortionsState { fn default() -> Self { let media_input = MediaPrepInput::default(); let media_result = media_prep(&media_input); let mut result = Self { solutions: Vec::new(), media_input, media_result, }; result } } #[derive(Default, Clone, Encode, Decode)] pub struct Solution { pub name: String, /// Liters pub total_volume: f32, pub reagents: Vec<Reagent>, pub sub_solns: Vec<Solution>, /// Volatile; not to be added to directly. pub reagents_sub_solns: Vec<Reagent>, } impl Solution { /// Find required amounts (mass or volume) for each reagent. pub fn calc_amounts(&mut self) { self.reagents_sub_solns = Vec::new(); for sub_sol in &self.sub_solns { for reagent in &sub_sol.reagents { self.reagents_sub_solns.push(reagent.clone()); } } for reagent in &mut self.reagents { reagent.calc_amount(self.total_volume); } } } #[derive(Clone, Copy, Encode, Decode)] pub enum AmountCalculated { /// grams Mass(f32), /// Liters Volume(f32), } impl Display for AmountCalculated { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Mass(v) => { if *v > 1. { format!("{:.2} g", v) } else if *v >= 0.001 { format!("{:.2} mg", v * 1_000.) } else { format!("{:.2} μg", v * 1_000_000.) } } // todo: Be careful about this calc being called frequently. Self::Volume(v) => { if *v > 1. { format!("{:.2} L", v) } else if *v >= 0.001 { format!("{:.2} mL", v * 1_000.) } else { // todo: If you have precision issues, make your base unit mL. format!("{:.2} μL", v * 1_000_000.) } } }; write!(f, "{}", str) } } #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum ReagentPrep { Mass, /// Inner: Molarity Volume(f32), } impl Display for ReagentPrep { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Mass => "Mass".to_owned(), // Self::Volume(molarity) => format!("Volume. Molarity: {molarity})"), Self::Volume(_molarity) => "Volume".to_owned(), }; write!(f, "{}", str) } } #[derive(Clone, Encode, Decode)] pub struct Reagent { pub type_: ReagentType, pub prep: ReagentPrep, /// Target moles per liter in the solution pub molarity: f32, /// Calculated result pub amount_calc: AmountCalculated, } impl Default for Reagent { fn default() -> Self { Self { type_: ReagentType::Custom(0.), prep: ReagentPrep::Mass, molarity: 0., amount_calc: AmountCalculated::Mass(0.), } } } impl Reagent { pub fn calc_amount(&mut self, total_volume: f32) { // mol = mol/L x L let moles_req = self.molarity * total_volume; self.amount_calc = match self.prep { // g = g/mol x mol ReagentPrep::Mass => AmountCalculated::Mass(self.type_.weight() * moles_req), // L = mol / mol/L: ReagentPrep::Volume(reagent_molarity) => { if reagent_molarity.abs() < 0.00000001 { AmountCalculated::Volume(0.) } else { AmountCalculated::Volume(moles_req / reagent_molarity) } } }; } } /// A collection of common reagents, where we have molecular weights. #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum ReagentType { Custom(f32), // Inner: Molecular weight /// Index of the solution in state. Solution(usize), SodiumChloride, SodiumPhosphateMonobasic, SodiumPhosphateDibasic, SodiumPhosphateDibasicHeptahydrate, PotassiumPhosphateMonobasic, PotassiumPhosphateDibasic, TrisHcl, Iptg, Imidazole, Lysozyme, Mes, Bes, Tes, CitricAcid, Edta, HydrochloricAcid, // AceticAcid, SodiumHydroxide, BromophenolBlue, Dtt, MagnesiumChloride, Glycine, Sds, Tris, } impl ReagentType { /// g/mol pub fn weight(&self) -> f32 { match self { Self::Custom(weight) => *weight, Self::Solution(_) => 0., // todo? Self::SodiumChloride => 58.44, Self::SodiumPhosphateMonobasic => 119.98, Self::SodiumPhosphateDibasic => 141.96, Self::SodiumPhosphateDibasicHeptahydrate => 268.10, Self::PotassiumPhosphateMonobasic => 136.08, Self::PotassiumPhosphateDibasic => 174.17, Self::TrisHcl => 121.14, Self::Iptg => 238.298, Self::Imidazole => 68.08, Self::Lysozyme => 14_388., Self::Mes => 195.24, Self::Bes => 213.25, Self::Tes => 229.25, Self::CitricAcid => 192.12, Self::Edta => 292.24, Self::HydrochloricAcid => 36.46, Self::SodiumHydroxide => 40., Self::BromophenolBlue => 669.96, Self::Dtt => 154.25, Self::MagnesiumChloride => 95.211, Self::Glycine => 75.07, Self::Sds => 288.5, Self::Tris => 121.14, } } } impl Display for ReagentType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Custom(_) => "Custom".to_owned(), Self::Solution(_) => "Solution".to_owned(), // todo Self::SodiumChloride => "NaCl".to_owned(), Self::SodiumPhosphateMonobasic => "NaH₂PO₄ (Mono)".to_owned(), Self::SodiumPhosphateDibasic => "Na₂HPO₄ (Di)".to_owned(), Self::SodiumPhosphateDibasicHeptahydrate => "Na₂HPO₄·7H₂O".to_owned(), Self::PotassiumPhosphateMonobasic => "H₂KO₄P".to_owned(), Self::PotassiumPhosphateDibasic => "HK₂O₄P".to_owned(), Self::TrisHcl => "Tris-HCl".to_owned(), Self::Iptg => "IPTG".to_owned(), Self::Imidazole => "Imidazole".to_owned(), Self::Lysozyme => "Lysozyme".to_owned(), Self::Mes => "MES".to_owned(), Self::Bes => "BES".to_owned(), Self::Tes => "TES".to_owned(), Self::CitricAcid => "Citric acid".to_owned(), Self::Edta => "EDTA".to_owned(), Self::HydrochloricAcid => "HCl".to_owned(), Self::SodiumHydroxide => "NaOH".to_owned(), Self::BromophenolBlue => "Bromophenol blue".to_owned(), Self::Dtt => "DTT".to_owned(), Self::MagnesiumChloride => "MgCl₂".to_owned(), Self::Sds => "SDS".to_owned(), Self::Glycine => "Glycine".to_owned(), Self::Tris => "Tris".to_owned(), }; write!(f, "{}", str) } } #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum PlateSize { /// 60mm diameter D60, D90, D100, D150, } impl PlateSize { /// Nominal amount of liquid. Note that these go with the square of the baseline. We use 7mL for 60mm /// plates as the baseline. pub fn volume(&self) -> f32 { match self { Self::D60 => 0.007, Self::D90 => 0.01575, Self::D100 => 0.01944, Self::D150 => 0.04375, } } } impl Display for PlateSize { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::D60 => "60mm", Self::D90 => "90mm", Self::D100 => "100mm", Self::D150 => "150mm", }; write!(f, "{}", str) } } #[derive(Clone, PartialEq, Encode, Decode)] pub enum MediaPrepInput { Plates((PlateSize, usize)), // number of plates, Liquid(f32), // volume } impl Display for MediaPrepInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Plates(_) => "Plates", Self::Liquid(_) => "Liquid culture", }; write!(f, "{}", str) } } impl Default for MediaPrepInput { fn default() -> Self { Self::Plates((PlateSize::D90, 6)) } } #[derive(Clone, Default, Encode, Decode, Debug)] pub struct MediaPrep { pub water: f32, // L pub food: f32, // g pub agar: f32, // g pub antibiotic: f32, // mL } /// Returns volume of water, grams of LB, grams of agar, mL of 1000x antibiotics. pub fn media_prep(input: &MediaPrepInput) -> MediaPrep { let (volume, agar) = match input { MediaPrepInput::Plates((plate_size, num)) => { let volume = plate_size.volume() * *num as f32; (volume, volume * 15.) } MediaPrepInput::Liquid(volume) => (*volume, 0.), }; MediaPrep { water: volume, food: volume * 25., agar, antibiotic: volume, } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/feature_db_builder.rs
src/feature_db_builder.rs
//! This is the entrypoint for a standalone program that parse features from GenBank and SnapGene files. //! It assigns each sequence a label and feature type. use std::{ fs, path::{Path, PathBuf}, str::FromStr, }; mod file_io; mod gui; mod primer; mod sequence; // Required due to naviation::Page being in file_io::save // mod main; // todo temp mod feature_db_load; // todo temp use sequence::{FeatureType, Seq}; use crate::file_io::genbank; const SOURCE_DIR: &str = "data"; // struct FeatureMapItem { // feature_name: String, // feature_type: FeatureType, // seq: Seq, // } fn collect_files_in_directory(dir: &Path) -> Vec<PathBuf> { let mut files = Vec::new(); if dir.is_dir() { for entry in fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if path.is_file() { files.push(path); } } } files } /// Combine feature maps that have identical sequences. fn consolidate(feature_map: &[FeatureMapItem]) -> Vec<FeatureMapItem> { let mut result = Vec::new(); result } fn main() { // todo: all files let files_genbank = collect_files_in_directory(&PathBuf::from_str(SOURCE_DIR).unwrap()); let files_snapgene = []; let mut feature_maps = Vec::new(); for file in files_genbank { let path = PathBuf::from_str(file).unwrap(); if let Ok(data) = genbank::import_genbank(&path) { for feature in &data.features { feature_maps.push({ FeatureMapItem { name: feature.name.clone(), feature_type: feature.feature_type, seq: data.seq[feature.range.0 - 1..feature.range.1], } }) } } } // todo: SQlite DB? }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/save_compat.rs
src/save_compat.rs
//! This module contains archived state structs used to open saves from previous versions //! of this program, and convert them to the latest version.
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/main.rs
src/main.rs
// Disables the terminal window. Use this for releases, and disable when debugging. #![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] // todo: Build a database of feature sequences. You can find GenBank etc files online (addGene, and other sources) // todo: and parse common features. // todo: Break out Generic into its own mod? // todo: // Focus on tools that allow you to conveniently design plasmid seqs based on source vectors, REs etc. It will make primers, // choose how to combine sequences etc. so, more towards realistic, product-first workflows. // // This will make more sense when you are designing new products. // For example: consider a lib of Addgene's generic vectors for E. Coli. // // The input: your target product: Output: as much we can automate as possible. // Reading frame: Guess the frame, and truncate the start based on CodingRegion and Gene feature types? use std::{env, path::PathBuf, str::FromStr}; use bincode::{Decode, Encode}; use cloning::CloningInsertData; use copypasta::ClipboardProvider; use eframe::{ self, egui::{self}, }; use file_io::save::{QUICKSAVE_FILE, load_import}; use gui::navigation::{Page, PageSeq}; use na_seq::{AaIdent, Nucleotide, Seq, restriction_enzyme::RestrictionEnzyme}; use state::State; use crate::{ backbones::BackboneFilters, file_io::{FileDialogs, save::DEFAULT_PREFS_FILE}, gui::{ WINDOW_HEIGHT, WINDOW_WIDTH, navigation::{PageSeqTop, Tab}, }, misc_types::{FeatureDirection, FeatureType}, pcr::PcrUi, primer::TM_TARGET, util::{RangeIncl, get_window_title}, }; mod alignment; mod alignment_map; mod backbones; mod cloning; mod external_websites; mod feature_db_load; mod file_io; mod gui; mod melting_temp_calcs; mod misc_types; mod pcr; mod portions; mod primer; mod primer_metrics; mod protein; mod reading_frame; mod save_compat; mod solution_helper; mod state; mod tags; mod toxic_proteins; mod util; type Color = (u8, u8, u8); // RGB // todo: Eventually, implement a system that automatically checks for changes, and don't // todo save to disk if there are no changes. const PREFS_SAVE_INTERVAL: u64 = 60; // Save user preferences this often, in seconds. #[derive(Default, Encode, Decode)] struct StateFeatureAdd { // This is in 1-based indexing. start_posit: usize, end_posit: usize, feature_type: FeatureType, direction: FeatureDirection, label: String, color: Option<Color>, } #[derive(Clone, Encode, Decode)] /// This Ui struct is used to determine which items on the sequence and map views to show and hide. struct SeqVisibility { /// Show or hide restriction enzymes from the sequence view. show_res: bool, /// Show and hide primers on show_primers: bool, /// todo: Show and hide individual features? show_features: bool, show_reading_frame: bool, } impl Default for SeqVisibility { fn default() -> Self { Self { show_res: true, show_primers: true, show_features: true, show_reading_frame: false, } } } /// UI state for restriction enzymes. pub struct ReUi { /// Inner: RE name /// todo: This is a trap for multiple tabs. // res_selected: Vec<String>, res_selected: Vec<RestrictionEnzyme>, /// Which tabs' sequences to digest. Note that the index of this vec doesn't matter; the values, which /// point to indices elsewhere, does. tabs_selected: Vec<usize>, unique_cutters_only: bool, /// No blunt ends; must produce overhangs. sticky_ends_only: bool, /// Only show REs that are present in at least two sequences. multiple_seqs: bool, } impl Default for ReUi { fn default() -> Self { Self { res_selected: Default::default(), tabs_selected: Default::default(), unique_cutters_only: true, sticky_ends_only: false, multiple_seqs: true, } } } /// Values defined here generally aren't worth saving to file etc. struct StateUi { // todo: Make separate primer cols and primer data; data in state. primer_cols are pre-formatted // todo to save computation. page: Page, page_seq: PageSeq, page_seq_top: PageSeqTop, seq_input: String, // todo: Consider moving this to volatile. pcr: PcrUi, feature_add: StateFeatureAdd, // primer_selected: Option<usize>, // primer page only. feature_hover: Option<usize>, // todo: Apply similar enum logic to selection: Allow Primer::, Feature::, or None:: selected_item: Selection, seq_visibility: SeqVisibility, hide_map_feature_editor: bool, /// Mouse cursor cursor_pos: Option<(f32, f32)>, /// Mouse cursor cursor_seq_i: Option<usize>, file_dialogs: FileDialogs, /// Show or hide the field to change origin show_origin_change: bool, new_origin: usize, /// Text-editing cursor. Used for editing on the sequence view. Chars typed /// will be inserted after this index. This index is 0-based. text_cursor_i: Option<usize>, /// We store if we've clicked somewhere separately from the action, as getting a sequence index /// from cursor positions may be decoupled, and depends on the view. click_pending_handle: bool, /// We use this for selecting features from the seq view dblclick_pending_handle: bool, cloning_insert: CloningInsertData, /// Volatile; computed dynamically based on window size. nt_chars_per_row: usize, search_input: String, /// Used to trigger a search focus on hitting ctrl+f highlight_search_input: bool, /// Activated when the user selects the search box; disables character insertion. text_edit_active: bool, /// This is used for selecting nucleotides on the sequence viewer. dragging: bool, /// 1-based indexing. text_selection: Option<RangeIncl>, quick_feature_add_name: String, quick_feature_add_dir: FeatureDirection, // todo: Protein ui A/R aa_ident_disp: AaIdent, pdb_error_received: bool, re: ReUi, backbone_filters: BackboneFilters, seq_edit_lock: bool, ab1_start_i: usize, } impl Default for StateUi { fn default() -> Self { Self { page: Default::default(), page_seq: Default::default(), page_seq_top: Default::default(), seq_input: Default::default(), pcr: Default::default(), feature_add: Default::default(), feature_hover: Default::default(), selected_item: Default::default(), seq_visibility: Default::default(), hide_map_feature_editor: true, cursor_pos: Default::default(), cursor_seq_i: Default::default(), file_dialogs: Default::default(), show_origin_change: Default::default(), new_origin: Default::default(), text_cursor_i: Some(0), click_pending_handle: Default::default(), dblclick_pending_handle: Default::default(), cloning_insert: Default::default(), nt_chars_per_row: Default::default(), search_input: Default::default(), highlight_search_input: Default::default(), text_edit_active: Default::default(), dragging: Default::default(), text_selection: Default::default(), quick_feature_add_name: Default::default(), quick_feature_add_dir: Default::default(), aa_ident_disp: AaIdent::OneLetter, pdb_error_received: false, re: Default::default(), backbone_filters: Default::default(), seq_edit_lock: true, ab1_start_i: Default::default(), } } } #[derive(Clone, Copy, PartialEq, Debug, Encode, Decode)] pub enum Selection { Feature(usize), // index Primer(usize), None, } impl Default for Selection { fn default() -> Self { Self::None } } fn main() { let mut state = State::default(); // todo: Temp to test BAM // let am = alignment_map::import(&PathBuf::from_str("../../Desktop/test.bam").unwrap()).unwrap(); // println!("Alignment map loaded: {:?}", am); state.load_prefs(&PathBuf::from_str(DEFAULT_PREFS_FILE).unwrap()); // Initial load hierarchy: // - Path argument (e.g. file association) // - Last opened files // - Quicksave let mut loaded_from_arg = false; let (path, window_title_initial) = { let mut p = PathBuf::from_str(QUICKSAVE_FILE).unwrap(); // Windows and possibly other operating systems, if attempting to use your program to natively // open a file type, will use command line arguments to indicate this. Determine if the program // is being launched this way, and if so, open the file. let args: Vec<String> = env::args().collect(); if args.len() > 1 { let temp = &args[1]; p = PathBuf::from_str(temp).unwrap(); loaded_from_arg = true; } let window_title = get_window_title(&p); (p, window_title) }; let mut prev_paths_loaded = false; for tab in &state.tabs_open { if tab.path.is_some() { prev_paths_loaded = true; } } // todo: Consider a standalone method for loaded-from-arg, // Load from the argument or quicksave A/R. if loaded_from_arg || !prev_paths_loaded { println!("Loading from quicksave or arg: {:?}", path); if let Some(loaded) = load_import(&path) { state.load(&loaded); } } state.sync_seq_related(None); state.reset_selections(); let icon_bytes: &[u8] = include_bytes!("resources/icon.png"); let icon_data = eframe::icon_data::from_png_bytes(icon_bytes); let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT]) .with_icon(icon_data.unwrap()), ..Default::default() }; eframe::run_native( &window_title_initial, options, Box::new(|_cc| Ok(Box::new(state))), ) .unwrap(); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/reading_frame.rs
src/reading_frame.rs
use std::fmt::Display; use bincode::{Decode, Encode}; use na_seq::{ Nucleotide, Nucleotide::{A, G, T}, Seq, seq_complement, }; use crate::util::RangeIncl; const START_CODON: [Nucleotide; 3] = [A, T, G]; pub const STOP_CODONS: [[Nucleotide; 3]; 3] = [[T, A, A], [T, A, G], [T, G, A]]; /// Of the 6 possible reading frames. #[derive(Clone, Copy, PartialEq, Debug, Encode, Decode)] pub enum ReadingFrame { /// Forward, with 0 offset (This pattern applies for all variants) Fwd0, Fwd1, Fwd2, Rev0, Rev1, Rev2, } impl ReadingFrame { pub fn offset(&self) -> usize { match self { Self::Fwd0 | Self::Rev0 => 0, Self::Fwd1 | Self::Rev1 => 1, Self::Fwd2 | Self::Rev2 => 2, } } pub fn is_reverse(&self) -> bool { // todo: Enum !matches!(self, Self::Fwd0 | Self::Fwd1 | Self::Fwd2) } /// Get a seqeuence of the full sequence in the appropriate direction, and with the appropriate offset. /// The result will always start in frame. It will be trimmed if offset > 0. /// todo: THis makes a clone. Can we instead do a slice? pub fn arrange_seq(&self, seq: &[Nucleotide]) -> Seq { let offset = self.offset(); if self.is_reverse() { seq_complement(seq)[offset..].to_vec() } else { seq[offset..].to_vec() } } } impl Default for ReadingFrame { fn default() -> Self { Self::Fwd0 } } impl Display for ReadingFrame { /// For use with selector buttons. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Fwd0 => "Fwd 0", Self::Fwd1 => "Fwd 1", Self::Fwd2 => "Fwd 2", Self::Rev0 => "Rev 0", Self::Rev1 => "Rev 1", Self::Rev2 => "Rev 2", } .to_owned(); write!(f, "{}", str) } } #[derive(Debug, Clone, Encode, Decode)] pub struct ReadingFrameMatch { pub frame: ReadingFrame, /// Indices are respective to the non-complementary seq, for both forward and reverse reading frames. pub range: RangeIncl, } /// Find coding regions in a sequence, given a reading frame. pub fn find_orf_matches(seq: &[Nucleotide], orf: ReadingFrame) -> Vec<ReadingFrameMatch> { let mut result = Vec::new(); let offset = orf.offset(); let seq_len_full = seq.len(); if seq_len_full < 3 { return result; } let seq_ = orf.arrange_seq(&seq); let len = seq_.len(); let mut frame_open = None; // Inner: Start index. for i_ in 0..len / 3 { let i = i_ * 3; // The actual sequence index. let nts = &seq_[i..i + 3]; if frame_open.is_none() && nts == START_CODON { frame_open = Some(i); // } else if frame_open.is_some() && stop_codons.contains(nts.try_into().unwrap()) { } else if frame_open.is_some() && (STOP_CODONS.contains(nts.try_into().unwrap()) || seq_len_full - i <= 3) { // If we reach the end of the sequence, consider it closed. // todo: Handle circular around the origin. Ie, don't auto-close in that case. // + 1 for our 1-based seq name convention. // This section's a bit hairy; worked by trial and error. Final indices are respective to // the non-complementary seq, for both forward and reverse reading frames. let range = if !orf.is_reverse() { // todo: We still have wonkiness here. // RangeIncl::new(frame_open.unwrap() + 1 + offset, i + 2 + offset) RangeIncl::new(frame_open.unwrap() + 1 + offset, i + 3 + offset) } else { RangeIncl::new( seq_len_full - (i + 2 + offset), seq_len_full - (frame_open.unwrap() + offset) - 1, ) }; result.push(ReadingFrameMatch { frame: orf, range }); frame_open = None; } } result }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/cloning.rs
src/cloning.rs
//! Used for a semi-automated cloning process that chooses a suitable backbone and restriction enzymes //! or primers. //! //! todo: Make sure you're QCing and filtering for expression system. //! //! todo: Allow users to enter custom backbones. use na_seq::{ AminoAcid, CodingResult, Nucleotide, Seq, insert_into_seq, ligation::{filter_multiple_seqs, filter_unique_cutters, find_common_res}, restriction_enzyme::{ReMatch, RestrictionEnzyme, find_re_matches}, seq_to_str_lower, }; use crate::{ Selection, backbones::Backbone, file_io::GenericData, gui::navigation::{Page, PageSeq}, misc_types::{Feature, FeatureDirection, FeatureType}, primer::{Primer, make_cloning_primers}, state::State, util::RangeIncl, }; /// Include this many nucleotides to the left, and right of each insert, when searching for RE sites. /// note: 4-6 nucleotides may be an ideal buffer. Note that this should be conservatively long. pub const RE_INSERT_BUFFER: usize = 22; /// Attempt to insert the sequence this far downstream of the RBS. 5-10 is ideal. pub const RBS_BUFFER: usize = 7; pub const RBS_BUFFER_MIN: isize = 4; pub const RBS_BUFFER_MAX: isize = 11; pub struct CloningState { pub backbone_selected: BackboneSelected, /// Note: This is only used currently if using the opened file as the BB; otherwise /// we use a ref to the library. pub backbone: Option<Backbone>, // todo: Other options: Store a ref; use in bb_selected instead of an index. pub res_common: Vec<RestrictionEnzyme>, pub re_matches_vec_common: Vec<ReMatch>, pub re_matches_insert_common: Vec<ReMatch>, pub status: CloneStatus, // todo: Should this be an option? pub insert_loc: usize, /// Data for the insert. For example, used to draw its linear sequence. pub data_insert: Option<GenericData>, // note: This one may make more sense as a UI var. pub remove_stop_codons: bool, /// Work-in-progress cloning product sequence. pub product_seq: Seq, pub product_primers: Vec<Primer>, } impl Default for CloningState { fn default() -> Self { Self { insert_loc: 1, backbone_selected: Default::default(), backbone: Default::default(), res_common: Default::default(), re_matches_vec_common: Default::default(), re_matches_insert_common: Default::default(), status: Default::default(), data_insert: Default::default(), // backbone_data: Default::default(), remove_stop_codons: Default::default(), product_seq: Default::default(), product_primers: Vec::new(), } } } impl CloningState { /// Run this whenever something relevant in the cloning state changes. (e.g. selected a new backbone, /// a new insert location etc.) It synchronizes cloning product, validation, and RE matches. pub fn sync( &mut self, // mut seq_insert: &[Nucleotide], seq_insert: &mut Seq, backbone_lib: &[Backbone], re_lib: &[RestrictionEnzyme], ) { println!("Syncing cloning state..."); // let backbone = self.get_backbone(backbone_lib); // todo: DRy with `get_backbone`, due to borrow errors. :( let backbone = match self.backbone_selected { BackboneSelected::Library(i) => { if i >= backbone_lib.len() { eprintln!("Invalid index in backbone lib"); None } else { Some(&backbone_lib[i]) } } BackboneSelected::Opened => match self.backbone.as_ref() { Some(i) => Some(i), None => None, }, }; if let Some(backbone) = backbone { // todo: Put back. Getting a hang when this is there, eg from clicking auto pick insert loc. // ( // self.res_common, // self.re_matches_vec_common, // self.re_matches_insert_common, // ) = find_re_candidates(&backbone, seq_insert, &re_lib); self.product_seq = backbone.seq.clone(); if seq_insert.len() < 3 { return; } // Trim off the stop codon at the end of the insert, A/R. This is quite specific. let insert_len = seq_insert.len(); if self.remove_stop_codons && CodingResult::from_codons(seq_insert[insert_len - 3..].try_into().unwrap()) == CodingResult::StopCodon { *seq_insert = seq_insert[..insert_len - 3].try_into().unwrap(); } insert_into_seq(&mut self.product_seq, seq_insert, self.insert_loc).ok(); self.status = CloneStatus::new( &backbone, self.insert_loc, seq_insert.len(), &self.product_seq, ); } } pub fn get_backbone<'a>(&'a self, lib: &'a [Backbone]) -> Option<&'a Backbone> { match self.backbone_selected { BackboneSelected::Library(i) => { if i >= lib.len() { eprintln!("Invalid index in backbone lib"); None } else { Some(&lib[i]) } } BackboneSelected::Opened => Some(self.backbone.as_ref().unwrap()), } } } #[derive(Clone, Copy, PartialEq)] pub enum BackboneSelected { /// A backbone from our library; index. Library(usize), /// The current tab. Opened, // None, // todo: Rem this? } impl Default for BackboneSelected { fn default() -> Self { // Self::None Self::Opened } } #[derive(Clone, Copy, PartialEq)] pub enum Status { Pass, Fail, NotApplicable, } impl Default for Status { fn default() -> Self { Self::Fail } } #[derive(Default)] pub struct CloningInsertData { /// We use this list to store a list of features to clone an insert from, loaded from a file. pub features_loaded: Vec<Feature>, /// `cloning_ins_features_loaded` indexes reference this sequence. pub seq_loaded: Seq, pub feature_selected: Option<usize>, pub seq_insert: Seq, pub seq_input: String, pub show_insert_picker: bool, } /// Given a set of features and the sequence their ranges map to, set up our /// insert sequences. pub fn setup_insert_seqs(state: &mut State, features: Vec<Feature>, seq: Seq) { // todo: Unecessary cloning if loading from file. state.ui.cloning_insert.features_loaded = features; state.ui.cloning_insert.seq_loaded = seq; // Choose the initial insert as the CDS or gene with the largest len. let mut best = None; let mut best_len = 0; for (i, feature) in state.ui.cloning_insert.features_loaded.iter().enumerate() { let len = feature.len(state.generic[state.active].seq.len()); if (feature.feature_type == FeatureType::CodingRegion || feature.feature_type == FeatureType::Gene) && len > best_len { best_len = len; best = Some(i); } } if let Some(feat_i) = best { let feature = &state.ui.cloning_insert.features_loaded[feat_i]; if let Some(seq_this_ft) = feature.range.index_seq(&state.ui.cloning_insert.seq_loaded) { state.ui.cloning_insert.feature_selected = best; state.ui.cloning_insert.seq_insert = seq_this_ft.to_owned(); state.ui.cloning_insert.seq_input = seq_to_str_lower(seq_this_ft); } } } /// Create a new tab containing of the cloning product. /// Optionally allow passing a new set of generic data to use, eg a backbone. If not present, /// the current tab's will be used. pub fn make_product_tab(state: &mut State, generic: Option<GenericData>) { // Note: This segment is almost a duplicate of `State::add_tab`, but retaining the generic data. let generic = match generic { Some(gen_) => gen_, None => state.generic[state.active].clone(), }; state.generic.push(generic); // state // .ion_concentrations = state.ion_concentrations[state.active].clone()); // state.file_active = None; state.portions.push(Default::default()); state.volatile.push(Default::default()); state.tabs_open.push(Default::default()); state.ab1_data.push(Default::default()); state.active = state.generic.len() - 1; // Make sure to create cloning primers before performing the insert, or the result will be wrong. make_cloning_primers(state); // todo: Unecessary clone? Due to borrow rules. let mut insert = state.ui.cloning_insert.seq_insert.clone(); state.insert_nucleotides(&insert, state.cloning.insert_loc); let label = match state.ui.cloning_insert.feature_selected { Some(i) => state.ui.cloning_insert.features_loaded[i].label.clone(), None => "Cloning insert".to_owned(), }; // todo: Eventually, we'll likely be pulling in sequences already associated with a feature; // todo: Use the already existing data instead. state.generic[state.active].features.push(Feature { range: RangeIncl::new( state.cloning.insert_loc, state.cloning.insert_loc + insert.len() - 1, ), label, feature_type: FeatureType::CodingRegion, direction: FeatureDirection::Forward, ..Default::default() }); "Cloning product".clone_into(&mut state.generic[state.active].metadata.plasmid_name); state.ui.page = Page::Map; state.ui.page_seq = PageSeq::View; state.ui.selected_item = Selection::Feature(state.generic[state.active].features.len() - 1); } /// Check if the (eg His) tag is in frame with the start of the coding region, and that there is /// no stop codon between the end of the coding region, and start of the sequence. /// /// We assume, for now, that the insert location is the start of a coding region. /// Note: `his_tag` here must have already been shifted based on the insert. /// todo: This assumption may not be always valid! // fn tag_in_frame(backbone: &Backbone, coding_region_start: usize, insert_len: usize) -> Status { fn tag_in_frame( seq_product: &[Nucleotide], his_tag: &Option<RangeIncl>, coding_region_start: usize, ) -> Status { if seq_product.is_empty() { eprintln!("Error checking tag frame: Product sequence is empty"); return Status::NotApplicable; } match his_tag { Some(tag_range) => { let tag_start = tag_range.start; let cr_start = coding_region_start % seq_product.len(); // // let (tag_start, cr_start) = match backbone.direction { // PrimerDirection::Forward => { // // (tag_range.start + insert_len, cr_start) // } // // todo: QC this. // PrimerDirection::Reverse => { // let tag_end = tag_range.end % backbone.seq.len(); // (coding_region_start, tag_end + insert_len) // } // }; if cr_start > tag_start { eprintln!( "Error with insert loc and tag end. Coding region start: {cr_start}, tag start: {tag_start}" ); return Status::Fail; } println!("Tag: {tag_start}, CR: {coding_region_start}"); // todo: Helper fn for this sort of check in general? // If there is a stop codon between the end of the sequence and the for i in (cr_start..tag_start).step_by(3) { if i + 2 >= seq_product.len() { eprintln!("Error: Invalid backbone seq in his check"); return Status::Fail; } if let CodingResult::StopCodon = CodingResult::from_codons([ // Offset for 1-based indexing. seq_product[i - 1], seq_product[i + 0], seq_product[i + 1], ]) { // todo: Confirm this is the full seq with insert adn vec. println!("Stop codon between seq start and his tag found at index {i}"); // todo temp return Status::Fail; } } let dist_from_start_codon = tag_start - cr_start; if dist_from_start_codon % 3 == 0 { Status::Pass } else { Status::Fail } } None => Status::NotApplicable, } } /// For a given insert and vector, find suitable restriction enzymes for cloning. /// Make sure that the insert sequence is properly buffered to allow for RE matching outside /// of the coding region (etc)'s range, upstream of this. /// todo: Fow now, we limit our options to unique-match, single-cutters. /// /// Returns REs, matches vector, matches insert. pub fn find_re_candidates<'a>( backbone: &Backbone, seq_insert: &[Nucleotide], // re_match_sets: &[&[ReMatch]], // insert_tab: usize, // insert_range: RangeIncl, lib: &'a [RestrictionEnzyme], // ) -> Vec<&'a RestrictionEnzyme> { ) -> (Vec<RestrictionEnzyme>, Vec<ReMatch>, Vec<ReMatch>) { // Note: The first part of this function is similar to how we filter REs for digest on the digest/ligation page. let matches_insert = find_re_matches(seq_insert, lib); let matches_backbone = find_re_matches(&backbone.seq, lib); let re_match_set = [&matches_insert, &matches_backbone]; // Set up our initial REs: Ones that match both the backbone, and insert. (anywhere, for now) let mut result = find_common_res(&re_match_set, lib, true); // For now, we are always filtering by these, as well as setting sticky ends only. filter_multiple_seqs(&mut result, &re_match_set, lib); filter_unique_cutters(&mut result, &re_match_set, lib); // Filter for REs that are at an appropriate place on the insert. let res = result.into_iter().map(|r| r.clone()).collect(); let mut matches_vector_common = Vec::new(); let mut matches_insert_common = Vec::new(); for match_insert in &matches_insert { for match_bb in &matches_backbone { if match_insert.lib_index == match_bb.lib_index { matches_vector_common.push(match_bb.clone()); matches_insert_common.push(match_insert.clone()); } } } (res, matches_vector_common, matches_insert_common) } /// Validation checks for cloning. #[derive(Default)] pub struct CloneStatus { pub rbs_dist: Status, pub downstream_of_promoter: Status, pub upstream_of_terminator: Status, // todo: Check for terminator? pub direction: Status, pub tag_frame: Status, // pub primer_quality: Status, // pub re_dist: Status, } impl CloneStatus { pub fn new( backbone: &Backbone, insert_loc: usize, insert_len: usize, seq_product: &[Nucleotide], ) -> Self { let rbs_dist = match backbone.rbs { Some(rbs) => { let dist = insert_loc as isize - rbs.end as isize; // todo: Handle wraps. if dist >= RBS_BUFFER_MIN && dist <= RBS_BUFFER_MAX { Status::Pass } else { Status::Fail } } None => Status::NotApplicable, }; // todo: Handle wraps. let downstream_of_promoter = match backbone.promoter { Some(p) => { if insert_loc > p.end { Status::Pass } else { Status::Fail } } None => Status::NotApplicable, }; let upstream_of_terminator = match backbone.terminator { Some(p) => { if insert_loc < p.end { Status::Pass } else { Status::Fail } } None => Status::NotApplicable, }; let direction = Status::Pass; // todo // let tag_frame = tag_in_frame(&backbone, insert_loc, insert_len); // Note: We are assuming for now, that the coding region start/frame, is the insert location. let his_tag_shifted = match backbone.his_tag { Some(tag) => Some(RangeIncl::new(tag.start + insert_len, tag.end + insert_len)), None => None, }; let tag_frame = tag_in_frame(seq_product, &his_tag_shifted, insert_loc); Self { rbs_dist, downstream_of_promoter, upstream_of_terminator, direction, tag_frame, } } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/primer_metrics.rs
src/primer_metrics.rs
//! This module handles assessing various primer metrics, such as GC concentration, and repeats. use bincode::{Decode, Encode}; use lin_alg::map_linear; use na_seq::{ Nucleotide, Nucleotide::{C, G}, calc_gc, }; use crate::{ TM_TARGET, melting_temp_calcs, primer::{IonConcentrations, MIN_PRIMER_LEN, Primer, TuneSetting}, util::remove_duplicates, }; /// Metrics related to primer quality. #[derive(Clone, Debug, Default, Encode, Decode)] pub struct PrimerMetrics { /// C pub melting_temp: f32, /// 0. to 1. pub gc_portion: f32, /// How many G and C nts are in the last 5 (3' end) nts of the sequence. pub gc_3p_count: u8, pub self_end_dimer: u8, pub seq_len: usize, pub repeats: u8, pub tm_score: f32, pub gc_score: f32, pub gc_3p_score: f32, pub len_score: f32, pub dimer_score: f32, /// https://www.benchling.com/primer-design-for-pcr /// "Avoid runs of four or more of a single base (e.g., ACCCCC), or four or more dinucleotide /// repeats (e.g., ATATATATAT) as they will cause mispriming." pub repeats_score: f32, /// This is a weighted overall score. pub quality_score: f32, } impl PrimerMetrics { /// Return a quality score, on a scale from 0 to 1. /// `dual_end` indicates if this is a double-end-tunable primer, which generally means a cloning /// insert primer. This affects the len-based score. pub fn update_scores(&mut self, dual_end: bool) { const GC_TARGET: f32 = 0.5; // todo: Do these weights have to add up to 1/total? const WEIGHT_TM: f32 = 1.; const WEIGHT_GC: f32 = 1.; const WEIGHT_STAB: f32 = 1.; // const WEIGHT_COMPLEXITY: f32 = 1.; const WEIGHT_DIMER: f32 = 1.; const WEIGHT_LEN: f32 = 1.5; const WEIGHT_REPEATS: f32 = 0.5; // todo: Instead of closeness to 59, should it be >54?? // Also: 50-60C. And within 5C of the complement primer. self.tm_score = map_linear((self.melting_temp - TM_TARGET).abs(), (0., 18.), (1., 0.)); self.tm_score = self.tm_score.clamp(0., 1.); // This is currently a linear map, between 0 and 1. self.gc_score = 1. - (self.gc_portion - GC_TARGET).abs() * 2.; // todo: This is not sophisticated enough, but is a start; we need to assess the length on both // todo sides of the anchor individually. self.len_score = if dual_end { let max_falloff_dist = 16.; let ideal = 42.; match self.seq_len { 36..=48 => 1., _ => { // More gentle penalty for long primers. let max_falloff = if self.seq_len > ideal as usize { ideal + max_falloff_dist } else { ideal - max_falloff_dist }; map_linear( (ideal - self.seq_len as f32).abs(), (0., max_falloff), (1., 0.), ) } } } else { let max_falloff_dist = 8.; let ideal = 21.; // todo: DRy with above. match self.seq_len { 18..=24 => 1., _ => { // More gentle penalty for long primers. let max_falloff = if self.seq_len > ideal as usize { ideal + max_falloff_dist } else { ideal - max_falloff_dist }; map_linear( (ideal - self.seq_len as f32).abs(), (0., max_falloff), (1., 0.), ) } } }; // Sources differ on if 4 is an ok value. AmplifX calls it "good"; [the DNA universe](https://the-dna-universe.com/2022/09/05/primer-design-guide-the-top-5-factors-to-consider-for-optimum-performance/) // considers it to be bad. self.gc_3p_score = match self.gc_3p_count { 0 | 1 => 0., 2 => 1., 3 => 1., 4 => 0.5, 5 => 0., _ => unreachable!(), }; let repeats = if dual_end { self.repeats / 2 // todo: odd-number rounding } else { self.repeats }; self.repeats_score = match repeats { 0 => 1., 1 => 0.8, 2 => 0.6, 3 => 0.3, 4 => 0.2, _ => 0., }; self.quality_score = (WEIGHT_TM * self.tm_score + WEIGHT_GC * self.gc_score + WEIGHT_STAB * self.gc_3p_score // + WEIGHT_COMPLEXITY * self.complexity_score + WEIGHT_DIMER * self.dimer_score + WEIGHT_LEN * self.len_score + WEIGHT_REPEATS * self.repeats_score) / 6. } } impl Primer { /// Calculate melting temperature (TM), in C. /// /// [Calc data from AmplifX](https://inp.univ-amu.fr/en/amplifx-manage-test-and-design-your-primers-for-pcr): /// "TM = 81.5 +16.6 X log10([Na+]+[K+])+0.41 x(%GC) - 675/N (with default values: [ Na+]+[K+]=0.05 (50mM)) /// /// "the most precise... "bases stacking method” : TM=dH/(dS+0.368xNxln[Na+]+ R /// x ln[Primer]/4) with R=1.987 and the different dH and dS taken in [Santalucia J PNAS 95 pp1460-1465 (1998)]" /// /// https://primerexplorer.jp/e/v4_manual/03.html (Different formula) /// /// https://www.rosalind.bio/en/knowledge/what-formula-is-used-to-calculate-tm /// Come up with something better A/R /// "ASSUMPTIONS: /// Equations above assume that the annealing occurs under the standard conditions of 50 nM /// primer, 50 mM Na+, and pH 7.0." /// /// We use the "bases stacking method" as defined hte Amplifx guide above. /// /// See [The BioPython MeltingTemp module](https://github.com/biopython/biopython/blob/master/Bio/SeqUtils/MeltingTemp.py) pub fn calc_tm(&self, ion_concentrations: &IonConcentrations) -> f32 { // const NAP_K_P: f32 = 0.05; // // // TM = 81.5 +16.6 X log10([Na+]+[K+])+0.41 x(%GC) - 675/N // // 81.5 + 16.6 * NAP_K_P.log10() + 0.41 * self.calc_gc() * 100. // // - 675. / (self.sequence.len() as f32) // // const dH: f32 = 1. // todo // const dS: f32 = 1. // todo // const R: f32 = 1.987; // Universal gas constant (Cal/C * Mol) // let N = self.sequence.len(); // // dH / (dS + 0.368 * N * NAP.ln() + R * primer.ln() / 4.) melting_temp_calcs::calc_tm(&self.sequence, ion_concentrations).unwrap_or(0.) } /// This is a metric known as 3' end stability. Return the number of Gs and Cs in the last 5 bases. /// 2-4 is ideal. (Other sources, 2-3, with 4 being too many). 1 or 5 is considered suboptimal. pub fn count_3p_g_c(&self) -> u8 { let mut result = 0; let len = self.sequence.len(); let last_5 = if len > 5 { self.sequence.split_at(len - 5).1 } else { &self.sequence[..] }; for nt in last_5 { if *nt == C || *nt == G { result += 1 } } result } /// Calculate self end dimer score. (Details on what this means here) /// /// http://www.premierbiosoft.com/tech_notes/PCR_Primer_Design.html /// "A primer self-dimer is formed by intermolecular interactions between the two (same sense) /// primers, where the primer is homologous to itself. Generally a large amount of primers are /// used in PCR compared to the amount of target gene. When primers form intermolecular dimers /// much more readily than hybridizing to target DNA, they reduce the product yield. Optimally a 3' /// end self dimer with a ΔG of -5 kcal/mol and an internal self dimer with a ΔG of -6 kcal/mol is /// tolerated generally." pub fn calc_self_end_dimer(&self) -> u8 { 0 } /// Calculate how many single or double nucleotide sequences exist that are of len 4 or more of the /// same nt or nt pair respectively. It currently doesn't differentiate between 4, and more. /// Also includes repeats of a set of 3 nucleotides anywhere in the seq. pub fn calc_repeats(&self) -> u8 { if self.sequence.len() < 4 { return 0; } let mut result = 0; result += single_nt_repeats(&self.sequence) as u8; result += double_nt_repeats(&self.sequence) as u8; result += triplet_repeats(&self.sequence) as u8; result } /// Calculate all primer metrics. /// todo: methods on Metrics instead? pub fn calc_metrics(&self, ion_concentrations: &IonConcentrations) -> Option<PrimerMetrics> { if self.sequence.len() < MIN_PRIMER_LEN { return None; } let mut result = PrimerMetrics { melting_temp: self.calc_tm(ion_concentrations), gc_portion: calc_gc(&self.sequence), seq_len: self.sequence.len(), gc_3p_count: self.count_3p_g_c(), // complexity: self.calc_complexity(), self_end_dimer: self.calc_self_end_dimer(), repeats: self.calc_repeats(), ..Default::default() }; let dual_ended = matches!(self.volatile.tune_setting, TuneSetting::Both(_)); result.update_scores(dual_ended); Some(result) } } /// Count the number of single-nucleotide repeats in a sequence. Counts when it's > 4. fn single_nt_repeats(seq: &[Nucleotide]) -> u16 { let mut result = 0; let mut prev_nt = seq[0]; let mut repeat_len = 1; // Counts the char. for nt in seq { if *nt == prev_nt { repeat_len += 1; if repeat_len >= 4 { result += 1; repeat_len = 1; } } else { repeat_len = 1; } prev_nt = *nt; } result } /// Count the number of double-nucleotide repeats in a sequence. Counts when it's > 4. eg `atatatat` fn double_nt_repeats(seq: &[Nucleotide]) -> u16 { let mut result = 0; let mut prev_nt = (seq[0], seq[1]); let mut repeat_len = 1; // Counts the char. for i in 0..seq.len() / 2 - 1 { // todo: Incomplete: Need to do the same offset by one. let nts = (seq[i * 2], seq[(i * 2) + 1]); if nts == prev_nt { repeat_len += 1; if repeat_len >= 4 { result += 1; repeat_len = 1; } } else { repeat_len = 1; } prev_nt = nts; } result } /// Count the number of times a set of three nucleotides is repeated in a sequence. /// This does not have to be adjacent. fn triplet_repeats(seq: &[Nucleotide]) -> u16 { let mut triplets = Vec::new(); for (i, nt) in seq.iter().enumerate() { if i == seq.len() - 2 { break; } triplets.push((i, nt, seq[i + 1], seq[i + 2])); } let mut triplet_repeat_seqs = Vec::new(); for (i, nt) in seq.iter().enumerate() { if i == seq.len() - 2 { break; } let triplet_this = (nt, seq[i + 1], seq[i + 2]); for triplet_other in &triplets { if triplet_this == (triplet_other.1, triplet_other.2, triplet_other.3) && i != triplet_other.0 { // Dount count each additional nt match beyond 3 as a new repeat if i >= 3 && triplet_other.0 >= 3 && seq[i - 1] == seq[triplet_other.0 - 1] { continue; } triplet_repeat_seqs.push(triplet_this); } } } triplet_repeat_seqs = remove_duplicates(triplet_repeat_seqs); triplet_repeat_seqs.len() as u16 }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/genbank.rs
src/file_io/genbank.rs
//! Parse and write GenBank files. This converts between this format for sequences, features, //! primers, notes etc., and our own equivalents. We use the [gb_io](https://docs.rs/gb-io/latest/gb_io) //! library. //! //! (NIH article on GenBank)[https://www.ncbi.nlm.nih.gov/genbank/] use std::{ fs::File, io::{self, ErrorKind}, path::Path, }; use gb_io::{ self, reader::SeqReader, seq::{After, Before, Location}, writer::SeqWriter, }; use na_seq::{Nucleotide, SeqTopology, seq_complement, seq_to_u8_lower}; use crate::{ file_io::{GenericData, get_filename}, misc_types::{Feature, FeatureDirection, FeatureType, Metadata, Reference}, primer::{Primer, PrimerData, PrimerDirection, PrimerMatch}, util::RangeIncl, }; /// Read a file in the GenBank format. /// [Rust docs ref of fields](https://docs.rs/gb-io/latest/gb_io/seq/struct.Seq.html) pub fn import_genbank(path: &Path) -> io::Result<GenericData> { let file = File::open(path)?; // todo: This currently only handles a single sequene. It returns the first found. for seq in SeqReader::new(file) { let seq = seq.map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to get GenBank seq {e}"), ) })?; let mut seq_ = Vec::new(); for nt in &seq.seq { match Nucleotide::from_u8_letter(*nt) { Ok(n) => seq_.push(n), Err(_) => { eprintln!("Unexpected char in GenBank sequence: {:?}", nt); } } } let topology = match seq.topology { gb_io::seq::Topology::Linear => SeqTopology::Linear, gb_io::seq::Topology::Circular => SeqTopology::Circular, }; let (features, primers) = parse_features_primers(&seq.features, &seq_); let mut references = Vec::new(); for ref_ in &seq.references { references.push(Reference { description: ref_.description.clone(), authors: ref_.authors.clone(), consortium: ref_.consortium.clone(), title: ref_.title.clone(), journal: ref_.journal.clone(), pubmed: ref_.pubmed.clone(), // todo: Appears not to work remark: ref_.remark.clone(), }) } // todo: What is contig location? Do we need that? let (source, organism) = match seq.source { Some(src) => (Some(src.source), src.organism), None => (None, None), }; let date = if let Some(date) = seq.date { // Some(NaiveDate::from_ymd(date.year(), date.month(), date.day())) Some((date.year(), date.month() as u8, date.day() as u8)) } else { None }; let metadata = Metadata { plasmid_name: get_filename(path), date, comments: seq.comments.clone(), definition: seq.definition.clone(), molecule_type: seq.molecule_type.clone(), division: seq.division.clone(), accession: seq.accession.clone(), version: seq.version.clone(), keywords: seq.keywords.clone(), locus: seq.name.clone().unwrap_or_default(), source, organism, references, }; return Ok(GenericData { seq: seq_, topology, features, primers, metadata, }); } Err(io::Error::new( ErrorKind::InvalidData, "No GenBank sequences found", )) } /// Parse Genbank ranges. This is broken out into a separate function to allow for recursion. fn parse_ranges(location: &Location, direction: &mut FeatureDirection) -> Vec<RangeIncl> { match location { // gb_io seems to list the start of the range as 1 too early; compensate. Location::Range(start, end) => vec![RangeIncl::new(start.0 as usize + 1, end.0 as usize)], Location::Complement(inner) => match **inner { Location::Range(start, end) => { *direction = FeatureDirection::Reverse; vec![RangeIncl::new(start.0 as usize + 1, end.0 as usize)] } _ => { eprintln!("Unexpected gb_io compl range type: {:?}", location); vec![RangeIncl::new(1, 1)] } }, Location::Join(sub_locs) => { // Note: Recursion, with no safety. let mut result = Vec::new(); for sub_loc in sub_locs { result.extend(&parse_ranges(sub_loc, direction)); } result } _ => { eprintln!("Unexpected gb_io range type: {:?}", location); vec![RangeIncl::new(1, 1)] } } } /// Parse features and primers, from GenBank's feature list. fn parse_features_primers( features: &[gb_io::seq::Feature], seq: &[Nucleotide], ) -> (Vec<Feature>, Vec<Primer>) { let mut result_ft = Vec::new(); let mut primers = Vec::new(); let compl = seq_complement(seq); for feature in features { let feature_type = FeatureType::from_external_str(feature.kind.as_ref()); // We parse label from qualifiers. // I'm unsure how direction works in GenBank files. It appears it's some mix of the LEFT/RIGHT // qualifiers, feature type, and if the location is complement, or forward. let mut direction = FeatureDirection::None; let mut label = String::new(); // We map multiple ranges, eg in the case of a GenBank `join` range type, to multiple features, // as our features currently only support a single range. let mut ranges = parse_ranges(&feature.location, &mut direction); for v in feature.qualifier_values("label".into()) { v.clone_into(&mut label); break; } match feature_type { FeatureType::Primer => { if direction != FeatureDirection::Reverse { direction = FeatureDirection::Forward; } } FeatureType::CodingRegion => { // As CDS regions are always directional, if not identified as reverse due to the range // being in complement format, set it to forward. if direction == FeatureDirection::None { direction = FeatureDirection::Forward } } _ => (), } for v in feature.qualifier_values("direction".into()) { let v = v.to_lowercase(); if v == "right" { direction = FeatureDirection::Forward; break; } else if v == "left" { direction = FeatureDirection::Reverse; break; } } // Parse notes from qualifiers other than label and direction. // let mut notes = HashMap::new(); let mut notes = Vec::new(); for (qual_key, val) in &feature.qualifiers { if qual_key == "label" || qual_key == "direction" { continue; // We handle these separately. } if let Some(v) = val { // notes.insert(qual_key.to_string(), v.clone()); notes.push((qual_key.to_string(), v.clone())); } } // See note above about adding a feature (or primer) per GB range. for range in &mut ranges { // Passing through the origin, most likely. Loop around past the end. if range.end < range.start { *range = RangeIncl::new(range.start, seq.len() + range.end); } // GenBank stores primer bind sites (Which we treat as volatile), vice primer sequences. // Infer the sequence using the bind indices, and the main sequence. if feature_type == FeatureType::Primer { let sequence = match direction { FeatureDirection::Reverse => { let range = RangeIncl::new( seq.len() - (range.end - 1), seq.len() - (range.start - 1), ); range.index_seq(&compl).unwrap_or_default() } _ => range.index_seq(seq).unwrap_or_default(), } .to_vec(); // Perhaps improper way of storing primer descriptions let description = if notes.is_empty() { None } else { Some(notes[0].1.clone()) }; let volatile = PrimerData::new(&sequence); primers.push(Primer { sequence, name: label.clone(), description, volatile, }); continue; } result_ft.push(Feature { range: *range, feature_type, direction, label: label.clone(), color_override: None, notes: notes.clone(), }) } } (result_ft, primers) } /// Export our local state into the GenBank format. This includes sequence, features, and primers. pub fn export_genbank( data: &GenericData, primer_matches: &[(PrimerMatch, String)], path: &Path, ) -> io::Result<()> { let file = File::create(path)?; let mut gb_data = gb_io::seq::Seq::empty(); gb_data.seq = seq_to_u8_lower(&data.seq); gb_data.topology = match data.topology { SeqTopology::Circular => gb_io::seq::Topology::Circular, SeqTopology::Linear => gb_io::seq::Topology::Linear, }; for feature in &data.features { let mut qualifiers = Vec::new(); if !feature.label.is_empty() { qualifiers.push(("label".into(), Some(feature.label.clone()))) } for note in &feature.notes { qualifiers.push((note.0.to_owned().into(), Some(note.1.to_owned()))); } match feature.direction { FeatureDirection::Forward => { qualifiers.push(("direction".into(), Some("RIGHT".to_owned()))) } FeatureDirection::Reverse => { qualifiers.push(("direction".into(), Some("LEFT".to_owned()))) } _ => (), } let start: i64 = feature.range.start.try_into().unwrap(); let end: i64 = feature.range.end.try_into().unwrap(); let location = match feature.direction { FeatureDirection::Reverse => Location::Complement(Box::new(Location::Range( (start - 1, Before(false)), (end, After(false)), ))), _ => Location::Range( (start - 1, Before(false)), (feature.range.end.try_into().unwrap(), After(false)), ), }; gb_data.features.push(gb_io::seq::Feature { kind: feature.feature_type.to_external_str().into(), location, qualifiers, }); } for (prim_match, name) in primer_matches { // todo: qualifiers/notes DRY with features. let mut qualifiers = Vec::new(); if !name.is_empty() { qualifiers.push(("label".into(), Some(name.to_owned()))); } // todo: This is a sloppy way of accessing the primer. for primer in &data.primers { if primer.name == *name { if let Some(descrip) = &primer.description { qualifiers.push(("note".into(), Some(descrip.to_owned()))); } break; } } // todo: Location code is DRY with features. let start: i64 = prim_match.range.start.try_into().unwrap(); let location = match prim_match.direction { PrimerDirection::Forward => Location::Range( (start - 1, Before(false)), (prim_match.range.end.try_into().unwrap(), After(false)), ), PrimerDirection::Reverse => Location::Complement(Box::new(Location::Range( (start - 1, Before(false)), (prim_match.range.end.try_into().unwrap(), After(false)), ))), }; // todo: Make sure we're not getting a duplicate label. gb_data.features.push(gb_io::seq::Feature { kind: "primer_bind".into(), location, qualifiers, }); } let md = &data.metadata; gb_data.comments.clone_from(&md.comments); gb_data.source = Some(gb_io::seq::Source { source: md.source.clone().unwrap_or_default(), organism: md.organism.clone(), }); if md.source.is_none() && md.organism.is_none() { gb_data.source = None; } // data.keywords = md.keywords.clone(); gb_data.keywords.clone_from(&md.keywords); gb_data.date = if let Some(date) = md.date { // gb_io::seq::Date::from_ymd(date.year(), date.month(), date.day()).ok() gb_io::seq::Date::from_ymd(date.0, date.1.into(), date.2.into()).ok() } else { None }; gb_data.version.clone_from(&md.version); gb_data.accession.clone_from(&md.accession); gb_data.definition.clone_from(&md.definition); gb_data.molecule_type.clone_from(&md.molecule_type); gb_data.division.clone_from(&md.division); gb_data.name = Some(md.locus.clone()); for ref_ in &md.references { gb_data.references.push(gb_io::seq::Reference { description: ref_.description.clone(), authors: ref_.authors.clone(), consortium: ref_.consortium.clone(), title: ref_.title.clone(), journal: ref_.journal.clone(), pubmed: ref_.pubmed.clone(), remark: ref_.remark.clone(), }) } let mut writer = SeqWriter::new(file); writer.write(&gb_data) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/pcad.rs
src/file_io/pcad.rs
//! This module contains code for saving and loading in our own PCAD format. //! //! This is a binary format that uses packets for each of several message types. This sytem //! should have better backwards compatibility than raw serialization and deserialization using //! Bincode or similar. //! //! Byte encoding is big endian. use std::{io, io::ErrorKind}; use bincode::config; use na_seq::{deser_seq_bin, serialize_seq_bin}; use num_enum::TryFromPrimitive; use crate::file_io::save::StateToSave; const START_BYTES: [u8; 2] = [0xca, 0xfe]; // Arbitrary, used as a sanity check. const PACKET_START: u8 = 0x11; const PACKET_OVERHEAD: usize = 6; // packet start, packet type, message size. #[repr(u8)] #[derive(Clone, Copy, PartialEq, TryFromPrimitive)] pub enum PacketType { Sequence = 0, Features = 1, Primers = 2, Metadata = 3, // IonConcentrations = 6, Portions = 7, // PathLoaded = 10, Topology = 11, Ab1 = 12, } /// Byte 0: Standard packet start. Bytes 1-4: u32 of payload len. Bytes 5[..]: Payload. pub struct Packet { type_: PacketType, payload: Vec<u8>, } impl Packet { /// Note: Bytes includes this payload, and potentially until the end of the entire file data. /// We use the length bytes to know when to stop reading. pub fn from_bytes(bytes: &[u8]) -> io::Result<Self> { if bytes.len() < PACKET_OVERHEAD { return Err(io::Error::new( ErrorKind::InvalidData, "Packet must be at least 2 bytes", )); } if bytes[0] != PACKET_START { return Err(io::Error::new( ErrorKind::InvalidData, "Invalid packet start byte in PCAD file.", )); } // todo: This may not be necessary, due to the vec being passed. let payload_size = u32::from_be_bytes(bytes[1..5].try_into().unwrap()) as usize; if bytes.len() < PACKET_OVERHEAD + payload_size { return Err(io::Error::new( ErrorKind::InvalidData, "Remaining payload is too short based on read packet len in PCAD file.", )); } Ok(Self { type_: bytes[5].try_into().map_err(|_| { io::Error::new(ErrorKind::InvalidData, "Invalid packet type received") })?, payload: bytes[PACKET_OVERHEAD..PACKET_OVERHEAD + payload_size].to_vec(), // todo: This essentially clones? Not ideal. }) } pub fn to_bytes(&self) -> Vec<u8> { let mut result = vec![PACKET_START]; let len = self.payload.len() as u32; result.extend(&len.to_be_bytes()); result.push(self.type_ as u8); result.extend(&self.payload); result } } impl StateToSave { /// Serialize state as bytes in the PCAD format, e.g. for file saving. pub fn to_bytes(&self) -> Vec<u8> { let cfg = config::standard(); let mut result = Vec::new(); result.extend(&START_BYTES); // Note: The order we add these packets in doesn't make a difference for loading. let seq_packet = Packet { type_: PacketType::Sequence, payload: serialize_seq_bin(&self.generic.seq), }; let features_packet = Packet { type_: PacketType::Features, payload: bincode::encode_to_vec(&self.generic.features, cfg).unwrap(), }; let primers_packet = Packet { type_: PacketType::Primers, payload: bincode::encode_to_vec(&self.generic.primers, cfg).unwrap(), }; let metadata_packet = Packet { type_: PacketType::Metadata, payload: bincode::encode_to_vec(&self.generic.metadata, cfg).unwrap(), }; let topology_packet = Packet { type_: PacketType::Topology, payload: bincode::encode_to_vec(&self.generic.topology, cfg).unwrap(), }; // let ion_concentrations_packet = Packet { // type_: PacketType::IonConcentrations, // payload: bincode::encode_to_vec(&self.ion_concentrations, cfg).unwrap(), // }; let portions_packet = Packet { type_: PacketType::Portions, payload: bincode::encode_to_vec(&self.portions, cfg).unwrap(), }; // let path_loaded_packet = Packet { // type_: PacketType::PathLoaded, // payload: bincode::encode_to_vec(&self.path_loaded, cfg).unwrap(), // }; let ab1_packet = Packet { type_: PacketType::Ab1, payload: bincode::encode_to_vec(&self.ab1_data, cfg).unwrap(), }; result.extend(&seq_packet.to_bytes()); result.extend(&features_packet.to_bytes()); result.extend(&primers_packet.to_bytes()); result.extend(&metadata_packet.to_bytes()); result.extend(&topology_packet.to_bytes()); result.extend(&ab1_packet.to_bytes()); // result.extend(&ion_concentrations_packet.to_bytes()); result.extend(&portions_packet.to_bytes()); // result.extend(&path_loaded_packet.to_bytes()); result } /// Deserialize state as bytes in the PCAD format, e.g. for file loading. pub fn from_bytes(bytes: &[u8]) -> io::Result<Self> { if bytes[0..2] != START_BYTES { return Err(io::Error::new( ErrorKind::InvalidData, "Invalid start bytes in PCAD file.", )); } let cfg = config::standard(); let mut result = StateToSave::default(); let mut i = START_BYTES.len(); loop { if i + PACKET_OVERHEAD > bytes.len() { break; // End of the packet. } let bytes_remaining = &bytes[i..]; let packet = match Packet::from_bytes(bytes_remaining) { Ok(p) => p, Err(e) => { eprintln!("Problem opening a packet: {:?}", e); let payload_size = u32::from_be_bytes(bytes_remaining[1..5].try_into().unwrap()) as usize; i += PACKET_OVERHEAD + payload_size; continue; } }; i += PACKET_OVERHEAD + packet.payload.len(); // Now, add packet data to our result A/R. match packet.type_ { PacketType::Sequence => match deser_seq_bin(&packet.payload) { Ok(v) => result.generic.seq = v, Err(e) => eprintln!("Error decoding sequence packet: {e}"), }, PacketType::Features => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.generic.features = v.0, Err(e) => eprintln!("Error decoding features packet: {e}"), }, PacketType::Primers => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.generic.primers = v.0, Err(e) => eprintln!("Error decoding primers packet: {e}"), }, PacketType::Metadata => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.generic.metadata = v.0, Err(e) => eprintln!("Error decoding metadata packet: {e}"), }, PacketType::Topology => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.generic.topology = v.0, Err(e) => eprintln!("Error decoding topology packet: {e}"), }, // PacketType::IonConcentrations => { // match bincode::decode_from_slice(&packet.payload, cfg) { // Ok(v) => result.ion_concentrations = v.0, // Err(e) => eprintln!("Error decoding ion concentrations packet: {e}"), // } // } PacketType::Portions => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.portions = v.0, Err(e) => eprintln!("Error decoding portions packet: {e}"), }, PacketType::Ab1 => match bincode::decode_from_slice(&packet.payload, cfg) { Ok(v) => result.ab1_data = v.0, Err(e) => eprintln!("Error decoding AB1 packet: {e}"), }, // PacketType::PathLoaded => match bincode::decode_from_slice(&packet.payload, cfg) { // Ok(v) => result.path_loaded = v.0, // Err(e) => eprintln!("Error decoding Seq packet: {e}"), // }, } } Ok(result) } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/mod.rs
src/file_io/mod.rs
//! This module contains code for saving and loading in several file formats. use std::{path::Path, sync::Arc}; use egui_file_dialog::{FileDialog, FileDialogConfig}; use na_seq::{Seq, SeqTopology}; use crate::{ file_io::save::{DEFAULT_DNA_FILE, DEFAULT_FASTA_FILE, DEFAULT_GENBANK_FILE, QUICKSAVE_FILE}, misc_types::{Feature, Metadata}, primer::Primer, }; mod ab1_tags; pub mod genbank; mod pcad; pub mod save; pub mod snapgene; /// The most important data to store, used by our format, GenBank, and SnapGene. /// We use this in our main State struct to keep track of this data. #[derive(Default, Clone)] pub struct GenericData { pub seq: Seq, pub topology: SeqTopology, pub features: Vec<Feature>, pub primers: Vec<Primer>, pub metadata: Metadata, } pub struct FileDialogs { pub save: FileDialog, pub load: FileDialog, pub export_fasta: FileDialog, pub export_genbank: FileDialog, pub export_dna: FileDialog, pub cloning_load: FileDialog, } impl Default for FileDialogs { fn default() -> Self { // We can't clone `FileDialog`; use this to reduce repetition instead. let cfg_import = FileDialogConfig { // todo: Explore other optiosn A/R ..Default::default() } .add_file_filter_extensions("PlasCAD", vec!["pcad"]) .add_file_filter_extensions("FASTA", vec!["fasta"]) .add_file_filter_extensions("GenBank", vec!["gb, gbk"]) .add_file_filter_extensions("SnapGene DNA", vec!["dna"]) .add_file_filter_extensions( "PCAD/FASTA/GB/DNA/AB1", vec!["pcad", "fasta, gb, gbk, dna, ab1"], ); let save = FileDialog::new() // .add_quick_access("Project", |s| { // s.add_path("☆ Examples", "examples"); // }) .add_save_extension("PlasCAD", "pcad") .default_save_extension("PlasCAD") .default_file_name(QUICKSAVE_FILE); // .id("0"); let import = FileDialog::with_config(cfg_import.clone()) .default_file_filter("PCAD/FASTA/GB/DNA/AB1"); let export_fasta = FileDialog::new() .add_save_extension("FASTA", "fasta") .default_save_extension("FASTA") .default_file_name(DEFAULT_FASTA_FILE); let export_genbank = FileDialog::new() .add_save_extension("GenBank", "gb") .default_save_extension("GenBank") .default_file_name(DEFAULT_GENBANK_FILE); let export_dna = FileDialog::new() .add_save_extension("SnapGene DNA", "dna") .default_save_extension("SnapGene DNA") .default_file_name(DEFAULT_DNA_FILE); let cloning_import = FileDialog::with_config(cfg_import).default_file_filter("PCAD/FASTA/GB/DNA/AB1"); Self { save, // load: load_, load: import, export_fasta, export_genbank, export_dna, cloning_load: cloning_import, // selected: None, } } } /// There doesn't seem to be a clear name in GenBank or Snapgene formats; use the filename. /// Note: This includes error checking, but this should always pass under normal circumstances. fn get_filename(path: &Path) -> String { if let Some(file_name) = path.file_stem() { file_name .to_str() .map(|s| s.to_string()) .unwrap_or_default() } else { String::new() } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/save.rs
src/file_io/save.rs
//! This module includes code for reading and writing our PlasCAD binary fileformat. //! //! Todo: Break into packets. This may require further ejecting from bincode, at least at the top level[s]. use std::{ env, fs::File, io, io::{ErrorKind, Read, Write}, path::{Path, PathBuf}, }; use bincode::{ Decode, Encode, error::{DecodeError, EncodeError}, }; use bio::io::fasta; use bio_files::{SeqRecordAb1, import_ab1}; use eframe::egui::Ui; use na_seq::{Nucleotide, Seq, SeqTopology, deser_seq_bin, seq_to_u8_lower, serialize_seq_bin}; use crate::{ Selection, SeqVisibility, StateUi, feature_db_load::find_features, file_io::{ GenericData, genbank::{export_genbank, import_genbank}, snapgene::{export_snapgene, import_snapgene}, }, gui::{ navigation::{Page, PageSeq, PageSeqTop, Tab}, set_window_title, }, misc_types::{Feature, Metadata}, pcr::PcrUi, portions::PortionsState, primer::{IonConcentrations, Primer}, state::State, }; pub const QUICKSAVE_FILE: &str = "quicksave.pcad"; pub const DEFAULT_PREFS_FILE: &str = "pcad_prefs.pp"; pub const DEFAULT_FASTA_FILE: &str = "export.fasta"; pub const DEFAULT_GENBANK_FILE: &str = "export.gbk"; pub const DEFAULT_DNA_FILE: &str = "export.dna"; /// Sequence-related data to save in our own file format, GBK, or Snapgene. #[derive(Default)] pub struct StateToSave { pub generic: GenericData, // pub path_loaded: Option<Tab>, // pub ion_concentrations: IonConcentrations, pub portions: PortionsState, // pub ab1_data: Vec<SeqRecordAb1>, // todo: Sort this out; how to indicate we loaded AB1 vs normal. pub ab1_data: SeqRecordAb1, pub path_loaded: Option<PathBuf>, } impl Encode for GenericData { fn encode<E: bincode::enc::Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> { // Serialize seq using our custom serializer let seq_data = serialize_seq_bin(&self.seq); seq_data.encode(encoder)?; // Serialize other fields using default serialization self.topology.encode(encoder)?; self.features.encode(encoder)?; self.primers.encode(encoder)?; self.metadata.encode(encoder)?; Ok(()) } } impl Decode<()> for GenericData { fn decode<D: bincode::de::Decoder>(decoder: &mut D) -> Result<Self, DecodeError> { // Deserialize seq using our custom deserializer let seq_data = Vec::decode(decoder)?; let seq = deser_seq_bin(&seq_data).unwrap_or_default(); // todo: Better error handling/propogation. // Deserialize other fields using default deserialization let topology = SeqTopology::decode(decoder)?; let features = Vec::<Feature>::decode(decoder)?; let primers = Vec::<Primer>::decode(decoder)?; let metadata = Metadata::decode(decoder)?; Ok(Self { seq, topology, features, primers, metadata, }) } } impl StateToSave { pub fn from_state(state: &State, active: usize) -> Self { Self { generic: state.generic[active].clone(), // insert_loc: state.cloning_insert_loc, // todo: Not fully handled. // ion_concentrations: state.ion_concentrations[active].clone(), // path_loaded: state.path_loaded[active].clone(), portions: state.portions[state.active].clone(), // ab1_data: state.ab1_data.clone(), ab1_data: state.ab1_data[state.active].clone(), path_loaded: None, // todo: Is this correct? } } /// Saves in PCAD format. todo: Move to the PCAD file A/R. pub fn save_to_file(&self, path: &Path) -> io::Result<()> { let encoded = self.to_bytes(); let mut file = File::create(path)?; file.write_all(&encoded)?; Ok(()) } /// Loads in PCAD format. pub fn load_from_file(path: &Path) -> io::Result<Self> { let mut file = File::open(path)?; let mut buffer = Vec::new(); file.read_to_end(&mut buffer)?; Self::from_bytes(&buffer) } } #[derive(Encode, Decode)] /// Represents state to save automatically; not related to sequence data. pub struct PrefsToSave { page: Page, page_seq: PageSeq, page_seq_top: PageSeqTop, pcr: PcrUi, selected_item: Selection, seq_visibility: SeqVisibility, hide_map_feature_editor: bool, tabs_open: Vec<Tab>, ion_concentrations: IonConcentrations, } impl PrefsToSave { pub fn from_state( state: &StateUi, tabs_open_: &[Tab], ion_concentrations: &IonConcentrations, ) -> Self { // Remove the empty paths; we can't load them. let mut tabs_open = Vec::new(); for t in tabs_open_ { if t.path.is_some() { tabs_open.push(t.clone()); } } Self { page: state.page, page_seq: state.page_seq, page_seq_top: state.page_seq_top, pcr: state.pcr.clone(), selected_item: state.selected_item, seq_visibility: state.seq_visibility.clone(), hide_map_feature_editor: state.hide_map_feature_editor, tabs_open, ion_concentrations: ion_concentrations.clone(), } } /// Used to load to state. The result is data from this struct, augmented with default values. pub fn to_state(&self) -> (StateUi, Vec<Tab>, IonConcentrations) { ( StateUi { page: self.page, page_seq: self.page_seq, page_seq_top: self.page_seq_top, pcr: self.pcr.clone(), selected_item: self.selected_item, seq_visibility: self.seq_visibility.clone(), hide_map_feature_editor: self.hide_map_feature_editor, // last_file_opened: self.last_file_opened.clone(), ..Default::default() }, self.tabs_open.clone(), self.ion_concentrations.clone(), ) } } // todo: same as in Graphics. /// Save to file, using Bincode. We currently use this for preference files. pub fn save<T: Encode>(path: &Path, data: &T) -> io::Result<()> { let config = bincode::config::standard(); let encoded: Vec<u8> = bincode::encode_to_vec(data, config).unwrap(); let mut file = File::create(path)?; file.write_all(&encoded)?; Ok(()) } // todo: same as in Graphics. /// Load from file, using Bincode. We currently use this for preference files. pub fn load<T: Decode<()>>(path: &Path) -> io::Result<T> { let config = bincode::config::standard(); let mut file = File::open(path)?; let mut buffer = Vec::new(); file.read_to_end(&mut buffer)?; let (decoded, _len) = match bincode::decode_from_slice(&buffer, config) { Ok(v) => v, Err(_) => { eprintln!("Error loading from file. Did the format change?"); return Err(io::Error::new(ErrorKind::Other, "error loading")); } }; Ok(decoded) } /// Export a sequence in FASTA format. pub fn export_fasta(seq: &[Nucleotide], name: &str, path: &Path) -> io::Result<()> { let file = File::create(path)?; let mut writer = fasta::Writer::new(file); writer.write( name, Some("A DNA export from PlasCAD"), seq_to_u8_lower(seq).as_slice(), )?; Ok(()) } /// Import from a FASTA file. (Seq, plasmid name (id), description) pub fn import_fasta(path: &Path) -> io::Result<(Seq, String, String)> { let file = File::open(path)?; let mut records = fasta::Reader::new(file).records(); let mut result = Vec::new(); // todo: Do we want id, or description? let mut id = String::new(); let mut description = String::new(); while let Some(Ok(record)) = records.next() { for r in record.seq() { result.push(Nucleotide::from_u8_letter(*r)?); record.id().clone_into(&mut id); // Note that this overrides previous records, if applicable. record .desc() .unwrap_or_default() .clone_into(&mut description) } } Ok((result, id, description)) } /// Save a new file, eg a cloning or PCR product. pub fn save_new_product(name: &str, state: &mut State, ui: &mut Ui) { name.clone_into(&mut state.generic[state.active].metadata.plasmid_name); let active = state.generic.len(); state.active = active; // todo: Option for GenBank and SnapGene formats here? let mut save_path = env::current_dir().unwrap(); let filename = { let name = state.generic[state.active] .metadata .plasmid_name .to_lowercase() .replace(' ', "_"); format!("{name}.pcad") }; save_path.push(Path::new(&filename)); state.ui.file_dialogs.save.config_mut().default_file_name = filename.to_string(); state.ui.file_dialogs.save.save_file(); if let Some(path) = state.ui.file_dialogs.save.take_picked() { match StateToSave::from_state(state, state.active).save_to_file(&path) { Ok(_) => { // state.file_active = Some(Tab { // path: path.to_owned(), // ab1: false, // }); set_window_title(&state.tabs_open[state.active], ui); // if let Some(path) = state.tabs_open[state.active].path { // // } } Err(e) => eprintln!( "Error saving cloning product in the PlasCAD format: {:?}", e ), }; } } /// Load state from a file of various formats. pub fn load_import(path: &Path) -> Option<StateToSave> { let mut result = StateToSave::default(); if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) { match extension.to_lowercase().as_ref() { "pcad" => { let state_loaded = StateToSave::load_from_file(path); match state_loaded { Ok(s) => { result.generic = s.generic; result.path_loaded = Some(path.to_owned()); // result.ion_concentrations = s.ion_concentrations; // result.path_loaded = Some(Tab { // path: path.to_owned(), // ab1: false, // }); result.portions = s.portions; return Some(result); } Err(e) => { eprintln!("Error loading a PCAD file: {e}"); } }; } // Does this work for FASTQ too? "fasta" | "fa" => { if let Ok((seq, id, description)) = import_fasta(path) { result.generic.seq = seq; result.generic.metadata.plasmid_name = id; result.generic.metadata.comments = vec![description]; // FASTA is seq-only data, so don't attempt to save over it. // Automatically annotate FASTA files. result.generic.features = find_features(&result.generic.seq); return Some(result); } } "dna" => { if let Ok(data) = import_snapgene(path) { result.generic = data; // We do not mark the path as opened if using SnapGene, since we currently can not // fully understand the format, nor make a native file SnapGene can open. return Some(result); } } "gb" | "gbk" => { if let Ok(data) = import_genbank(path) { result.generic = data; // result.path_loaded = Some(Tab { // path: path.to_owned(), // ab1: false, // }); result.path_loaded = Some(path.to_owned()); return Some(result); } } "ab1" => { if let Ok(data) = import_ab1(path) { if data.len() >= 1 { result.ab1_data = data[0].clone(); // todo: Note that this assumes len 1 of results. } // result.path_loaded = Some(Tab { // path: path.to_owned(), // ab1: true, // }); result.path_loaded = Some(path.to_owned()); return Some(result); } } _ => { eprintln!( "The file to import must be in PlasCAD, FASTA, GenBank, SnapGene, or AB1 format." ) } } } None } /// Save the current file ("save" vice "save as") if there is one; if not, quicksave to an anonymous file. pub fn save_current_file(state: &State) { match &state.tabs_open[state.active].path { Some(path) => { if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) { match extension.to_lowercase().as_ref() { "pcad" => { // if let Err(e) = save(path, &StateToSave::from_state(state, state.active)) { if let Err(e) = StateToSave::from_state(state, state.active).save_to_file(&path) { eprintln!("Error saving in PlasCAD format: {}", e); }; } // Does this work for FASTQ too? "fasta" => { if let Err(e) = export_fasta( state.get_seq(), &state.generic[state.active].metadata.plasmid_name, &path, ) { eprintln!("Error exporting to FASTA: {:?}", e); }; } "dna" => { if let Err(e) = export_snapgene(&state.generic[state.active], path) { eprintln!("Error exporting to SnapGene: {:?}", e); }; } "gb" | "gbk" => { let mut primer_matches = Vec::new(); for primer in &state.generic[state.active].primers { for prim_match in &primer.volatile.matches { primer_matches.push((prim_match.clone(), primer.name.clone())); } } if let Err(e) = export_genbank(&state.generic[state.active], &primer_matches, path) { eprintln!("Error exporting to GenBank: {:?}", e); }; } _ => { eprintln!("Unexpected file format loading.") } } } } None => { // Quicksave. if let Err(e) = StateToSave::from_state(state, state.active) .save_to_file(&PathBuf::from(QUICKSAVE_FILE)) { eprintln!("Error quicksaving: {e}"); } } } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/ab1_tags.rs
src/file_io/ab1_tags.rs
//! [BioPython code](https://github.com/biopython/biopython/blob/master/Bio/SeqIO/AbiIO.py) use std::{fmt::Display, io, io::ErrorKind}; #[derive(Clone, Copy, PartialEq)] enum TagSeqRecord { SampleWell, Dye, Polymer, MachineModel, } // todo: Tag to string rep? impl TagSeqRecord { fn from_str(inp: &str) -> io::Result<Self> { match inp { "TUBE1" => Ok(Self::SampleWell), "DySN1" => Ok(Self::SampleWell), "GTyp1" => Ok(Self::SampleWell), "MODL1" => Ok(Self::SampleWell), _ => Err(io::Error::new(ErrorKind::InvalidData, "Invalid tag string")), } } } #[derive(Clone, Copy, PartialEq)] enum GeneralTag { Apfn2, Apxv1, Aprn1, Aprv1, Aprx1, Cmnt1, Ctid1, Ctnm1, Cttl1, Cpep1, Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10, Data11, Data12, Dsam1, Dysn1, DyeNum1, DyeN1, DyeN2, DyeN3, DyeN4, DyeW1, DyeW2, DyeW3, DyeW4, Epvt1, Evnt1, Evnt2, Evnt3, Evnt4, Fwo1, Gtyp1, Insc1, Invt1, Lane1, Lims1, Lntd1, Lsrp1, Mchn1, Modf1, Modl1, Navg1, Nlne1, Ofsc1, Ovri1, Ovri2, Ovri3, Ovri4, Ovrv1, Ovrv2, Ovrv3, Ovrv4, Pdmf1, Rmxv1, Rmdn1, Rmdx1, Rprn1, Rprv1, Rund1, Rund2, Rund3, Rund4, Runt1, Runt2, Runt3, Runt4, Rate1, Runn1, Scan1, Smed1, Smlt1, Smpl1, Sver1, Sver3, Satd1, Scal1, Tube1, Tmpr1, User1, } impl GeneralTag { fn from_str(inp: &str) -> io::Result<Self> { match inp { "APFN2" => Ok(Self::Apfn2), "APXV1" => Ok(Self::Apxv1), "APrN1" => Ok(Self::Aprn1), "APrV1" => Ok(Self::Aprv1), "APrX1" => Ok(Self::Aprx1), "CMNT1" => Ok(Self::Cmnt1), "CTID1" => Ok(Self::Ctid1), "CTNM1" => Ok(Self::Ctnm1), "CTTL1" => Ok(Self::Cttl1), "CpEP1" => Ok(Self::Cpep1), "DATA1" => Ok(Self::Data1), "DATA2" => Ok(Self::Data2), "DATA3" => Ok(Self::Data3), "DATA4" => Ok(Self::Data4), "DATA5" => Ok(Self::Data5), "DATA6" => Ok(Self::Data6), "DATA7" => Ok(Self::Data7), "DATA8" => Ok(Self::Data8), "DATA9" => Ok(Self::Data9), "DATA10" => Ok(Self::Data10), "DATA11" => Ok(Self::Data11), "DATA12" => Ok(Self::Data12), "DSam1" => Ok(Self::Dsam1), "DySN1" => Ok(Self::Dysn1), "Dye#1" => Ok(Self::DyeNum1), "DyeN1" => Ok(Self::DyeN1), "DyeN2" => Ok(Self::DyeN2), "DyeN3" => Ok(Self::DyeN3), "DyeN4" => Ok(Self::DyeN4), "DyeW1" => Ok(Self::DyeW1), "DyeW2" => Ok(Self::DyeW2), "DyeW3" => Ok(Self::DyeW3), "DyeW4" => Ok(Self::DyeW4), "EPVt1" => Ok(Self::Epvt1), "EVNT1" => Ok(Self::Evnt1), "EVNT2" => Ok(Self::Evnt2), "EVNT3" => Ok(Self::Evnt3), "EVNT4" => Ok(Self::Evnt4), "FWO_1" => Ok(Self::Fwo1), "GTyp1" => Ok(Self::Gtyp1), "InSc1" => Ok(Self::Insc1), "InVt1" => Ok(Self::Invt1), "LANE1" => Ok(Self::Lane1), "LIMS1" => Ok(Self::Lims1), "LNTD1" => Ok(Self::Lntd1), "LsrP1" => Ok(Self::Lsrp1), "MCHN1" => Ok(Self::Mchn1), "MODF1" => Ok(Self::Modf1), "MODL1" => Ok(Self::Modl1), "NAVG1" => Ok(Self::Navg1), "NLNE1" => Ok(Self::Nlne1), "OfSc1" => Ok(Self::Ofsc1), "OvrI1" => Ok(Self::Ovri1), "OvrI2" => Ok(Self::Ovri2), "OvrI3" => Ok(Self::Ovri3), "OvrI4" => Ok(Self::Ovri4), "OvrV1" => Ok(Self::Ovrv1), "OvrV2" => Ok(Self::Ovrv2), "OvrV3" => Ok(Self::Ovrv3), "OvrV4" => Ok(Self::Ovrv4), "PDMF1" => Ok(Self::Pdmf1), "RMXV1" => Ok(Self::Rmxv1), "RMdN1" => Ok(Self::Rmdn1), "RMdX1" => Ok(Self::Rmdx1), "RPrN1" => Ok(Self::Rprn1), "RPrV1" => Ok(Self::Rprv1), "RUND1" => Ok(Self::Rund1), "RUND2" => Ok(Self::Rund2), "RUND3" => Ok(Self::Rund3), "RUND4" => Ok(Self::Rund4), "RUNT1" => Ok(Self::Runt1), "RUNT2" => Ok(Self::Runt2), "RUNT3" => Ok(Self::Runt3), "RUNT4" => Ok(Self::Runt4), "Rate1" => Ok(Self::Rate1), "RunN1" => Ok(Self::Runn1), "SCAN1" => Ok(Self::Scan1), "SMED1" => Ok(Self::Smed1), "SMLt1" => Ok(Self::Smlt1), "SMPL1" => Ok(Self::Smpl1), "SVER1" => Ok(Self::Sver1), "SVER3" => Ok(Self::Sver3), "Satd1" => Ok(Self::Satd1), "Scal1" => Ok(Self::Scal1), "TUBE1" => Ok(Self::Tube1), "Tmpr1" => Ok(Self::Tmpr1), "User1" => Ok(Self::User1), _ => Err(io::Error::new( ErrorKind::InvalidData, format!("Invalid tag string: {}", inp), )), } } } // impl ToString for GeneralTag { // fn to_string(&self) -> String { // match self { // Self::Apfn2 => "Sequencing Analysis parameters file name", // #[derive(Clone, Copy, PartialEq)] enum Abi3130Tag { CtoW1, HcfG1, HcfG2, HcfG3, HcfG4, RmdVa1, } impl Abi3130Tag { fn from_str(inp: &str) -> io::Result<Self> { match inp { "CTOw1" => Ok(Self::CtoW1), "HCFG1" => Ok(Self::HcfG1), "HCFG2" => Ok(Self::HcfG2), "HCFG3" => Ok(Self::HcfG3), "HCFG4" => Ok(Self::HcfG4), "RMdVa1" => Ok(Self::RmdVa1), _ => Err(io::Error::new( ErrorKind::InvalidData, format!("Invalid tag string: {}", inp), )), } } } impl Display for Abi3130Tag { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::CtoW1 => "Container owner", Self::HcfG1 => "Instrument Class", Self::HcfG2 => "Instrument Family", Self::HcfG3 => "Official Instrument Name", Self::HcfG4 => "Instrument Parameters", Self::RmdVa1 => "Run Module version", } .to_string(); write!(f, "{}", str) } } #[derive(Clone, Copy, PartialEq)] enum Abi3530Tag { Aact1, Abed1, Abid1, Ablt1, Abrn1, Abtp1, Aept1, Aept2, Apcn1, Artn1, Aspf1, Aspt1, Aspt2, Audt2, Avld1, Ambt1, Asyc1, Asyn1, Asyv1, B1pt1, B1pt2, Bcts1, Bcrn1, Bcrs1, Bcrs2, Caed1, Calt1, Carn1, Casn1, Cbed1, Cbid1, Cblt1, Cbrn1, Cbtp1, Clrg1, Clrg2, Crln1, Crln2, Ctow1, Cksm1, Dcev1, Dcht1, Doev1, Esig2, Ftab1, Fvoc1, Feat1, Hcfg1, Hcfg2, Hcfg3, Hcfg4, Injn1, Last1, Nois1, P1am1, P1rl1, P1wd1, P2am1, P2ba1, P2rl1, Pbas1, Pbas2, Pcon1, Pcon2, Pdmf2, Ploc1, Ploc2, Prjt1, Proj4, Psze1, Ptyp1, Pusc1, Qv201, Qv202, Qcpa1, Qcrn1, Qcrs1, Qcrs2, Rgow1, Rinj1, Rnmf1, Revc1, Runn1, Sn1, Smid1, Smrn1, Spac1, Spac2, Spac3, Spec1, Sver2, Sver4, Scpa1, Scst1, Spen1, Trpa1, Trsc1, Trsc2, Phar1, Phch1, Phdy1, Phql1, Phtr1, Phtr2, } impl Abi3530Tag { fn from_str(inp: &str) -> io::Result<Self> { match inp { "AAct1" => Ok(Self::Aact1), "ABED1" => Ok(Self::Abed1), "ABID1" => Ok(Self::Abid1), "ABLt1" => Ok(Self::Ablt1), "ABRn1" => Ok(Self::Abrn1), "ABTp1" => Ok(Self::Abtp1), "AEPt1" => Ok(Self::Aept1), "AEPt2" => Ok(Self::Aept2), "APCN1" => Ok(Self::Apcn1), "ARTN1" => Ok(Self::Artn1), "ASPF1" => Ok(Self::Aspf1), "ASPt1" => Ok(Self::Aspt1), "ASPt2" => Ok(Self::Aspt2), "AUDT2" => Ok(Self::Audt2), "AVld1" => Ok(Self::Avld1), "AmbT1" => Ok(Self::Ambt1), "AsyC1" => Ok(Self::Asyc1), "AsyN1" => Ok(Self::Asyn1), "AsyV1" => Ok(Self::Asyv1), "B1Pt1" => Ok(Self::B1pt1), "B1Pt2" => Ok(Self::B1pt2), "BCTS1" => Ok(Self::Bcts1), "BcRn1" => Ok(Self::Bcrn1), "BcRs1" => Ok(Self::Bcrs1), "BcRs2" => Ok(Self::Bcrs2), "CAED1" => Ok(Self::Caed1), "CALt1" => Ok(Self::Calt1), "CARn1" => Ok(Self::Carn1), "CASN1" => Ok(Self::Casn1), "CBED1" => Ok(Self::Cbed1), "CBID1" => Ok(Self::Cbid1), "CBLt1" => Ok(Self::Cblt1), "CBRn1" => Ok(Self::Cbrn1), "CBTp1" => Ok(Self::Cbtp1), "CLRG1" => Ok(Self::Clrg1), "CLRG2" => Ok(Self::Clrg2), "CRLn1" => Ok(Self::Crln1), "CRLn2" => Ok(Self::Crln2), "CTOw1" => Ok(Self::Ctow1), "CkSm1" => Ok(Self::Cksm1), "DCEv1" => Ok(Self::Dcev1), "DCHT1" => Ok(Self::Dcht1), "DOEv1" => Ok(Self::Doev1), "ESig2" => Ok(Self::Esig2), "FTab1" => Ok(Self::Ftab1), "FVoc1" => Ok(Self::Fvoc1), "Feat1" => Ok(Self::Feat1), "HCFG1" => Ok(Self::Hcfg1), "HCFG2" => Ok(Self::Hcfg2), "HCFG3" => Ok(Self::Hcfg3), "HCFG4" => Ok(Self::Hcfg4), "InjN1" => Ok(Self::Injn1), "LAST1" => Ok(Self::Last1), "NOIS1" => Ok(Self::Nois1), "P1AM1" => Ok(Self::P1am1), "P1RL1" => Ok(Self::P1rl1), "P1WD1" => Ok(Self::P1wd1), "P2AM1" => Ok(Self::P2am1), "P2BA1" => Ok(Self::P2ba1), "P2RL1" => Ok(Self::P2rl1), "PBAS1" => Ok(Self::Pbas1), "PBAS2" => Ok(Self::Pbas2), "PCON1" => Ok(Self::Pcon1), "PCON2" => Ok(Self::Pcon2), "PDMF2" => Ok(Self::Pdmf2), "PLOC1" => Ok(Self::Ploc1), "PLOC2" => Ok(Self::Ploc2), "PRJT1" => Ok(Self::Prjt1), "PROJ4" => Ok(Self::Proj4), "PSZE1" => Ok(Self::Psze1), "PTYP1" => Ok(Self::Ptyp1), "PuSc1" => Ok(Self::Pusc1), "QV201" => Ok(Self::Qv201), "QV202" => Ok(Self::Qv202), "QcPa1" => Ok(Self::Qcpa1), "QcRn1" => Ok(Self::Qcrn1), "QcRs1" => Ok(Self::Qcrs1), "QcRs2" => Ok(Self::Qcrs2), "RGOw1" => Ok(Self::Rgow1), "RInj1" => Ok(Self::Rinj1), "RNmF1" => Ok(Self::Rnmf1), "RevC1" => Ok(Self::Revc1), "RunN1" => Ok(Self::Runn1), "S/N%1" => Ok(Self::Sn1), "SMID1" => Ok(Self::Smid1), "SMRn1" => Ok(Self::Smrn1), "SPAC1" => Ok(Self::Spac1), "SPAC2" => Ok(Self::Spac2), "SPAC3" => Ok(Self::Spac3), "SPEC1" => Ok(Self::Spec1), "SVER2" => Ok(Self::Sver2), "SVER4" => Ok(Self::Sver4), "ScPa1" => Ok(Self::Scpa1), "ScSt1" => Ok(Self::Scst1), "SpeN1" => Ok(Self::Spen1), "TrPa1" => Ok(Self::Trpa1), "TrSc1" => Ok(Self::Trsc1), "TrSc2" => Ok(Self::Trsc2), "phAR1" => Ok(Self::Phar1), "phCH1" => Ok(Self::Phch1), "phDY1" => Ok(Self::Phdy1), "phQL1" => Ok(Self::Phql1), "phTR1" => Ok(Self::Phtr1), "phTR2" => Ok(Self::Phtr2), _ => Err(io::Error::new( ErrorKind::InvalidData, format!("Invalid tag string: {}", inp), )), } } } impl Display for Abi3530Tag { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Aact1 => "Primary Analysis Audit Active indication. True if system auditing was enabled during the last write of this file.", Self::Abed1 => "Anode buffer expiration date using ISO 8601 format.", Self::Abid1 => "Anode buffer tray first installed date.", Self::Ablt1 => "Anode buffer lot number.", Self::Abrn1 => "Number of runs processed with the current Anode Buffer (runs allowed - runs remaining).", Self::Abtp1 => "Anode buffer type.", Self::Aept1 => "Analysis Ending scan number for basecalling on initial analysis.", Self::Aept2 => "Analysis Ending scan number for basecalling on last analysis.", Self::Apcn1 => "Amplicon name.", Self::Artn1 => "Analysis Return code. Produced only by 5 Prime basecaller 1.0b3.", Self::Aspf1 => "Flag to indicate whether adaptive processing worked or not.", Self::Aspt1 => "Analysis Starting scan number for first analysis.", Self::Aspt2 => "Analysis Starting scan number for last analysis.", Self::Audt2 => "Audit log used across 3500 software.", Self::Avld1 => "Assay validation flag (true or false).", Self::Ambt1 => "Record of ambient temperature readings.", Self::Asyc1 => "The assay contents (XML format).", Self::Asyn1 => "The assay name.", Self::Asyv1 => "The assay version.", Self::B1pt1 => "Reference scan number for mobility and spacing curves for first analysis.", Self::B1pt2 => "Reference scan number for mobility and spacing curves for last analysis.", Self::Bcts1 => "Basecaller timestamp. Time of completion of most recent analysis.", Self::Bcrn1 => "Basecalling QC code.", Self::Bcrs1 => "Basecalling warnings, a concatenated comma-separated string.", Self::Bcrs2 => "Basecalling errors, a concatenated comma-separated string.", Self::Caed1 => "Capillary array expiration.", Self::Calt1 => "Capillary array lot number.", Self::Carn1 => "Number of injections processed through the capillary array.", Self::Casn1 => "Capillary array serial number.", Self::Cbed1 => "Cathode buffer expiration date.", Self::Cbid1 => "Cathode buffer tray first installed date.", Self::Cblt1 => "Cathode buffer lot number.", Self::Cbrn1 => "Number of runs processed with the current Cathode Buffer (runs allowed - runs remaining).", Self::Cbtp1 => "Cathode buffer type.", Self::Clrg1 => "Start of the clear range (inclusive).", Self::Clrg2 => "Clear range length.", Self::Crln1 => "Contiguous read length.", Self::Crln2 => "QC status: Pass, Fail, or Check.", Self::Ctow1 => "The name entered as the Owner of a plate in the plate editor.", Self::Cksm1 => "File checksum.", Self::Dcev1 => "A list of door-close events, separated by semicolon.", Self::Dcht1 => "Detection cell heater temperature setting from the Run Module.", Self::Doev1 => "A list of door-open events, separated by semicolon.", Self::Esig2 => "Electronic signature record used across 3500 software.", Self::Ftab1 => "Feature table created by Nibbler for Clear Range.", Self::Fvoc1 => "Feature table vocabulary created by Nibbler for Clear Range.", Self::Feat1 => "Features created by Nibbler for Clear Range.", Self::Hcfg1 => "The Instrument Class: CE.", Self::Hcfg2 => "The Instrument Family: 31XX, 35XX, or 37XX.", Self::Hcfg3 => "The official instrument name: e.g., 3130, 3130xl, 3730, 3730xl, 3500, 3500xl.", Self::Hcfg4 => "Instrument parameters: key-value pairs of instrument configuration information.", Self::Injn1 => "Injection name.", Self::Last1 => "Parameter settings information.", Self::Nois1 => "Estimate of RMS baseline noise for each dye.", Self::P1am1 => "Amplitude of primary peak.", Self::P1rl1 => "Deviation of primary peak position.", Self::P1wd1 => "Full-width half-max of primary peak.", Self::P2am1 => "Amplitude of secondary peak.", Self::P2ba1 => "Base of secondary peak.", Self::P2rl1 => "Deviation of secondary peak position.", Self::Pbas1 => "Array of sequence characters edited by user.", Self::Pbas2 => "Array of sequence characters as called by Basecaller.", Self::Pcon1 => "Array of quality values edited by user.", Self::Pcon2 => "Array of quality values as called by Basecaller.", Self::Pdmf2 => "Mobility file name chosen in most recent analysis.", Self::Ploc1 => "Array of peak locations edited by user.", Self::Ploc2 => "Array of peak locations as called by Basecaller.", Self::Prjt1 => "SeqScape project template name.", Self::Proj4 => "SeqScape project name.", Self::Psze1 => "Plate size: 96 or 384.", Self::Ptyp1 => "Plate type: 96-Well or 384-Well.", Self::Pusc1 => "Median pupscore.", Self::Qv201 => "QV20+ value.", Self::Qv202 => "QC status: Pass, Fail, or Check.", Self::Qcpa1 => "QC parameters.", Self::Qcrn1 => "Trimming and QC code.", Self::Qcrs1 => "QC warnings, a concatenated comma-separated string.", Self::Qcrs2 => "QC errors, a concatenated comma-separated string.", Self::Rgow1 => "Results group owner name.", Self::Rinj1 => "Reinjection number.", Self::Rnmf1 => "Raman normalization factor.", Self::Revc1 => "Whether the sequence has been complemented.", Self::Runn1 => "Run name (different from injection name on 3500).", Self::Sn1 => "Signal strength for each dye.", Self::Smid1 => "Polymer first installed date.", Self::Smrn1 => "Number of runs processed with the current polymer.", Self::Spac1 => "Average peak spacing used in last analysis.", Self::Spac2 => "Basecaller name.", Self::Spac3 => "Average peak spacing calculated by the Basecaller.", Self::Spec1 => "Sequencing Analysis Specimen Name.", Self::Sver2 => "Basecaller version number.", Self::Sver4 => "Sample File Format Version String.", Self::Scpa1 => "Size caller parameter string.", Self::Scst1 => "Raw data start point.", Self::Spen1 => "Active spectral calibration name.", Self::Trpa1 => "Trimming parameters.", Self::Trsc1 => "Trace score.", Self::Trsc2 => "QC status: Pass, Fail, or Check.", Self::Phar1 => "Trace peak area ratio.", Self::Phch1 => "Chemistry type based on DYE_1 information.", Self::Phdy1 => "Dye information.", Self::Phql1 => "Maximum Quality Value.", Self::Phtr1 => "Trim region set.", Self::Phtr2 => "Trim probability.", } .to_string(); write!(f, "{}", str) } } #[derive(Clone, Copy, PartialEq)] enum Abi3730Tag { Buft1, } impl Abi3730Tag { fn from_str(inp: &str) -> io::Result<Self> { match inp { "BufT1" => Ok(Self::Buft1), _ => Err(io::Error::new( ErrorKind::InvalidData, format!("Invalid tag string: {}", inp), )), } } } impl Display for Abi3730Tag { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Buft1 => "Buffer tray heater temperature (degrees C)", } .to_string(); write!(f, "{}", str) } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/file_io/snapgene.rs
src/file_io/snapgene.rs
//! Parse and write SnapGene DNA files. This converts between the Snapgene format for sequences, features, //! primers, notes etc., and our own equivalents. //! //! (Unofficial file format description)[https://incenp.org/dvlpt/docs/binary-sequence-formats/binary-sequence-formats.pdf] //! DNA files are divided into packets. Packet structure: //! - A byte indicating the packet's type //! - A big endian 32-bit unsigned integer of packet len //! - The payload use std::{ fs::File, io::{self, ErrorKind, Read, Write}, path::Path, str, }; use num_enum::TryFromPrimitive; use quick_xml::{de::from_str, se::to_string}; // We remove these from SnapGene feature qualifiers. const HTML_TAGS: [&str; 8] = [ "<html>", "</html>", "<body>", "</body>", "<i>", "</i>", "<b>", "</b>", ]; use na_seq::{Nucleotide, Seq, SeqTopology, seq_from_str, seq_to_str_lower}; use crate::{ file_io::{ GenericData, get_filename, snapgene::feature_xml::{ FeatureSnapGene, Features, Notes, PrimerSnapGene, Primers, Qualifier, QualifierValue, Segment, }, }, misc_types::{Feature, FeatureDirection, FeatureType}, primer::{Primer, PrimerData}, util::{RangeIncl, color_from_hex, color_to_hex}, }; const COOKIE_PACKET_LEN: usize = 14; #[derive(Debug, TryFromPrimitive)] #[repr(u8)] // todo: We are observing other packet types: 0x9, 0x3, 0x11, 0x8, 0xd, 0xe, 0x1c enum PacketType { /// The cookie is always the first packet. Cookie = 0x09, Dna = 0x00, Primers = 0x05, Notes = 0x06, Features = 0x0a, AdditionalSequenceProperties = 0x08, AlignableSequences = 0x11, CustomEnzymeSets = 0xe, Unknown = 0x99, // Placeholder for encountering one we don't recognize } /// Import a file in SnapGene's DNA format into local state. This includes sequence, features, and primers. pub fn import_snapgene(path: &Path) -> io::Result<GenericData> { let mut file = File::open(path)?; let buf = { let mut b = Vec::new(); file.read_to_end(&mut b)?; b }; let mut result = GenericData::default(); result.metadata.plasmid_name = get_filename(path); let mut i = 0; loop { if i + 6 >= buf.len() { break; } let packet_type = PacketType::try_from_primitive(buf[i]).unwrap_or(PacketType::Unknown); i += 1; let payload_len = u32::from_be_bytes(buf[i..i + 4].try_into().unwrap()) as usize; i += 4; if i + payload_len + 1 > buf.len() { eprintln!( "Error parsing DNA file: Payload would exceed file length. Index: {}, buf len: {}", i + payload_len, buf.len() ); break; } let payload = &buf[i..i + payload_len]; i += payload_len; match packet_type { PacketType::Cookie => { if payload_len != COOKIE_PACKET_LEN { eprintln!("Invalid cookie packet length: {}", payload_len); } if &payload[..8] != b"SnapGene" { eprintln!("Invalid cookie payload: {:?}", &payload[0..8]); } // The next bytes describe the type of seq (1 for DNA, export version, and import version) // at indexes 0xd, 0xf, and 0x11 respectively. } PacketType::Dna => { // todo: Note: This doesn't properly handle if there are multiple DNA packets. // todo: How should we do that? match parse_dna(payload) { Ok(v) => { result.seq = v.0; result.topology = v.1; } Err(e) => eprintln!("Error parsing DNA packet: {:?}", e), } } PacketType::Primers => match parse_primers(payload) { Ok(v) => result.primers = v, Err(e) => eprintln!("Error parsing Primers packet: {:?}", e), }, PacketType::Notes => match parse_notes(payload) { Ok(_v) => { // if !v.inner.is_empty() { // // todo: Are there ever multiple notes? // result.metadata.plasmid_name = v.inner[0].title.clone(); // } // todo: Other fields, references etc. Compare in SnapGene itself, and how snapgene // todo parses and exports a GenBank file. } Err(e) => eprintln!("Error parsing Notes packet: {:?}", e), }, PacketType::Features => match parse_features(payload) { Ok(v) => result.features = v, Err(e) => eprintln!("Error parsing Features packet: {:?}", e), }, PacketType::Unknown => { println!( "Unknown packet type: {:x} len: {payload_len}", buf[i - 5 - payload_len] ); let payload_str = str::from_utf8(payload) .map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert payload to string: {e}",), ) }) .ok(); println!("Payload str: \n{:?}", payload_str); } _ => (), } } Ok(result) } fn parse_dna(payload: &[u8]) -> io::Result<(Seq, SeqTopology)> { if payload.is_empty() { return Err(io::Error::new(ErrorKind::InvalidData, "Empty DNA packet")); } let flags = payload[0]; let sequence = &payload[1..]; let mut seq = Vec::new(); for nt in sequence { match Nucleotide::from_u8_letter(*nt) { Ok(n) => seq.push(n), Err(_) => { eprintln!("Unexpected char in DNA sequence: {:?}", nt); } } } let topology = if flags & 0x01 != 0 { SeqTopology::Circular } else { SeqTopology::Linear }; println!("Flags: {flags}"); Ok((seq, topology)) } // todo: Consider a sub-module for XML parsing. mod feature_xml { use std::str::FromStr; use serde::{Deserialize, Deserializer, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Features { #[serde(rename = "Feature", default)] pub inner: Vec<FeatureSnapGene>, } // Workaround for parsing "" into None not supported natively by quick-xml/serde. fn deserialize_directionality<'de, D>(deserializer: D) -> Result<Option<u8>, D::Error> where D: Deserializer<'de>, { let s: Option<String> = Option::deserialize(deserializer)?; if let Some(s) = s { if s.is_empty() { Ok(None) } else { u8::from_str(&s).map(Some).map_err(serde::de::Error::custom) } } else { Ok(None) } } #[derive(Debug, Serialize, Deserialize)] pub struct FeatureSnapGene { #[serde(rename = "@type")] pub feature_type: Option<String>, #[serde( rename = "@directionality", deserialize_with = "deserialize_directionality", default )] pub directionality: Option<u8>, #[serde(rename = "@name", default)] pub name: Option<String>, // Other Feature attributes: allowSegmentOverlaps (0/1), consecutiveTranslationNumbering (0/1) #[serde(rename = "Segment", default)] pub segments: Vec<Segment>, #[serde(rename = "Q", default)] pub qualifiers: Vec<Qualifier>, } #[derive(Debug, Serialize, Deserialize)] pub struct Segment { #[serde(rename = "@type", default)] pub segment_type: Option<String>, #[serde(rename = "@range", default)] pub range: Option<String>, #[serde(rename = "@name", default)] pub name: Option<String>, #[serde(rename = "@color", default, skip_serializing_if = "Option::is_none")] pub color: Option<String>, // Hex. // Other fields: "translated": 0/1 } #[derive(Debug, Serialize, Deserialize)] pub struct Qualifier { #[serde(rename = "@name")] pub name: String, #[serde(rename = "V", default)] pub values: Vec<QualifierValue>, } #[derive(Debug, Serialize, Deserialize)] pub struct QualifierValue { #[serde(rename = "@text", default, skip_serializing_if = "Option::is_none")] pub text: Option<String>, #[serde(rename = "@predef", default, skip_serializing_if = "Option::is_none")] pub predef: Option<String>, #[serde(rename = "@int", default, skip_serializing_if = "Option::is_none")] pub int: Option<i32>, } #[derive(Debug, Serialize, Deserialize)] pub struct Primers { #[serde(rename = "Primer", default)] pub inner: Vec<PrimerSnapGene>, } // Note; We have left out the binding site and a number of other fields, as they are not relevant // for us at this time. This also includes melting temperature, which we calculate. #[derive(Debug, Serialize, Deserialize)] pub struct PrimerSnapGene { #[serde(rename = "@sequence")] pub sequence: String, #[serde(rename = "@name")] pub name: String, #[serde(rename = "@description")] pub description: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Notes { #[serde(rename = "Notes", default)] pub inner: Vec<Notes_>, } // Note; We have left out the binding site and other fields, as they are not relevant for us at this time. #[derive(Debug, Serialize, Deserialize)] pub struct Notes_ { #[serde(rename = "UUID")] pub uuid: String, #[serde(rename = "Type")] pub type_: String, #[serde(rename = "ConfirmedExperimentally")] pub confirmed_experimentally: u8, // todo? `0` in example #[serde(rename = "CreatedBy")] pub created_by: String, #[serde(rename = "SequenceClass")] pub sequence_class: String, #[serde(rename = "TransformedInto")] pub transformed_into: String, // todo: How do we handle LastModified and Created, given they have timestamps in the field name? #[serde(rename = "Reference journal")] pub reference_journal: String, pub doi: String, pub pages: String, #[serde(rename = "pubMedID")] pub pub_med_id: String, pub title: String, pub date: String, pub authors: String, #[serde(rename = "journalName")] pub nournal_name: String, pub volume: String, } // <Notes> // <UUID>0962493c-08f0-4964-91b9-24840fea051e</UUID> // <Type>Synthetic</Type> // <ConfirmedExperimentally>0</ConfirmedExperimentally> // <Created UTC="22:48:15">2024.7.12</Created> // <LastModified UTC="18:2:52">2024.7.14</LastModified> // <CreatedBy>SnapGene License</CreatedBy> // <SequenceClass>UNA</SequenceClass> // <TransformedInto>DH5α™</TransformedInto> // </Notes> } fn parse_features(payload: &[u8]) -> io::Result<Vec<Feature>> { let payload_str = str::from_utf8(payload).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert payload to string: {e}",), ) })?; // println!("\n\n\nPayload str: {:?}\n\n\n", payload_str); let features: Features = from_str(payload_str).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to parse features: {e}"), ) })?; let mut result = Vec::new(); for feature_sg in &features.inner { // Note: Our model does not include the concept of segments; treat each SnapGene segment as a new feature. let name = feature_sg.name.clone().unwrap_or(String::new()); let direction = match feature_sg.directionality { Some(1) => FeatureDirection::Forward, Some(2) => FeatureDirection::Reverse, _ => FeatureDirection::None, }; let feature_type = match &feature_sg.feature_type { Some(t) => FeatureType::from_external_str(t), None => FeatureType::default(), }; // let mut notes = HashMap::new(); let mut notes = Vec::new(); for qual in &feature_sg.qualifiers { // It seems there is generally one value per qualifier. In the case there are multiple, // we will parse them as separate notes. for val in &qual.values { // Generally, each val only has one of text, int, predef let mut v = String::new(); if let Some(t) = &val.int { v = t.to_string(); } if let Some(t) = &val.predef { v.clone_from(t); } if let Some(t) = &val.text { v.clone_from(t); } // Remove the HTML tags and related that SnapGene inserts into qual values. for html_tag in HTML_TAGS { v = v.replace(html_tag, ""); } // notes.insert(qual.name.clone(), v); notes.push((qual.name.clone(), v)); } } // Note: We currently parse multiple segments as separate features, but SnapGene has the concept // of multiple segments per feature. These share all data except the <Segment tag attributes. // (name, range, color, type, translated etc) for segment in &feature_sg.segments { let color_override = match &segment.color { Some(c) => color_from_hex(c).ok(), None => None, }; let range = match &segment.range { Some(r) => range_from_str(r).unwrap_or(RangeIncl::new(1, 1)), None => RangeIncl::new(1, 1), }; result.push(Feature { range, feature_type, direction, label: name.clone(), color_override, notes: notes.clone(), }); } } Ok(result) } fn parse_primers(payload: &[u8]) -> io::Result<Vec<Primer>> { let payload_str = str::from_utf8(payload).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert payload to string: {e}",), ) })?; let primers: Primers = from_str(payload_str).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to parse primers: {e}"), ) })?; let mut result = Vec::new(); for primer_sg in &primers.inner { let seq = seq_from_str(&primer_sg.sequence); let volatile = PrimerData::new(&seq); result.push(Primer { sequence: seq, name: primer_sg.name.clone(), description: Some(primer_sg.description.clone()), volatile, }); } Ok(result) } // fn parse_notes(payload: &[u8]) -> io::Result<Vec<String>> { fn parse_notes(payload: &[u8]) -> io::Result<Notes> { let payload_str = str::from_utf8(payload).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert payload to string: {e}",), ) })?; println!("Notes string: \n\n{:?}\n\n", payload_str); // todo: Is this a strict format, or arbitary notes? let notes: Notes = from_str(payload_str).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to parse notes: {e}"), ) })?; let result = notes; Ok(result) } fn range_from_str(range: &str) -> Result<RangeIncl, &'static str> { let parts: Vec<&str> = range.split('-').collect(); if parts.len() != 2 { return Err("Invalid range format"); } let start = parts[0] .parse::<usize>() .map_err(|_| "Invalid number in range")?; let end = parts[1] .parse::<usize>() .map_err(|_| "Invalid number in range")?; Ok(RangeIncl::new(start, end)) } /// Add feature data to the buffer. fn export_features(buf: &mut Vec<u8>, features: &[Feature]) -> io::Result<()> { let mut features_sg = Features { inner: Vec::new() }; for feature in features { let directionality = match feature.direction { FeatureDirection::Forward => Some(1), FeatureDirection::Reverse => Some(2), FeatureDirection::None => None, }; let segments = vec![Segment { segment_type: None, range: Some(format!("{}-{}", feature.range.start, feature.range.end)), name: None, color: feature.color_override.map(color_to_hex), }]; let mut qualifiers = Vec::with_capacity(feature.notes.len()); for (key, value) in &feature.notes { // todo: If int parsable, consider saving as an int. qualifiers.push(Qualifier { name: key.to_string(), values: vec![QualifierValue { text: Some(value.to_string()), predef: None, int: None, }], }) } features_sg.inner.push(FeatureSnapGene { feature_type: Some(feature.feature_type.to_string()), segments, qualifiers, name: Some(feature.label.clone()), directionality, }); } let xml_str = to_string(&features_sg).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert features to an XML string: {e}"), ) })?; let xml = xml_str.into_bytes(); buf.push(PacketType::Features as u8); buf.extend((xml.len() as u32).to_be_bytes()); buf.extend(&xml); Ok(()) } /// Add primer data to the buffer. fn export_primers(buf: &mut Vec<u8>, primers: &[Primer]) -> io::Result<()> { let mut primers_sg = Primers { inner: Vec::new() }; for primer in primers { primers_sg.inner.push(PrimerSnapGene { sequence: seq_to_str_lower(&primer.sequence), name: primer.name.clone(), description: primer.description.clone().unwrap_or_default(), }); } let xml_str = to_string(&primers_sg).map_err(|e| { io::Error::new( ErrorKind::InvalidData, format!("Unable to convert primers to an XML string: {e}"), ) })?; let xml = xml_str.into_bytes(); buf.push(PacketType::Features as u8); buf.extend((xml.len() as u32).to_be_bytes()); buf.extend(&xml); Ok(()) } /// Export our local state into the SnapGene dna format. This includes sequence, features, and primers. pub fn export_snapgene(data: &GenericData, path: &Path) -> io::Result<()> { let mut file = File::create(path)?; let mut buf = Vec::new(); let mut cookie_packet = [0; 19]; cookie_packet[0] = PacketType::Cookie as u8; cookie_packet[1..5].clone_from_slice(&(COOKIE_PACKET_LEN as u32).to_be_bytes()); cookie_packet[5..13].clone_from_slice(b"SnapGene"); buf.extend(&cookie_packet); buf.push(PacketType::Dna as u8); buf.extend(((data.seq.len() + 1) as u32).to_be_bytes()); let flag = match data.topology { SeqTopology::Circular => 1, SeqTopology::Linear => 0, }; buf.push(flag); buf.extend(seq_to_str_lower(&data.seq).as_bytes()); export_features(&mut buf, &data.features)?; export_primers(&mut buf, &data.primers)?; file.write_all(&buf)?; Ok(()) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/primer_table.rs
src/gui/primer_table.rs
//! This module contains code to the primer editor, QC etc. use eframe::egui::{Align, Color32, Layout, RichText, ScrollArea, TextEdit, Ui}; use egui_extras::{Column, TableBuilder}; use na_seq::{seq_from_str, seq_to_str_lower}; use crate::{ Selection, gui::{ COL_SPACING, ROW_SPACING, theme::{COLOR_ACTION, COLOR_INFO}, }, primer::{IonConcentrations, Primer, TuneSetting, make_amplification_primers}, state::State, }; const TABLE_ROW_HEIGHT: f32 = 60.; const COLOR_GOOD: Color32 = Color32::GREEN; const COLOR_MARGINAL: Color32 = Color32::GOLD; const COLOR_BAD: Color32 = Color32::LIGHT_RED; pub const DEFAULT_TRIM_AMT: usize = 32 - 20; // const TM_IDEAL: f32 = 59.; // todo: Fill thi sin // // const THRESHOLDS_TM: (f32, f32) = (59., 60.); // const THRESHOLDS_GC: (f32, f32) = (59., 60.); /// Color scores in each category according to these thresholds. These scores should be on a scale /// between 0 and 1. fn color_from_score(score: f32) -> Color32 { const SCORE_COLOR_THRESH: (f32, f32) = (0.5, 0.8); if score > SCORE_COLOR_THRESH.1 { COLOR_GOOD } else if score > SCORE_COLOR_THRESH.0 { COLOR_MARGINAL } else { COLOR_BAD } } /// Allows editing ion concentration, including float manip. Return if the response changed, /// so we can redo TM calcs downstream. fn ion_edit(val: &mut f32, label: &str, ui: &mut Ui) -> bool { ui.label(label); let mut v = format!("{:.1}", val); let response = ui.add(TextEdit::singleline(&mut v).desired_width(30.)); if response.changed() { *val = v.parse().unwrap_or(0.); true } else { false } } fn primer_table(state: &mut State, ui: &mut Ui) { let mut run_match_sync = None; // Avoids a double-mutation error. TableBuilder::new(ui) .column(Column::initial(650.).resizable(true)) // Sequence .column(Column::initial(160.).resizable(true)) // Description .column(Column::auto().resizable(true))// Len .column(Column::auto().resizable(true))// Len .column(Column::auto().resizable(true))// Matches .column(Column::auto().resizable(true))// Quality .column(Column::initial(40.).resizable(true)) // TM .column(Column::initial(36.).resizable(true))// GC % .column(Column::auto().resizable(true))// 3' GC content .column(Column::auto().resizable(true))// Complexity .column(Column::auto().resizable(true))// Dimer formation .column(Column::auto().resizable(true)) // Repeats .column(Column::remainder()) .header(20.0, |mut header| { header.col(|ui| { ui.heading("Primer sequence (5' ⏵ 3')"); }); header.col(|ui| { ui.heading("Name"); }); header.col(|ui| { ui.heading("Len").on_hover_text("Number of nucleotides in the (tuned, if applicable) primer"); }); header.col(|ui| { ui.heading("Weight").on_hover_text("The weight of this primer, in Daltons."); }); header.col(|ui| { ui.heading("Mt").on_hover_text("Number of matches with the target sequence"); }); header.col(|ui| { ui.heading("Qual").on_hover_text("Overall primer quality. This is an abstract estimate, taking all other listed factors into account."); }); header.col(|ui| { ui.heading("TM").on_hover_text("Primer melting temperature, in °C. Calculated using base a base stacking method, where\ enthalpy and entropy of neighboring base pairs are added. See the readme for calculations and assumptions."); }); header.col(|ui| { ui.heading("GC").on_hover_text("The percentage of nucleotides that are C or G."); }); header.col(|ui| { ui.heading("3'GC").on_hover_text("3' end stability: The number of G or C nucleotides in the last 5 nucleotides. 2-3 is ideal. Sources differ on if 4 is acceptable."); }); // header.col(|ui| { // ui.heading("Cplx").on_hover_text("Sequence complexity. See the readme for calculations and assumptions."); // }); header.col(|ui| { ui.heading("Dmr").on_hover_text("Potential of forming a self-end dimer. See the readme for calculations and assumptions."); }); header.col(|ui| { ui.heading("Rep").on_hover_text("Count of repeats of a single or double nt sequence >4 in a row, and count of triplet \ repeats anywhere in the sequence."); }); // For selecting the row. header.col(|_ui| {}); }) .body(|mut body| { for (i, primer) in state.generic[state.active].primers.iter_mut().enumerate() { // println!("Primer: 5p: {:?} 3p: {:?} Rem5: {:?} Rem3: {:?}", primer.volatile.tunable_5p, // primer.volatile.tunable_5p, primer.volatile.seq_removed_5p, primer.volatile.seq_removed_3p); body.row(TABLE_ROW_HEIGHT, |mut row| { row.col(|ui| { ui.horizontal(|ui| { let color = match primer.volatile.tune_setting { TuneSetting::Only5(_) | TuneSetting::Both(_) => Color32::GREEN, _ => Color32::LIGHT_GRAY, }; if ui .button(RichText::new("T").color(color)) .clicked() { primer.volatile.tune_setting.toggle_5p(); // if primer.volatile.tunable_5p == TuneSetting::Disabled { // primer.run_calcs(&state.ion_concentrations[state.active]); // To re-sync the sequence without parts removed. primer.run_calcs(&state.ion_concentrations); // To re-sync the sequence without parts removed. // } run_match_sync = Some(i); } let response = ui.add( TextEdit::singleline(&mut primer.volatile.sequence_input).desired_width(400.), ); if response.changed() { primer.sequence = seq_from_str(&primer.volatile.sequence_input); primer.volatile.sequence_input = seq_to_str_lower(&primer.sequence); // primer.run_calcs(&state.ion_concentrations[state.active]); primer.run_calcs(&state.ion_concentrations); run_match_sync = Some(i); } let color = match primer.volatile.tune_setting { TuneSetting::Only3(_) | TuneSetting::Both(_) => Color32::GREEN, _ => Color32::LIGHT_GRAY, }; if ui .button(RichText::new("T").color(color)) .clicked() { primer.volatile.tune_setting.toggle_3p(); // if primer.volatile.tunable_3p == TuneSetting::Disabled { // primer.run_calcs(&state.ion_concentrations[state.active]); // To re-sync the sequence without parts removed. primer.run_calcs(&state.ion_concentrations); // To re-sync the sequence without parts removed. // } run_match_sync = Some(i); } ui.add_space(COL_SPACING); match primer.volatile.tune_setting { TuneSetting::Both(_) | TuneSetting::Only5(_) | TuneSetting::Only3(_) => { if ui .button(RichText::new("Tune")).on_hover_text("Tune selected ends for this primer").clicked() { // primer.tune(&state.ion_concentrations[state.active]); primer.tune(&state.ion_concentrations); run_match_sync = Some(i); } } _ => (), } }); // let updated_seq = primer_tune_display(primer, &state.ion_concentrations[state.active], ui); let updated_seq = primer_tune_display(primer, &state.ion_concentrations, ui); if updated_seq { run_match_sync = Some(i); } }); row.col(|ui| { ui.add(TextEdit::singleline(&mut primer.name).text_color(COLOR_INFO)); }); row.col(|ui| { let text = match &primer.volatile.metrics { Some(m) => { RichText::new(primer.sequence.len().to_string()) .color(color_from_score(m.len_score)) }, None => RichText::new(primer.sequence.len().to_string()), }; ui.label(text); }); row.col(|ui| { ui.label(format!("{:.1}", primer.volatile.weight)); }); row.col(|ui| { ui.label(primer.volatile.matches.len().to_string()); }); row.col(|ui| { let text = match & primer.volatile.metrics { // todo: PRe-compute the * 100? Some(m) => RichText::new(format!("{:.0}", m.quality_score * 100.)) .color(color_from_score(m.quality_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let text = match & primer.volatile.metrics { Some(m) => RichText::new(format!("{:.1}°C", m.melting_temp)) .color(color_from_score(m.tm_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let text = match & primer.volatile.metrics { // todo: Cache this calc? Some(m) => RichText::new(format!("{:.0}%", m.gc_portion * 100.)) .color(color_from_score(m.gc_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let text = match & primer.volatile.metrics { Some(m) => RichText::new(format!("{}", m.gc_3p_count)) .color(color_from_score(m.gc_3p_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let text = match & primer.volatile.metrics { Some(m) => RichText::new(format!("{}", m.self_end_dimer)) .color(color_from_score(m.dimer_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let text = match & primer.volatile.metrics { Some(m) => RichText::new(format!("{}", m.repeats)) .color(color_from_score(m.repeats_score)), None => RichText::new("-"), }; ui.label(text); }); row.col(|ui| { let mut selected = false; if let Selection::Primer(sel_i) = state.ui.selected_item { if sel_i == i { selected = true; } } if selected { if ui.button(RichText::new("🔘").color(Color32::GREEN)).clicked() { state.ui.selected_item = Selection::None; } } else if ui.button("🔘").clicked() { state.ui.selected_item = Selection::Primer(i); } }); }); } }); if run_match_sync.is_some() { state.sync_seq_related(run_match_sync); } } pub fn primer_details(state: &mut State, ui: &mut Ui) { ScrollArea::vertical().show(ui, |ui| { ui.horizontal(|ui| { let add_btn = ui .button("➕ Add primer") .on_hover_text("Adds a primer to the list below."); if add_btn.clicked() { state.generic[state.active].primers.push(Default::default()) } if ui .button("➕ Make whole seq primers") .on_hover_text("Adds a primer pair that amplify the entire loaded sequence.") .clicked() { make_amplification_primers(state); } let mut sync_primer_matches = false; // Prevents a double-borrow error. if ui.button("Tune all").clicked() { for primer in &mut state.generic[state.active].primers { // primer.tune(&state.ion_concentrations[state.active]); primer.tune(&state.ion_concentrations); sync_primer_matches = true; } } if sync_primer_matches { state.sync_primer_matches(None); } ui.add_space(COL_SPACING * 2.); ui.add_space(2. * COL_SPACING); ui.heading("Ions: (mMol)"); // if ion_edit(&mut state.ion_concentrations.monovalent, "Na+ and K+", ui) if ion_edit(&mut state.ion_concentrations.monovalent, "Na+ and K+", ui) || ion_edit(&mut state.ion_concentrations.divalent, "mg2+", ui) || ion_edit(&mut state.ion_concentrations.dntp, "dNTP", ui) || ion_edit(&mut state.ion_concentrations.primer, "primer (nM)", ui) { for primer in &mut state.generic[state.active].primers { // primer.run_calcs(&state.ion_concentrations[state.active]); // Note: We only need to run the TM calc. primer.run_calcs(&state.ion_concentrations); // Note: We only need to run the TM calc. } } }); ui.label("Tuning instructions: Include more of the target sequence than required on the end[s] that can be tuned. These are the \ ends that do not define your insert, gene of interest, insertion point etc. Mark that end as tunable using the \"T\" button. \ To learn about a table column, mouse over it."); ui.add_space(ROW_SPACING); if let Selection::Primer(sel_i) = state.ui.selected_item { ui.horizontal(|ui| { if sel_i + 1 > state.generic[state.active].primers.len() { // This currently happens if deleting the bottom-most primer. // If so, select the primer above it. state.ui.selected_item = if !state.generic[state.active].primers.is_empty() { Selection::Primer(state.generic[state.active].primers.len() - 1) } else { Selection::None }; return; } if ui.button(RichText::new("⏶")).clicked() { // todo: Arrow icons if sel_i != 0 { state.generic[state.active].primers.swap(sel_i, sel_i - 1); state.ui.selected_item = Selection::Primer(sel_i - 1); } } if ui.button(RichText::new("⏷")).clicked() && sel_i != state.generic[state.active].primers.len() - 1 { state.generic[state.active].primers.swap(sel_i, sel_i + 1); state.ui.selected_item = Selection::Primer(sel_i + 1); } if ui .button(RichText::new("Delete 🗑").color(Color32::RED)) .clicked() { state.generic[state.active].primers.remove(sel_i); } if ui .button(RichText::new("Deselect").color(COLOR_ACTION)) .clicked() { state.ui.selected_item = Selection::None; } ui.add_space(COL_SPACING); if sel_i + 1 > state.generic[state.active].primers.len() { state.ui.selected_item = Selection::None; return; } ui.heading(&format!("Selected: {}", &state.generic[state.active].primers[sel_i].name)); }); ui.add_space(ROW_SPACING); } primer_table(state, ui); }); } /// Shows below each primer sequence. Data and controls on trimming primer size for optimization. /// Returns wheather a button was clicked. fn primer_tune_display( primer: &mut Primer, ion_concentrations: &IonConcentrations, ui: &mut Ui, ) -> bool { // This avoids a double-mutable error let mut tuned = false; let len_full = primer.volatile.sequence_input.len(); // Section for tuning primer length. ui.horizontal(|ui| { // todo: We only need this when the button is clicked, but getting borrow errors. // This tune limit controls the maximum value of this tune; only applicable if both ends are tunable. let (tune_limit_5p, tune_limit_3p) = match primer.volatile.tune_setting { // Note: The 3p end is minus two, both due to our normal indexing logic, and since the anchor is technically // between two nucleotides. TuneSetting::Both((anchor, _, _)) => { let p3 = if len_full - anchor >= 2 { len_full - anchor - 2 } else { len_full - anchor }; (anchor, p3) }, // -2 _ => { if len_full > 0 { (len_full - 1, len_full - 1) } else { (len_full, len_full) } } // No limit other than primer size. }; if let Some(i) = primer.volatile.tune_setting.val_5p_mut() { ui.label("5'"); if ui.button("⏴").clicked() { if *i > 0 { *i -= 1; } tuned = true; }; if ui.button("⏵").clicked() { if *i < tune_limit_5p { *i += 1; } tuned = true; }; } // Allow setting the anchor. (Eg insertion point when cloning) if let TuneSetting::Both((anchor, _, _)) = &mut primer.volatile.tune_setting { ui.label(format!("Anchor ({}):", *anchor + 1)).on_hover_text("Generally for cloning insert primers; the point of insertion. Can not be tuned out, and primer size is assessed on both sides of it."); if ui.button("⏴").clicked() { if *anchor > 0 { *anchor -= 1; } tuned = true; }; if ui.button("⏵").clicked() { if *anchor + 1 < len_full { *anchor += 1; } tuned = true; }; } // This section shows the trimmed sequence, with the removed parts visible to the left and right. ui.with_layout(Layout::left_to_right(Align::Center), |ui| { ui.label(RichText::new(&primer.volatile.seq_removed_5p).color(Color32::GRAY)); ui.add_space(COL_SPACING / 2.); // if primer.volatile.tunable_5p != TuneSetting::Disabled // || primer.volatile.tunable_3p != TuneSetting::Disabled // { if primer.volatile.tune_setting.tunable() { ui.label(RichText::new(seq_to_str_lower(&primer.sequence)).color(COLOR_INFO)); } ui.add_space(COL_SPACING / 2.); ui.label(RichText::new(&primer.volatile.seq_removed_3p).color(Color32::GRAY)); }); // Note: We need to reverse the item order for this method of right-justifying to work. // This is kind of OK with the intent here though. ui.with_layout(Layout::right_to_left(Align::Max), |ui| { if let Some(i) = primer.volatile.tune_setting.val_3p_mut() { ui.label("3'"); if ui.button("⏵").clicked() { if *i > 0 { *i -= 1; } tuned = true; }; if ui.button("⏴").clicked() { if *i < tune_limit_3p { *i += 1; } tuned = true; }; } }); if tuned { primer.run_calcs(ion_concentrations); } }); tuned }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/lin_maps.rs
src/gui/lin_maps.rs
//! Contains code for our mini view above the circlular map. use eframe::{ egui::{ Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, Sense, Shape, Stroke, Ui, pos2, vec2, }, emath::RectTransform, }; use lin_alg::map_linear; use na_seq::restriction_enzyme::{ReMatch, RestrictionEnzyme}; use crate::{ Selection, StateUi, file_io::GenericData, gui::{ BACKGROUND_COLOR, COLOR_RE, COLOR_RE_HIGHLIGHTED, LINEAR_MAP_HEIGHT, circle::{FEATURE_OUTLINE_COLOR, FEATURE_OUTLINE_SELECTED, FEATURE_STROKE_WIDTH, RE_WIDTH}, }, misc_types::{Feature, FeatureType}, primer::{Primer, PrimerDirection}, state::State, util::RangeIncl, }; // How many nucleotides the zoomed-in display at the top of the page represents. // A smaller value corresponds to a more zoomed-in display. pub const MINI_DISP_NT_LEN: usize = 400; // const MINI_DISP_NT_LEN_DIV2: usize = MINI_DISP_NT_LEN / 2; const CENTER_Y: f32 = 18.; pub const OFFSET: Pos2 = pos2(4., 6.); const Y_START: f32 = OFFSET.y + CENTER_Y; const FEATURE_HEIGHT: f32 = 18.; const FEATURE_HEIGHT_DIV2: f32 = FEATURE_HEIGHT / 2.; const PRIMER_HEIGHT: f32 = 26.; const PRIMER_HEIGHT_DIV2: f32 = PRIMER_HEIGHT / 2.; const RE_HEIGHT: f32 = 30.; const RE_HEIGHT_DIV2: f32 = RE_HEIGHT / 2.; const RE_HEIGHT_HIGHLIGHTED: f32 = 40.; const RE_HEIGHT_HIGHLIGHTED_DIV2: f32 = RE_HEIGHT_HIGHLIGHTED / 2.; fn feature_helper( result: &mut Vec<Shape>, to_screen: &RectTransform, disp_range: RangeIncl, index_to_x: impl Fn(usize) -> f32, pixel_left: f32, pixel_right: f32, feature_range: RangeIncl, feature: &Feature, stroke_color: Color32, ) { /// Used to assist with splitting features around the origin let stroke = Stroke::new(FEATURE_STROKE_WIDTH, stroke_color); let contains_start = disp_range.contains(feature_range.start); let contains_end = disp_range.contains(feature_range.end); // todo: Way to not make this a special case? let full_size = // feature_range.start < disp_range.start && feature_range.end > disp_range.end && disp_range.start < disp_range.end; feature_range.start < disp_range.start && feature_range.end > disp_range.end; let (r, g, b) = feature.color(); let color = Color32::from_rgb(r, g, b); if contains_start || contains_end || full_size { let start_x = if contains_start { index_to_x(feature_range.start) } else { pixel_left }; let end_x = if contains_end { index_to_x(feature_range.end) } else { pixel_right }; // todo: Arrow heads. result.push(Shape::convex_polygon( vec![ to_screen * pos2(start_x, Y_START - FEATURE_HEIGHT_DIV2), to_screen * pos2(end_x, Y_START - FEATURE_HEIGHT_DIV2), to_screen * pos2(end_x, Y_START + FEATURE_HEIGHT_DIV2), to_screen * pos2(start_x, Y_START + FEATURE_HEIGHT_DIV2), ], color, stroke, )); } } fn draw_features( features: &[Feature], seq_len: usize, to_screen: &RectTransform, disp_range: RangeIncl, selected_item: Selection, index_to_x: impl Fn(usize) -> f32, pixel_left: f32, pixel_right: f32, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, feature) in features.iter().enumerate() { if feature.feature_type == FeatureType::Source { // From some GB files indicating the entire sequence. continue; } // todo: DRY with teh main view. helper fn. let stroke_color = match selected_item { Selection::Feature(j) => { if j == i { FEATURE_OUTLINE_SELECTED } else { FEATURE_OUTLINE_COLOR } } _ => FEATURE_OUTLINE_COLOR, }; let mut feature_range = feature.range; // Handle wraps around the origin if feature_range.end > seq_len || feature_range.end < feature_range.start { // Draw a second feature rectangle, from 0 to the end. feature_helper( &mut result, to_screen, disp_range, &index_to_x, pixel_left, pixel_right, RangeIncl::new(0, feature_range.end % seq_len), feature, stroke_color, ); feature_range.end = seq_len; } feature_helper( &mut result, to_screen, disp_range, &index_to_x, pixel_left, pixel_right, feature_range, feature, stroke_color, ); // Draw the label in the center. todo: More locations A/R for long features let center_i = (feature_range.end + feature_range.start) / 2; if disp_range.contains(center_i) { let center_x = index_to_x(center_i); // Draw the label after the shape. let label_pt = pos2(center_x, OFFSET.y + CENTER_Y); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt, Align2::CENTER_CENTER, feature.label(), FontId::new(13., FontFamily::Proportional), Color32::DARK_GREEN, ) })); } } result } /// todo: DRY with draw_features (Similar issue to the non-zoomed cirlc.e fn draw_primers( primers: &[Primer], seq_len: usize, to_screen: &RectTransform, disp_range: RangeIncl, selected_item: Selection, index_to_x: impl Fn(usize) -> f32, pixel_left: f32, pixel_right: f32, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, primer) in primers.iter().enumerate() { for prim_match in &primer.volatile.matches { let mut outline_color = prim_match.direction.color(); if let Selection::Primer(sel_i) = selected_item { if sel_i == i { outline_color = Color32::RED; } } let stroke = Stroke::new(1., outline_color); let mut prim_range = prim_match.range; // Handle wraps around the origin if disp_range.end > seq_len { prim_range.start += seq_len; prim_range.end += seq_len; } let contains_start = disp_range.contains(prim_range.start); let contains_end = disp_range.contains(prim_range.end); // todo: Way to not make this a special case? let full_size = // feature_range.start < disp_range.start && feature_range.end > disp_range.end && disp_range.start < disp_range.end; prim_range.start < disp_range.start && prim_range.end > disp_range.end; if contains_start || contains_end || full_size { let start_x = if contains_start { index_to_x(prim_range.start) } else { pixel_left }; let end_x = if contains_end { index_to_x(prim_range.end) } else { pixel_right }; // todo: Arrow heads. result.push(Shape::convex_polygon( vec![ to_screen * pos2(start_x, Y_START - PRIMER_HEIGHT_DIV2), to_screen * pos2(end_x, Y_START - PRIMER_HEIGHT_DIV2), to_screen * pos2(end_x, Y_START + PRIMER_HEIGHT_DIV2), to_screen * pos2(start_x, Y_START + PRIMER_HEIGHT_DIV2), ], Color32::TRANSPARENT, stroke, )); } // Draw the label in the center. todo: More locations A/R for long features let center_i = (prim_range.end + prim_range.start) / 2; if disp_range.contains(center_i) { let center_x = index_to_x(center_i); // Draw the label after the shape. let label_v_offset = match prim_match.direction { PrimerDirection::Forward => -20., PrimerDirection::Reverse => 20., }; // let label_pt = pos2(center_x, Y_START + PRIMER_HEIGHT_DIV2 + label_v_offset); let label_pt = pos2(center_x, OFFSET.y + CENTER_Y + label_v_offset); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt, Align2::CENTER_CENTER, &primer.name, FontId::new(13., FontFamily::Proportional), outline_color, ) })); } } } result } /// Draw RE cut sites through the circle. /// todo: DRY with tick drawing code. fn draw_re_sites( re_matches: &[ReMatch], lib: &[RestrictionEnzyme], to_screen: &RectTransform, index_to_x: impl Fn(usize) -> f32, unique_cutters_only: bool, sticky_ends_only: bool, selected: &[RestrictionEnzyme], ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, re_match) in re_matches.iter().enumerate() { if re_match.lib_index >= lib.len() { eprintln!("Invalid RE selected"); return result; } let re = &lib[re_match.lib_index]; if (unique_cutters_only && re_match.match_count > 1) || (sticky_ends_only && re.makes_blunt_ends()) { continue; } let cut_i = re_match.seq_index + 1; // to display in the right place. let (font_size, color, height, label_offset) = if selected.contains(&re) { (16., COLOR_RE_HIGHLIGHTED, RE_HEIGHT_HIGHLIGHTED_DIV2, 2.) } else { (13., COLOR_RE, RE_HEIGHT_DIV2, -2.) }; let point_top = pos2(index_to_x(cut_i), Y_START - height); let point_bottom = pos2(index_to_x(cut_i), Y_START + height); result.push(Shape::line_segment( [to_screen * point_bottom, to_screen * point_top], Stroke::new(RE_WIDTH, color), )); let (mut label_pt, label_align) = (point_top + vec2(20., label_offset), Align2::LEFT_CENTER); // Alternate label vertical position, to reduce changes of overlaps. if i % 2 == 0 { label_pt.y += RE_HEIGHT + 8.; } result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt, label_align, &re.name, FontId::new(font_size, FontFamily::Proportional), color, ) })); } result } /// A general purpose linear sequence view, used on several pages. /// This shows features, primers, and index ticks. pub fn draw_linear_map( data: &GenericData, to_screen: &RectTransform, index_left: usize, index_right: usize, show_re_sites: bool, res_highlighted: &[RestrictionEnzyme], re_matches: &[ReMatch], re_lib: &[RestrictionEnzyme], selected_item: Selection, cursor: Option<usize>, state_ui: &StateUi, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); let seq_full_len = data.seq.len(); if seq_full_len < 10 { return result; } let pixel_left = OFFSET.x; let pixel_right = ui.available_width() - 2. * OFFSET.x; let mut disp_range = RangeIncl::new(index_left, index_right); // Handle wraps around the origin. if disp_range.start > disp_range.end { disp_range.end += seq_full_len; } // Based on the display range, map index to a pixel position. let index_to_x = |mut i: usize| { // This handles the case when the zoomed-in view is near the top; the left index // will be near the end of the sequence, incorrectly calculating the portion-through in // the linear map. let right = if index_left > index_right { if i < index_right { // Ie, we are to the right of the origin. i += seq_full_len } index_right + seq_full_len } else { index_right }; map_linear( i as f32, (index_left as f32, right as f32), (pixel_left, pixel_right), ) }; result.append(&mut draw_features( &data.features, seq_full_len, to_screen, disp_range, selected_item, index_to_x, pixel_left, pixel_right, ui, )); result.append(&mut draw_primers( &data.primers, seq_full_len, to_screen, disp_range, selected_item, index_to_x, pixel_left, pixel_right, ui, )); if state_ui.seq_visibility.show_res && show_re_sites { result.append(&mut draw_re_sites( re_matches, re_lib, to_screen, index_to_x, state_ui.re.unique_cutters_only, state_ui.re.sticky_ends_only, res_highlighted, ui, )); } if let Some(loc) = cursor { let point_top = pos2(index_to_x(loc), 4.); let point_bottom = pos2(index_to_x(loc), 44.); result.push(Shape::line_segment( [to_screen * point_bottom, to_screen * point_top], Stroke::new(3., Color32::YELLOW), )); } result } /// Draw a zoomed-in view around the cursor. We use this as the mini view on the circular map page, and on the cloning /// to show the vector insert point. /// set `nt_len` to the sequence len if displaying the whole sequence. Set it to a smaller value for a zoomed in view. pub fn lin_map_zoomed( data: &GenericData, to_screen: &RectTransform, nt_center: usize, nt_len: usize, selection: Selection, state_ui: &StateUi, re_matches: &[ReMatch], re_lib: &[RestrictionEnzyme], ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); let seq_len = data.seq.len(); if seq_len == 0 { return result; // Avoid Divide-by-0 } // Find the bounds of the indices to display; we use them to map indices to pixels for this // mini-display. // todo: Only if circular. let index_left = (nt_center as isize - (nt_len / 2) as isize).rem_euclid(seq_len as isize) as usize; // Rust awk % on negative values. let index_right = (nt_center + nt_len / 2) % seq_len; result.append(&mut draw_linear_map( data, to_screen, index_left, index_right, true, &Vec::new(), // todo: Highlighted REs? re_matches, re_lib, selection, None, &state_ui, ui, )); result } /// Draw a mini sequence display in its own canvas. This displays the entire sequence, and is used on several pages. /// We use this where we are not drawing on an existing canvas. pub fn seq_lin_disp( data: &GenericData, show_re_sites: bool, selection: Selection, res_highlighted: &[RestrictionEnzyme], cursor: Option<usize>, // Or cloning insert, etc state_ui: &StateUi, re_matches: &[ReMatch], re_lib: &[RestrictionEnzyme], ui: &mut Ui, ) { let seq_len = data.seq.len(); Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let (response, _painter) = { let desired_size = vec2(ui.available_width(), LINEAR_MAP_HEIGHT); ui.allocate_painter(desired_size, Sense::click()) }; let to_screen = RectTransform::from_to( Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); if seq_len == 0 { return; // Prevents -1 error on index right calc. } let shapes = draw_linear_map( data, &to_screen, 0, seq_len - 1, show_re_sites, res_highlighted, re_matches, re_lib, selection, cursor, &state_ui, ui, ); ui.painter().extend(shapes); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/ligation.rs
src/gui/ligation.rs
//! GUI code related to ligation operations. use std::{collections::HashMap, path::PathBuf}; use eframe::{ egui::{ Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, RichText, ScrollArea, Sense, Shape, Stroke, Ui, pos2, vec2, }, emath::RectTransform, }; use lin_alg::map_linear; use na_seq::{ ligation, ligation::{LigationFragment, digest}, seq_to_str_lower, }; use crate::{ gui::{ BACKGROUND_COLOR, COL_SPACING, ROW_SPACING, circle::{FEATURE_OUTLINE_COLOR, FEATURE_STROKE_WIDTH}, lin_maps::seq_lin_disp, navigation::{Tab, get_tab_names, name_from_path}, select_color_text, theme::COLOR_ACTION, }, state::State, util::filter_res, }; // This X offset must have room for the RE Nts displayed on the left. const OFFSET_X: f32 = 60.; const OFFSET_Y: f32 = 30.; const PRODUCT_ROW_SPACING: f32 = 60.; const FRAG_DISP_HEIGHT: f32 = 30.; const FRAG_DISP_HEIGHT_DIV2: f32 = FRAG_DISP_HEIGHT / 2.; // We cycle through this for visual separation const SEQ_COLORS: [Color32; 4] = [ Color32::LIGHT_RED, Color32::LIGHT_GREEN, Color32::LIGHT_YELLOW, Color32::LIGHT_GRAY, ]; /// Draw a graphical depiction of digestion products. fn draw_graphics(products: &[LigationFragment], seq_len: usize, ui: &mut Ui) { Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let (response, _painter) = { let desired_size = vec2(ui.available_width(), ui.available_height()); ui.allocate_painter(desired_size, Sense::click()) }; let to_screen = RectTransform::from_to( // Rect::from_min_size(pos2(0., -VERITICAL_CIRCLE_OFFSET), response.rect.size()), Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); // let rect_size = response.rect.size(); let mut shapes = Vec::new(); let stroke = Stroke::new(FEATURE_STROKE_WIDTH, FEATURE_OUTLINE_COLOR); let mut row_px = OFFSET_Y; // Scale pixel length based on the full sequence length. let left_edge_px = OFFSET_X; // Leave enough room on both sides for descriptive text annotations. let right_edge_px = ui.available_width() - OFFSET_X - 80.; let mut seq_colors: HashMap<String, Color32> = HashMap::new(); let mut color_i = 0; for frag in products { let frag_color = if seq_colors.contains_key(&frag.source_name) { seq_colors[&frag.source_name] } else { color_i = (color_i + 1) % SEQ_COLORS.len(); seq_colors.insert(frag.source_name.to_owned(), SEQ_COLORS[color_i]); SEQ_COLORS[color_i] }; let start_x = OFFSET_X; // let end_x = start_x + frag.seq.len() as f32 * 2.; // todo: Rough. // todo: This approach won't work when adding in fragments from other sequences. let end_x = map_linear( frag.seq.len() as f32, (0., seq_len as f32), (left_edge_px, right_edge_px), ); shapes.push(Shape::convex_polygon( vec![ to_screen * pos2(start_x, row_px - FRAG_DISP_HEIGHT_DIV2), to_screen * pos2(end_x, row_px - FRAG_DISP_HEIGHT_DIV2), to_screen * pos2(end_x, row_px + FRAG_DISP_HEIGHT_DIV2), to_screen * pos2(start_x, row_px + FRAG_DISP_HEIGHT_DIV2), ], frag_color, stroke, )); let box_center = pos2((end_x + start_x) / 2., row_px); // Draw the RE ends. let label_pt_left_top = pos2(start_x - 10., row_px - 10.); let label_pt_right_top = pos2(end_x + 10., row_px - 10.); let label_pt_left_bottom = pos2(start_x - 10., row_px + 10.); let label_pt_right_bottom = pos2(end_x + 10., row_px + 10.); let (re_text_left_top, re_text_left_bottom, re_name_left) = match &frag.re_left { Some(re) => ( seq_to_str_lower(&re.overhang_top_left(&[])), // todo: Update this seq_to_str_lower(&re.overhang_bottom_left(&[])), // todo: Update this re.name.clone(), ), None => (String::new(), String::new(), String::new()), }; let (re_text_right_top, re_text_right_bottom, re_name_right) = match &frag.re_right { Some(re) => ( seq_to_str_lower(&re.overhang_top_right(&[])), // todo: Update this seq_to_str_lower(&re.overhang_bottom_right(&[])), // todo: Update this re.name.clone(), ), None => (String::new(), String::new(), String::new()), }; // todo: Allow viewing and copying fragment seqs, eg from selecting them. // Draw info like fragment length inside the boxes. shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * box_center, Align2::CENTER_CENTER, &format!("{} bp", frag.seq.len()), FontId::new(14., FontFamily::Proportional), Color32::BLACK, ) })); // Left, top shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt_left_top, Align2::RIGHT_CENTER, &re_text_left_top, FontId::new(14., FontFamily::Proportional), Color32::LIGHT_YELLOW, ) })); // Right, top shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt_right_top, Align2::LEFT_CENTER, &re_text_right_top, FontId::new(14., FontFamily::Proportional), Color32::LIGHT_YELLOW, ) })); // Left, bottom shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt_left_bottom, Align2::RIGHT_CENTER, &re_text_left_bottom, FontId::new(14., FontFamily::Proportional), Color32::LIGHT_YELLOW, ) })); // Right, bottom shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * label_pt_right_bottom, Align2::LEFT_CENTER, &re_text_right_bottom, FontId::new(14., FontFamily::Proportional), Color32::LIGHT_YELLOW, ) })); // Text description of which enzymes were used. let enzyme_text = format!("{} | {}", re_name_left, re_name_right); let enzyme_text_pos = to_screen * pos2(end_x + 50., row_px); let source_name_text_pos = to_screen * pos2(end_x + 150., row_px); shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, enzyme_text_pos, Align2::LEFT_CENTER, &enzyme_text, FontId::new(14., FontFamily::Proportional), Color32::LIGHT_RED, ) })); // Show the source name this fragment came from. shapes.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, source_name_text_pos, Align2::LEFT_CENTER, &frag.source_name, FontId::new(14., FontFamily::Proportional), frag_color, ) })); row_px += PRODUCT_ROW_SPACING; } ui.painter().extend(shapes); }); } fn tab_selection( tabs: &mut Vec<usize>, path_loaded: &[Tab], plasmid_names: &[&str], ui: &mut Ui, ) -> bool { let mut clear_res = false; ui.horizontal(|ui| { ui.heading("Opened files to digest"); ui.add_space(COL_SPACING); for (name, i) in get_tab_names(path_loaded, plasmid_names, true) { // todo: DRY with page selectors and Cloning. let selected = tabs.contains(&i); let button = ui.button( select_color_text(&name, selected), // .background_color(TAB_BUTTON_COLOR), ); if button.clicked() { if tabs.contains(&i) { // todo: DRY with res_selected below. for (j, tab_i) in tabs.iter().enumerate() { if i == *tab_i { tabs.remove(j); // This is crude; we only need to re-select REs that were enabled by this tab. clear_res = true; break; } } } else { tabs.push(i); } } ui.add_space(COL_SPACING / 2.); } }); clear_res } // // todo // /// Remove selected res if they are filtered out. // fn filter_res_selected(data: &mut ReUi, lib: &[RestrictionEnzyme]) { // for name in &mut data.res_selected { // let mut re = None; // for re_ in lib { // // if &re_.name == name { // if &re_.name == name { // re = Some(re_.clone()); // break; // } // if re.is_none() { // eprintln!("Error: Unable to find matching RE"); // break; // } // } // // let re = re.unwrap(); // } // } pub fn ligation_page(state: &mut State, ui: &mut Ui) { // todo: Scrolling is not working ScrollArea::vertical().id_salt(100).show(ui, |ui| { // todo: Cache calcs in this fn A/R // Adjust the nucleotide width of digest bars based on the longest sequence selected. let mut longest_seq = 0; for active in &state.ui.re.tabs_selected { if state.generic[*active].seq.len() > longest_seq { longest_seq = state.generic[*active].seq.len(); } } // todo: Don't run this every frame! Store in state, and update it only when something notable changes. let res_matched = filter_res(&state.ui.re, &state.volatile, &state.restriction_enzyme_lib); ui.horizontal(|ui| { ui.heading("Digestion and ligation"); ui.add_space(COL_SPACING * 2.); let mut changed_filters = false; ui.label("Unique cutters only:").on_hover_text("Only display restriction enzymes that cut a sequence exactly once. (Affects display on other pages as well)."); if ui.checkbox(&mut state.ui.re.unique_cutters_only, "").changed() { changed_filters = true; }; ui.add_space(COL_SPACING); ui.label("Sticky ends only:").on_hover_text("Only display restriction enzymes that produce overhangs (sticky ends). Don't show ones that produce blunt ends. (Affects display on other pages as well)."); if ui.checkbox(&mut state.ui.re.sticky_ends_only, "").changed() { changed_filters = true; }; ui.add_space(COL_SPACING); ui.label("2+ sequences only:"); if ui.checkbox(&mut state.ui.re.multiple_seqs, "") .on_hover_text("Only display restriction enzymes that cut two or more selected sequences, if applicable.") .changed() { changed_filters = true; }; ui.add_space(COL_SPACING); // If we've c fmt // hanged filters, update REs selected IRT these filtersx. if changed_filters { // filter_res_selected(&mut state.ui.re, &state.restriction_enzyme_lib); } }); ui.add_space(ROW_SPACING); let plasmid_names: &Vec<_> = &state.generic.iter().map(|v| v.metadata.plasmid_name.as_str()).collect(); let clear_res = tab_selection(&mut state.ui.re.tabs_selected, &state.tabs_open, plasmid_names, ui); if clear_res { state.ui.re.res_selected = Vec::new(); } ui.add_space(ROW_SPACING / 2.); // // todo: This is potentially un-ideal computationally. Note that the name-based code is stored permanently. // // todo: NOte that this is just for the highlights. todo: Just store teh whole Re Match instead of names as state.ui.res_selected. // let mut res_sel = Vec::new(); // for name in &state.ui.re.res_selected { // for re in &state.restriction_enzyme_lib { // if name == &re.name { // res_sel.push(re); // } // } // } for active in &state.ui.re.tabs_selected { seq_lin_disp(&state.generic[*active], true, state.ui.selected_item, &state.ui.re.res_selected, None, &state.ui,&state.volatile[state.active].restriction_enzyme_matches, &state.restriction_enzyme_lib, ui); ui.add_space(ROW_SPACING/2.); } // todo: Highlight common (and later, compatible) RE matches among fragments. ui.horizontal(|ui| { ui.heading("Restriction enzymes matched"); ui.add_space(COL_SPACING); ui.label("Click to select for digestion."); }); let res_per_row = 8; // todo: Based on screen width etc. let num_re_rows = res_matched.len() / res_per_row + 1; for row_i in 0..num_re_rows { ui.horizontal(|ui| { for col_i in 0..res_per_row { let index = row_i * res_per_row + col_i; if index + 1 > res_matched.len() { break; } let re = res_matched[index]; let selected = state.ui.re.res_selected.contains(&re); if ui.button(select_color_text(&re.name, selected)).clicked() { if selected { for (i, re_sel) in state.ui.re.res_selected.iter().enumerate() { if re_sel == re { state.ui.re.res_selected.remove(i); break; } } } else { state.ui.re.res_selected.push(re.clone()); } } ui.label(re.cut_depiction()); ui.add_space(COL_SPACING / 2.); } ui.add_space(COL_SPACING); }); } ui.add_space(ROW_SPACING); ui.horizontal(|ui| { if !state.ui.re.res_selected.is_empty() { if ui .button(RichText::new("Digest").color(COLOR_ACTION)) .clicked() { let mut products = Vec::new(); for active in &state.ui.re.tabs_selected { let source_name = name_from_path( &state.tabs_open[*active].path, &state.generic[*active].metadata.plasmid_name, true, ); products.extend(digest( &source_name, &state.ui.re.res_selected, &state.volatile[*active].restriction_enzyme_matches, &state.restriction_enzyme_lib, &state.generic[*active].seq, state.generic[*active].topology, )); } state.volatile[state.active].re_digestion_products = products; } } if !state.volatile[state.active] .re_digestion_products .is_empty() { // todo: Put back when ready // ui.add_space(COL_SPACING); // if ui // .button(RichText::new("Ligate").color(COLOR_ACTION)) // .clicked() // { // // state.volatile[state.active].re_ligation_products = ligate( // // &state.volatile[state.active].re_digestion_products, // // ); // } } }); // Display the digestion products, draw_graphics( &state.volatile[state.active].re_digestion_products, longest_seq, ui, ); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/theme.rs
src/gui/theme.rs
use eframe::egui::Color32; pub const COLOR_ACTION: Color32 = Color32::GOLD; pub const COLOR_INFO: Color32 = Color32::LIGHT_BLUE;
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/alignment.rs
src/gui/alignment.rs
use eframe::egui::{Color32, FontFamily, FontId, RichText, ScrollArea, TextEdit, Ui}; use na_seq::{seq_aa_from_str, seq_aa_to_str, seq_from_str, seq_to_str_lower}; use crate::{ alignment::{AlignmentMode, align_pairwise_aa, align_pairwise_nt, distance_aa, distance_nt}, gui::{ COL_SPACING, ROW_SPACING, theme::{COLOR_ACTION, COLOR_INFO}, }, state::State, }; fn mode_btn(state: &mut State, mode: AlignmentMode, name: &str, ui: &mut Ui) { let color = if state.alignment.mode == mode { Color32::LIGHT_BLUE } else { Color32::WHITE }; if ui.button(RichText::new(name).color(color)).clicked() { state.alignment.mode = mode; // Reset fields to prevent invalid data. state.alignment.seq_a = Vec::new(); state.alignment.seq_aa_a = Vec::new(); state.alignment.seq_a_input = String::new(); state.alignment.seq_b = Vec::new(); state.alignment.seq_aa_b = Vec::new(); state.alignment.seq_b_input = String::new(); } } fn input_area(state: &mut State, seq_b: bool, ui: &mut Ui) { let (seq, seq_aa, seq_input) = if seq_b { ( &mut state.alignment.seq_a, &mut state.alignment.seq_aa_a, &mut state.alignment.seq_a_input, ) } else { ( &mut state.alignment.seq_b, &mut state.alignment.seq_aa_b, &mut state.alignment.seq_b_input, ) }; let active_seq = state.generic[state.active].seq.clone(); // Avoid borrowing state in the closure ui.horizontal(|ui| { ui.label(if seq_b { "Seq B" } else { "Seq A" }); ui.add_space(COL_SPACING); if let AlignmentMode::Dna = state.alignment.mode { if ui .button(RichText::new("Load active tab's sequence").color(Color32::LIGHT_BLUE)) .clicked() { *seq = active_seq.clone(); // Use the pre-fetched active sequence *seq_input = seq_to_str_lower(seq); } } }); let response = ui.add(TextEdit::multiline(seq_input).desired_width(800.)); if response.changed() { match state.alignment.mode { AlignmentMode::Dna => { *seq = seq_from_str(seq_input); *seq_input = seq_to_str_lower(seq); // Todo: why? // state.sync_seq_related(None); } AlignmentMode::AminoAcid => { *seq_aa = seq_aa_from_str(seq_input); *seq_input = seq_aa_to_str(seq_aa); } } } } pub fn alignment_page(state: &mut State, ui: &mut Ui) { ui.add_space(ROW_SPACING); ui.horizontal(|ui| { ui.heading("Alignment (Work in Progress)"); ui.add_space(COL_SPACING * 2.); mode_btn(state, AlignmentMode::Dna, "DNA", ui); mode_btn(state, AlignmentMode::AminoAcid, "Amino acid", ui); }); ui.add_space(ROW_SPACING); ScrollArea::vertical().id_salt(200).show(ui, |ui| { input_area(state, false, ui); ui.add_space(ROW_SPACING); input_area(state, true, ui); ui.add_space(ROW_SPACING); if ui .button(RichText::new("Align").color(COLOR_ACTION)) .clicked() { let alignment = match state.alignment.mode { AlignmentMode::Dna => { align_pairwise_nt(&state.alignment.seq_a, &state.alignment.seq_b) } AlignmentMode::AminoAcid => { align_pairwise_aa(&state.alignment.seq_aa_a, &state.alignment.seq_aa_b) } }; state.alignment.alignment_result = Some(alignment.0); state.alignment.text_display = alignment.1; state.alignment.dist_result = Some(match state.alignment.mode { AlignmentMode::Dna => distance_nt(&state.alignment.seq_a, &state.alignment.seq_b), AlignmentMode::AminoAcid => { distance_aa(&state.alignment.seq_aa_a, &state.alignment.seq_aa_b) } }); } ui.add_space(ROW_SPACING); if let Some(alignment) = &state.alignment.alignment_result { ui.heading(&format!("Alignment score: {:?}", alignment.score)); ui.add_space(ROW_SPACING); ui.label( RichText::new(&state.alignment.text_display) .color(COLOR_INFO) .font(FontId::new(16., FontFamily::Monospace)), ); } if let Some(dist) = &state.alignment.dist_result { ui.horizontal(|ui| { ui.heading(&format!("Distance score: {:?}", dist)); let dist_type_text = if state.alignment.seq_a.len() == state.alignment.seq_b.len() { "(Hamming)" } else { "(Levenshtein)" }; ui.label(dist_type_text); }); } }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/protein.rs
src/gui/protein.rs
use bio_apis::rcsb::{self, PdbData}; use eframe::{ egui::{ Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, RichText, ScrollArea, Sense, Shape, Stroke, Ui, pos2, vec2, }, emath::RectTransform, epaint::PathShape, }; use na_seq::{AaIdent, AminoAcid}; use crate::{ gui::{ BACKGROUND_COLOR, COL_SPACING, ROW_SPACING, circle::TICK_COLOR, theme::{COLOR_ACTION, COLOR_INFO}, }, misc_types::FeatureType, state::State, }; const COLOR_PROT_SEQ: Color32 = Color32::from_rgb(255, 100, 200); const COLOR_PRE_POST_CODING_SEQ: Color32 = Color32::from_rgb(100, 255, 200); const FONT_SIZE_SEQ: f32 = 14.; const CHART_HEIGHT: f32 = 200.; const CHART_LINE_WIDTH: f32 = 2.; const CHART_LINE_COLOR: Color32 = Color32::from_rgb(255, 100, 100); const NUM_X_TICKS: usize = 12; // todo: Color-code AAs, start/stop codons etc. // todo: Eval how cacheing and state is handled. /// Convert an AA sequence to an ident string. fn make_aa_text(seq: &[AminoAcid], aa_ident_disp: AaIdent) -> String { let mut result = String::new(); for aa in seq { let aa_str = format!("{} ", aa.to_str(aa_ident_disp)); result.push_str(&aa_str); } result } /// Plot a hydrophobicity line plot. fn hydrophobicity_chart(data: &Vec<(usize, f32)>, ui: &mut Ui) { let stroke = Stroke::new(CHART_LINE_WIDTH, CHART_LINE_COLOR); Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let width = ui.available_width(); let (response, _painter) = { let desired_size = vec2(width, CHART_HEIGHT); // ui.allocate_painter(desired_size, Sense::click()) ui.allocate_painter(desired_size, Sense::click_and_drag()) }; let to_screen = RectTransform::from_to( Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); // let from_screen = to_screen.inverse(); const MAX_VAL: f32 = 6.; let mut points = Vec::new(); let num_pts = data.len() as f32; // todo: Consider cacheing the calculations here instead of running this each time. for pt in data { points.push( to_screen * pos2( pt.0 as f32 / num_pts * width, // Offset for 0 baseline. (pt.1 + MAX_VAL / 2.) / MAX_VAL * CHART_HEIGHT, ), ); } let line = Shape::Path(PathShape::line(points, stroke)); let mut x_axis = Vec::new(); if data.len() == 0 { return; } let data_range = data[data.len() - 1].0 - data[0].0; let dr_nt = data_range / NUM_X_TICKS; let x_axis_posit = CHART_HEIGHT - 4.; for i in 0..NUM_X_TICKS { let tick_v = data[0].0 + dr_nt * i; x_axis.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * pos2(i as f32 / NUM_X_TICKS as f32 * width, x_axis_posit), Align2::CENTER_CENTER, tick_v.to_string(), FontId::new(14., FontFamily::Proportional), TICK_COLOR, ) })); } let mut y_axis = Vec::new(); const NUM_Y_TICKS: usize = 7; let data_range = 2. * MAX_VAL; let dr_nt = data_range / NUM_Y_TICKS as f32; let y_axis_posit = 4.; for i in 0..NUM_Y_TICKS { let tick_v = -(-MAX_VAL + dr_nt * i as f32) as i8; y_axis.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, // to_screen * pos2(y_axis_posit, i as f32 / NUM_Y_TICKS as f32 * CHART_HEIGHT), to_screen * pos2(y_axis_posit, i as f32 * dr_nt), Align2::CENTER_CENTER, tick_v.to_string(), FontId::new(14., FontFamily::Proportional), TICK_COLOR, ) })); } let center_axis = Shape::line_segment( [ to_screen * pos2(0., CHART_HEIGHT / 2.), to_screen * pos2(width, CHART_HEIGHT / 2.), ], Stroke::new(1., TICK_COLOR), ); ui.painter().extend([line]); ui.painter().extend(x_axis); // ui.painter().extend(y_axis); ui.painter().extend([center_axis]); }); } fn pdb_links(data: &PdbData, ui: &mut Ui) { ui.horizontal(|ui| { if ui .button(RichText::new("PDB").color(COLOR_ACTION)) .clicked() { rcsb::open_overview(&data.rcsb_id); } if ui.button(RichText::new("3D").color(COLOR_ACTION)).clicked() { rcsb::open_3d_view(&data.rcsb_id); } if ui .button(RichText::new("Structure").color(COLOR_ACTION)) .clicked() { rcsb::open_structure(&data.rcsb_id); } ui.add_space(COL_SPACING / 2.); ui.label( RichText::new(&format!("{}: {}", data.rcsb_id, data.title)) .color(Color32::LIGHT_BLUE) .font(FontId::monospace(14.)), ); }); } fn draw_proteins(state: &mut State, ui: &mut Ui) { for protein in &mut state.volatile[state.active].proteins { ui.horizontal(|ui| { ui.heading(RichText::new(&protein.feature.label).color(COLOR_INFO)); ui.add_space(COL_SPACING); if ui .button(RichText::new("PDB search").color(COLOR_ACTION)) .clicked() { match rcsb::pdb_data_from_seq(&protein.aa_seq) { Ok(pdb_data) => { state.ui.pdb_error_received = false; protein.pdb_data = pdb_data; } Err(_) => { eprintln!("Error fetching PDB results."); state.ui.pdb_error_received = true; } } } if state.ui.pdb_error_received { ui.label(RichText::new("Error getting PDB results").color(Color32::LIGHT_RED)); } // // if !protein.pdb_ids.is_empty() { // ui.add_space(COL_SPACING); // ui.label("Click to open a browser:"); // } }); if !protein.pdb_data.is_empty() { for pdb_result in &protein.pdb_data { // todo: Use a grid layout or similar; take advantage of horizontal space. pdb_links(pdb_result, ui); } ui.add_space(ROW_SPACING / 2.); } ui.horizontal(|ui| { ui.label(format!( "Reading frame: {}, Range: {}", protein.reading_frame_match.frame, protein.reading_frame_match.range )); ui.add_space(COL_SPACING); if protein.weight != protein.weight_with_prepost { // Only show this segment if pre and post-coding sequences exist ui.label(format!( "(Coding region only): AA len: {} Weight: {:.1}kDa", protein.aa_seq.len(), protein.weight, )); ui.add_space(COL_SPACING); } ui.label(format!( "AA len: {} Weight: {:.1}kDa", protein.aa_seq.len() + protein.aa_seq_precoding.len() + protein.aa_seq_postcoding.len(), protein.weight_with_prepost, )); }); ui.add_space(ROW_SPACING / 2.); let aa_text = make_aa_text(&protein.aa_seq, state.ui.aa_ident_disp); let aa_text_precoding = make_aa_text(&protein.aa_seq_precoding, state.ui.aa_ident_disp); let aa_text_postcoding = make_aa_text(&protein.aa_seq_postcoding, state.ui.aa_ident_disp); if !aa_text_precoding.is_empty() { ui.label( RichText::new(aa_text_precoding) .color(COLOR_PRE_POST_CODING_SEQ) .font(FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace)), ); } ui.label( RichText::new(aa_text) .color(COLOR_PROT_SEQ) .font(FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace)), ); if !aa_text_postcoding.is_empty() { ui.label( RichText::new(aa_text_postcoding) .color(COLOR_PRE_POST_CODING_SEQ) .font(FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace)), ); } if protein.show_hydropath { ui.horizontal(|ui| { ui.heading("Hydrophopathy"); ui.add_space(COL_SPACING); ui.label("High values indicate hydrophobic regions; low ones hydrophilic regions."); ui.add_space(COL_SPACING); if ui.button("Hide hydropathy").clicked() { protein.show_hydropath = false; } }); hydrophobicity_chart(&protein.hydropath_data, ui); } else { if ui.button("Show hydrophpathy").clicked() { protein.show_hydropath = true; } } ui.add_space(ROW_SPACING * 2.); } } pub fn protein_page(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { ui.heading("Proteins, from coding regions"); ui.add_space(COL_SPACING); ui.label("One letter ident:"); let mut one_letter = state.ui.aa_ident_disp == AaIdent::OneLetter; if ui.checkbox(&mut one_letter, "").changed() { state.ui.aa_ident_disp = if one_letter { AaIdent::OneLetter } else { AaIdent::ThreeLetters }; } }); ui.add_space(ROW_SPACING); if state.generic[state.active] .features .iter() .any(|f| f.feature_type == FeatureType::CodingRegion) { ScrollArea::vertical().id_salt(200).show(ui, |ui| { draw_proteins(state, ui); }); } else { ui.label("Create one or more Coding Region feature to display proteins here."); } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/navigation.rs
src/gui/navigation.rs
//! This module contains code related to navigation buttons. use std::{fmt::Display, path::PathBuf}; use bincode::{Decode, Encode}; use eframe::egui::{Color32, RichText, Ui}; use na_seq::seq_to_str_lower; use crate::{ gui::{COL_SPACING, ROW_SPACING, select_color_text, set_window_title}, state::State, }; pub const NAV_BUTTON_COLOR: Color32 = Color32::from_rgb(0, 0, 110); pub const TAB_BUTTON_COLOR: Color32 = Color32::from_rgb(40, 80, 110); pub const DEFAULT_TAB_NAME: &str = "New plasmid"; // When abbreviating a path, show no more than this many characters. const PATH_ABBREV_MAX_LEN: usize = 16; // todo: Alt name: Path loaded #[derive(Encode, Decode, Clone, Default, Debug)] pub struct Tab { pub path: Option<PathBuf>, pub ab1: bool, // todo: Enum if you add a third category. } /// Used in several GUI components to get data from open tabs. /// Note: For name, we currently default to file name (with extension), then /// plasmid name, then a default. See if you want to default to plasmid name. /// /// Returns the name, and the tab index. pub fn get_tab_names( tabs: &[Tab], plasmid_names: &[&str], abbrev_name: bool, ) -> Vec<(String, usize)> { let mut result = Vec::new(); for (i, p) in tabs.iter().enumerate() { let name = name_from_path(&p.path, plasmid_names[i], abbrev_name); result.push((name, i)); } result } #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum Page { /// Primer design and QC, including for cloning Sequence, /// A circular "graphical map" of the plasmid Map, Features, Primers, Proteins, /// Determine optimal PCR parameters Pcr, Alignment, Portions, Metadata, Ligation, /// A simplified cloning process, for both PCR and RE-based cloning. Cloning, /// i.e. Sanger sequencing data. This page is fundamentally different from the others; /// it is only for .ab1 files, and is selected automatically, vice from the menu. Ab1, } impl Default for Page { fn default() -> Self { Self::Sequence } } impl Display for Page { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Sequence => "Sequence", Self::Map => "Map", Self::Features => "Features", Self::Primers => "Primers", Self::Proteins => "Proteins", Self::Pcr => "PCR", Self::Alignment => "Align", Self::Portions => "Mixing", Self::Metadata => "Data", Self::Ligation => "Digest", Self::Cloning => "Clone", Self::Ab1 => "AB1", } .to_owned(); write!(f, "{}", str) } } /// Selects which tab (ie file) is active pub fn tab_selector(state: &mut State, ui: &mut Ui) { // Note: This assumes generic, paths_loaded etc are always the same length. (Which they *should* be.) let mut tab_removed = None; ui.horizontal(|ui| { if ui .button("New") .on_hover_text("Create and open a new file. (Ctrl + N)") .clicked() { state.add_tab(); state.tabs_open.push(Default::default()); } ui.add_space(COL_SPACING); let plasmid_names: &Vec<_> = &state .generic .iter() .map(|v| v.metadata.plasmid_name.as_str()) .collect(); for (name, i) in get_tab_names(&state.tabs_open, plasmid_names, false) { // todo: DRY with page selectors. let button = ui.button( select_color_text(&name, i == state.active).background_color(TAB_BUTTON_COLOR), ); if button.clicked() { state.active = i; set_window_title(&state.tabs_open[i], ui); // todo: Apt state sync fn for this? state.ui.seq_input = seq_to_str_lower(state.get_seq()); // todo: Move seq_input to an indexed vector? // todo: Cache these instead? // state.sync_seq_related(None); } if button.middle_clicked() { tab_removed = Some(i); } ui.add_space(COL_SPACING / 2.); } // todo: Right-align? ui.add_space(2. * ROW_SPACING); if ui .button( RichText::new("Close active tab") .color(Color32::WHITE) .background_color(Color32::DARK_RED), ) .on_hover_text("Shortcut: Middle click the tab to close it.") .clicked() { tab_removed = Some(state.active) }; }); if let Some(i) = tab_removed { state.remove_tab(i); } } pub fn page_selector(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { page_button(&mut state.ui.page, Page::Sequence, ui, true); page_button(&mut state.ui.page, Page::Map, ui, true); page_button(&mut state.ui.page, Page::Features, ui, true); page_button(&mut state.ui.page, Page::Primers, ui, true); page_button(&mut state.ui.page, Page::Proteins, ui, true); page_button(&mut state.ui.page, Page::Cloning, ui, true); page_button(&mut state.ui.page, Page::Pcr, ui, true); page_button(&mut state.ui.page, Page::Alignment, ui, true); page_button(&mut state.ui.page, Page::Ligation, ui, true); page_button(&mut state.ui.page, Page::Metadata, ui, true); page_button(&mut state.ui.page, Page::Portions, ui, true); }); } pub fn page_button<T: PartialEq + ToString>(page_state: &mut T, page: T, ui: &mut Ui, space: bool) { if ui .button( select_color_text(&page.to_string(), *page_state == page) .background_color(NAV_BUTTON_COLOR), ) .clicked() { *page_state = page; } if space { ui.add_space(COL_SPACING / 2.); } } /// This is used for selecting what is displayed in the sequence view, ie view or edit. #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum PageSeq { EditRaw, // EditSlic, View, } impl Default for PageSeq { fn default() -> Self { Self::View } } impl Display for PageSeq { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::EditRaw => "Edit raw", // Self::EditSlic => "SLIC/FC cloning", Self::View => "Sequence", } .to_owned(); write!(f, "{}", str) } } pub fn page_seq_selector(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { page_button(&mut state.ui.page_seq, PageSeq::EditRaw, ui, true); page_button(&mut state.ui.page_seq, PageSeq::View, ui, true); }); } /// This is used for selecting what is displayed above the sequence view, ie various tabular editors. #[derive(Clone, Copy, PartialEq, Encode, Decode)] pub enum PageSeqTop { Primers, Features, None, } impl Default for PageSeqTop { fn default() -> Self { Self::None } } impl Display for PageSeqTop { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Self::Primers => "Primers", Self::Features => "Features", Self::None => "None", } .to_owned(); write!(f, "{}", str) } } pub fn page_seq_top_selector(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { ui.label("Display above sequence:"); page_button(&mut state.ui.page_seq_top, PageSeqTop::None, ui, true); page_button(&mut state.ui.page_seq_top, PageSeqTop::Features, ui, true); page_button(&mut state.ui.page_seq_top, PageSeqTop::Primers, ui, true); }); } /// A short, descriptive name for a given opened tab. pub fn name_from_path(path: &Option<PathBuf>, plasmid_name: &str, abbrev_name: bool) -> String { let mut name = match path { Some(path) => path .file_name() .and_then(|name| name.to_str()) .map(|name_str| name_str.to_string()) .unwrap(), None => { if !plasmid_name.is_empty() { plasmid_name.to_owned() } else { DEFAULT_TAB_NAME.to_owned() } } }; if abbrev_name && name.len() > PATH_ABBREV_MAX_LEN { name = format!("{}...", &name[..PATH_ABBREV_MAX_LEN].to_string()) } name }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/circle.rs
src/gui/circle.rs
//! A module for the circular view of a plasmid use core::f32::consts::TAU; use eframe::{ egui::{ Align2, Color32, CursorIcon, FontFamily, FontId, Frame, Pos2, Rect, RichText, ScrollArea, Sense, Shape, Slider, Stroke, Ui, pos2, vec2, }, emath::RectTransform, epaint::{CircleShape, PathShape}, }; use na_seq::{ restriction_enzyme::{ReMatch, RestrictionEnzyme}, seq_to_str_lower, }; use crate::{ Selection, gui::{ COL_SPACING, COLOR_RE, COLOR_SEQ, PRIMER_FWD_COLOR, ROW_SPACING, SPLIT_SCREEN_MAX_HEIGHT, feature_from_index, feature_table::feature_table, get_cursor_text, lin_maps, lin_maps::MINI_DISP_NT_LEN, navigation::NAV_BUTTON_COLOR, select_feature, }, misc_types::{Feature, FeatureDirection, FeatureType}, primer::Primer, state::State, }; const BACKGROUND_COLOR: Color32 = Color32::from_rgb(10, 20, 10); const BACKBONE_COLOR: Color32 = Color32::from_rgb(180, 180, 180); const BACKBONE_WIDTH: f32 = 10.; pub const TICK_COLOR: Color32 = Color32::from_rgb(180, 220, 220); const TICK_WIDTH: f32 = 2.; pub const RE_WIDTH: f32 = 2.; const TICK_SPACING: usize = 500; // Nucleotides between ticks const TICK_LEN: f32 = 90.; // in pixels. const TICK_LEN_DIV_2: f32 = TICK_LEN / 2.; const TICK_LABEL_OFFSET: f32 = 12.; pub const FEATURE_OUTLINE_COLOR: Color32 = Color32::from_rgb(200, 200, 255); // const FEATURE_OUTLINE_HIGHLIGHTED: Color32 = Color32::from_rgb(200, 200, 255); pub const FEATURE_OUTLINE_SELECTED: Color32 = Color32::RED; const RE_LEN: f32 = 50.; // in pixels. const RE_LEN_DIV_2: f32 = RE_LEN / 2.; const RE_LABEL_OFFSET: f32 = 10.; // We may use per-feature-type widths, but have this for now. const FEATURE_WIDTH_DEFAULT: f32 = 26.; pub const FEATURE_STROKE_WIDTH: f32 = 3.; const PRIMER_WIDTH: f32 = 54.; pub const PRIMER_STROKE_WIDTH: f32 = 2.; const TIP_LEN: f32 = 0.03; // Len of arrow tips, in radians const TIP_WIDTH_RATIO: f32 = 1.5; // Compared to its feature width. // Radius, comparedd to the available width or height (whichever is lower). const CIRCLE_SIZE_RATIO: f32 = 0.42; // The maximum distance the cursor can be from the circle for various tasks like selection, finding // the cursor position etc. const SELECTION_MAX_DIST: f32 = 80.; const CENTER_TEXT_ROW_SPACING: f32 = 20.; const FEATURE_SLIDER_WIDTH: f32 = 180.; // We limit each filled concave shape to a circumfrence segment this long, as part of a workaround to EGUI not having a great // way to draw concave shapes. const _MAX_ARC_FILL: f32 = 230.; const VERITICAL_CIRCLE_OFFSET: f32 = 22.; // Useful for leaving room for the zoomed view. /// These aguments define the circle, and are used in many places in this module. pub struct CircleData { pub seq_len: usize, pub center: Pos2, pub radius: f32, pub to_screen: RectTransform, pub from_screen: RectTransform, /// This is `from_screen * center`. We store it here to cache. pub center_rel: Pos2, } impl CircleData { /// Automatically populates `center_rel` and `from_screen`. fn new(seq_len: usize, center: Pos2, radius: f32, to_screen: RectTransform) -> Self { let center_rel = to_screen * center; let from_screen = to_screen.inverse(); Self { seq_len, center, radius, to_screen, from_screen, center_rel, } } } /// Create points for an arc. Can be used with line_segment to draw the arc. /// Two of these can be used with convex_polygon to make a filled arc segment. // Adapted from PR https://github.com/emilk/egui/pull/4836/files fn arc_points(center: Pos2, radius: f32, start_angle: f32, end_angle: f32) -> Vec<Pos2> { let num_segs = if radius <= 2.0 { 8 } else if radius <= 5.0 { 16 } else if radius < 18.0 { 32 } else if radius < 50.0 { 64 } else { 128 }; let angle = (end_angle - start_angle).clamp(-TAU + f32::EPSILON, TAU - f32::EPSILON); let mut points = Vec::with_capacity(num_segs + 3); let step = angle / num_segs as f32; for i in 0..=num_segs { let a = start_angle + step * i as f32; points.push(angle_to_pixel(a, radius) + center.to_vec2()); } points } /// Return the angle in radians of a given sequence index. fn seq_i_to_angle(seq_i: usize, seq_len: usize) -> f32 { TAU * seq_i as f32 / seq_len as f32 // todo: Include mapping to pixels here, or elsewhere? } /// Return the sequence index, corresponding to an angle in radians. fn angle_to_seq_i(mut angle: f32, seq_len: usize) -> usize { if angle < 0. { // Our index-finding logic will fail unless the angle is positive. angle += TAU; } (angle * seq_len as f32 / TAU) as usize } /// Convert an angle, in radians, to pixels. Our origin is at the top, and the direction /// is clockwise. fn angle_to_pixel(angle: f32, radius: f32) -> Pos2 { // Offset and reverse the angle to reflect an origin of 0. let angle = angle - TAU / 4.; pos2(angle.cos() * radius, angle.sin() * radius) } /// Draw a tick every 1kbp. fn draw_ticks(data: &CircleData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); for i_div_1k in 0..data.seq_len / TICK_SPACING { let i = i_div_1k * TICK_SPACING; let angle = seq_i_to_angle(i, data.seq_len); let point_inner = angle_to_pixel(angle, data.radius - TICK_LEN_DIV_2) + data.center.to_vec2(); let point_outer = angle_to_pixel(angle, data.radius + TICK_LEN_DIV_2) + data.center.to_vec2(); result.push(Shape::line_segment( [data.to_screen * point_inner, data.to_screen * point_outer], Stroke::new(TICK_WIDTH, TICK_COLOR), )); let (label_pt, label_align) = if angle > TAU / 2. { ( point_outer + vec2(-TICK_LABEL_OFFSET, 0.), Align2::RIGHT_CENTER, ) } else { ( point_outer + vec2(TICK_LABEL_OFFSET, 0.), Align2::LEFT_CENTER, ) }; result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * label_pt, label_align, i.to_string(), FontId::new(16., FontFamily::Proportional), TICK_COLOR, ) })); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * label_pt, label_align, i.to_string(), FontId::new(16., FontFamily::Proportional), TICK_COLOR, ) })); } result } /// Created a filled-in arc. E.g. for features. fn draw_filled_arc( data: &CircleData, angle: (f32, f32), width: f32, fill_color: Color32, stroke: Stroke, ) -> Vec<Shape> { let mut points_outer = arc_points(data.center_rel, data.radius + width / 2., angle.0, angle.1); let mut points_inner = arc_points(data.center_rel, data.radius - width / 2., angle.0, angle.1); points_inner.reverse(); // todo: Confirm this is going clockwise, for nominal performance reasons. points_outer.append(&mut points_inner); let mut result = Vec::new(); result.push(Shape::convex_polygon(points_outer, fill_color, stroke)); // We divide our result into a single line segment, and multiple filled areas. This is to work around // EGUI's limitation regarding filling concave shapes. // result.push(Shape::closed_line(points_outer, stroke)); // Draw filled segments. It appears the limitation is based on segment absolute size, vice angular size. // No segment will be larger than our threshold. // let circum_segment = data.radius * (angle.1 - angle.0); // let num_segments = (MAX_ARC_FILL / circum_segment) as usize + 1; // let segment_ang_dist = (angle.1 - angle.0) / num_segments as f32; // // for i in 0..num_segments { // continue; // let ang_seg = ( // angle.0 + i as f32 * segment_ang_dist, // angle.0 + (i + 1) as f32 * segment_ang_dist, // ); // // println!("ANG SEG: {:.4?}. Orig: {:.4?}", ang_seg, angle); // // todo: DRY // let mut points_outer = arc_points( // data.center_rel, // data.radius + width / 2., // ang_seg.0, // ang_seg.1, // ); // let mut points_inner = arc_points( // data.center_rel, // data.radius - width / 2., // ang_seg.0, // ang_seg.1, // ); // // points_inner.reverse(); // // points_outer.append(&mut points_inner); // // // result.push(Shape::convex_polygon(points_outer, fill_color, Stroke::NONE)); // result.push(Shape::convex_polygon( // points_outer, // Color32::YELLOW, // Stroke::NONE, // )); // } // Note: We may need to put something like this back, if we use multiple feature widths, feature layers etc.\ // todo: Perhaps instead of drawing a pie, we draw slimmer slices. let points_patch = arc_points( data.center_rel, data.radius - width / 2. - stroke.width / 2., angle.0, angle.1, ); // points_patch.push(data.center); result.push(Shape::convex_polygon( points_patch, BACKGROUND_COLOR, Stroke::NONE, )); result } /// This is a fancy way of saying triangle. fn draw_arrowhead( data: &CircleData, width: f32, angle: (f32, f32), color: Color32, stroke: Stroke, ) -> Shape { let center = data.center.to_vec2(); let base_outer = data.to_screen * angle_to_pixel(angle.0, data.radius + width / 2.) + center; let base_inner = data.to_screen * angle_to_pixel(angle.0, data.radius - width / 2.) + center; let tip = data.to_screen * angle_to_pixel(angle.1, data.radius) + center; // Points arranged clockwise for performance reasons. let points = if angle.1 > angle.0 { vec![base_outer, tip, base_inner] } else { vec![base_inner, tip, base_outer] }; Shape::convex_polygon(points, color, stroke) } fn draw_features( features: &[Feature], data: &CircleData, selected: Selection, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, feature) in features.iter().enumerate() { // Draw the arc segment. // Source features generally take up the whole plasmid length. // Alternative: Filter by features that take up the whole length. if feature.feature_type == FeatureType::Source { continue; } // todo: Adjust feature, tick etc width (stroke width, and dimensions from cicle) based on window size. // todo: Sort out how to handle feature widths. Byy type? let feature_width = FEATURE_WIDTH_DEFAULT; // todo: Sort out color, as you have a note elsewhere. Type or custom? Type with avail override? let (r, g, b) = feature.color(); let feature_color = Color32::from_rgb(r, g, b); let stroke_color = match selected { Selection::Feature(j) => { if j == i { FEATURE_OUTLINE_SELECTED } else { FEATURE_OUTLINE_COLOR } } _ => FEATURE_OUTLINE_COLOR, }; let stroke = Stroke::new(FEATURE_STROKE_WIDTH, stroke_color); let angle_start = seq_i_to_angle(feature.range.start, data.seq_len); let mut angle_end = seq_i_to_angle(feature.range.end, data.seq_len); // This allows for wraps around the origin, without changing other code. if angle_end < angle_start { angle_end += TAU; } // We subtract parts from the start or end angle for the arrow tip, if present. let angle = match feature.direction { FeatureDirection::None => (angle_start, angle_end), FeatureDirection::Forward => (angle_start, angle_end - TIP_LEN), FeatureDirection::Reverse => (angle_start + TIP_LEN, angle_end), }; result.append(&mut draw_filled_arc( data, angle, feature_width, feature_color, stroke, )); // if i == features.len() - 1 { // // Egui doesn't support concave fills; convex_polygon will spill into the interior concave part. // // Patch this by filling over this with a circle. This is roughly the inner points plus the center point, // // but slightly inwards as not to override the feature edge. // // // Draw this after feature bodies, and before arrows, and all other things. // // // Note: This single-circle approach will only work for constant size feature widths. // // // This insert location, or something similar, is required. // // // todo: WHy is this overriding the arrow heads? // result.push(Shape::Circle(CircleShape::filled(data.center_rel, // data.radius - FEATURE_WIDTH_DEFAULT / 2. - 3. / 2., BACKGROUND_COLOR) // // )); // } // Draw the label. let angle_mid = (angle.0 + angle.1) / 2.; let point_mid_outer = angle_to_pixel(angle_mid, data.radius + feature_width / 2.) + data.center.to_vec2(); let (mut label_pt, label_align) = if angle_mid > TAU / 2. { ( point_mid_outer + vec2(-TICK_LABEL_OFFSET, 0.), Align2::RIGHT_CENTER, ) } else { ( point_mid_outer + vec2(TICK_LABEL_OFFSET, 0.), Align2::LEFT_CENTER, ) }; // If towards the very top of bottom, offset the label vertically. if angle_mid < TAU / 16. || angle_mid > 15. * TAU / 16. { label_pt += vec2(0., -TICK_LABEL_OFFSET); } else if angle_mid > 7. * TAU / 16. && angle_mid < 9. * TAU / 16. { label_pt += vec2(0., TICK_LABEL_OFFSET); } // todo: Rotate, and place the label inside the arc segment. Unfortunately, rotating text // todo is currently difficult with EGUI. // "At the moment this is somewhat tricky; you will need to first produce a ClippedShape with the // text you want in it. Then you can use ctx.tesselate() to turn this into a Mesh. Use the // rotate method on that mesh. Then you can draw that with the Painter" result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * label_pt, label_align, feature.label(), FontId::new(14., FontFamily::Proportional), stroke.color, ) })); // Draw the tip if feature.direction != FeatureDirection::None { let tip_angle = match feature.direction { FeatureDirection::Forward => (angle_end - TIP_LEN, angle_end), FeatureDirection::Reverse => (angle_start + TIP_LEN, angle_start), _ => unreachable!(), }; result.push(draw_arrowhead( data, feature_width * TIP_WIDTH_RATIO, tip_angle, feature_color, stroke, )); } } result } /// todo: C+P from draw_features! Build this into the feature one like you did in seq view. fn draw_primers( primers: &[Primer], data: &CircleData, selected_item: Selection, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); let radius_outer = data.radius + PRIMER_WIDTH / 2.; let radius_inner = data.radius - PRIMER_WIDTH / 2.; for (i, primer) in primers.iter().enumerate() { // todo: Do not run these calcs each time. Cache. for prim_match in &primer.volatile.matches { let angle_start = seq_i_to_angle(prim_match.range.start, data.seq_len); let angle_end = seq_i_to_angle(prim_match.range.end, data.seq_len); let angle_mid = (angle_start + angle_end) / 2.; let point_start_inner = angle_to_pixel(angle_start, radius_inner) + data.center.to_vec2(); let point_start_outer = angle_to_pixel(angle_start, radius_outer) + data.center.to_vec2(); let point_end_inner = angle_to_pixel(angle_end, radius_inner) + data.center.to_vec2(); let point_end_outer = angle_to_pixel(angle_end, radius_outer) + data.center.to_vec2(); let point_mid_outer = angle_to_pixel(angle_mid, radius_outer) + data.center.to_vec2(); let mut outline_color = prim_match.direction.color(); if let Selection::Primer(sel_i) = selected_item { if sel_i == i { outline_color = Color32::RED; } } let stroke = Stroke::new(PRIMER_STROKE_WIDTH, outline_color); result.push(Shape::Path(PathShape::line( arc_points(data.center_rel, radius_outer, angle_start, angle_end), stroke, ))); result.push(Shape::Path(PathShape::line( arc_points(data.center_rel, radius_inner, angle_start, angle_end), stroke, ))); // Lines connected the inner and outer arcs. result.push(Shape::line_segment( [ data.to_screen * point_start_inner, data.to_screen * point_start_outer, ], stroke, )); result.push(Shape::line_segment( [ data.to_screen * point_end_inner, data.to_screen * point_end_outer, ], stroke, )); // todo: A/R let (label_pt, label_align) = if angle_mid > TAU / 2. { ( point_mid_outer + vec2(-TICK_LABEL_OFFSET, 0.), Align2::RIGHT_CENTER, ) } else { ( point_mid_outer + vec2(TICK_LABEL_OFFSET, 0.), Align2::LEFT_CENTER, ) }; result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * label_pt, label_align, &primer.name, FontId::new(14., FontFamily::Proportional), stroke.color, ) })); } } result } /// Change the selected feature's range from the sequence or map views. /// todo: Move out of circle.rs, as it's also used in the seq view now. pub fn feature_range_sliders(state: &mut State, ui: &mut Ui) { if let Selection::Feature(feat_i) = &mut state.ui.selected_item { ui.spacing_mut().slider_width = FEATURE_SLIDER_WIDTH; let seq_len = state.generic[state.active].seq.len(); if *feat_i >= state.generic[state.active].features.len() { eprintln!("Invalid selected feature"); state.ui.selected_item = Selection::None; } else { let feature = &mut state.generic[state.active].features[*feat_i]; // todo: Handle wraps. ui.label("Start:"); ui.add(Slider::new(&mut feature.range.start, 0..=seq_len)); ui.add_space(COL_SPACING); ui.label("End:"); ui.add(Slider::new(&mut feature.range.end, 0..=seq_len)); // todo: Don't let end be before start. // if feature.range.start > feature.range.end { // feature.range.end = feature.range.start + 1; // } } } } fn top_details(state: &mut State, ui: &mut Ui) { // todo: A/R // display_filters(&mut state.ui, ui); // We re-impl display_filters to, to avoid having reading frames. Change A/R. let name = if state.ui.re.unique_cutters_only { "Single cut sites" } else { "RE sites" } .to_owned(); ui.label(name); ui.checkbox(&mut state.ui.seq_visibility.show_res, ""); ui.add_space(COL_SPACING / 2.); ui.label("Features:"); ui.checkbox(&mut state.ui.seq_visibility.show_features, ""); ui.add_space(COL_SPACING / 2.); ui.label("Primers:"); ui.checkbox(&mut state.ui.seq_visibility.show_primers, ""); ui.add_space(COL_SPACING / 2.); // Sliders to edit the feature. feature_range_sliders(state, ui); ui.add_space(COL_SPACING); ui.label("Cursor:"); let cursor_posit_text = get_cursor_text(state.ui.cursor_seq_i, state.get_seq().len()); ui.heading(cursor_posit_text); } /// Find the sequence index under the cursor, if it is over the sequence. fn find_cursor_i(cursor_pos: Option<(f32, f32)>, data: &CircleData) -> Option<usize> { match cursor_pos { Some(p) => { let pos_rel = data.from_screen * pos2(p.0, p.1); let diff = vec2(pos_rel.x - data.center.x, pos_rel.y - data.center.y); let cursor_dist = diff.length(); if (cursor_dist - data.radius).abs() > SELECTION_MAX_DIST { return None; } // Shifted so 0 is at the top. let angle = diff.angle() + TAU / 4.; Some(angle_to_seq_i(angle, data.seq_len)) } None => None, } } /// Helper fn. fn draw_text(text: &str, pos: Pos2, font_size: f32, color: Color32, ui: &mut Ui) -> Shape { ui.ctx().fonts(|fonts| { Shape::text( fonts, pos, Align2::CENTER_CENTER, text, FontId::new(font_size, FontFamily::Proportional), color, ) }) } /// Draw RE cut sites through the circle. /// todo: DRY with tick drawing code. fn draw_re_sites( re_matches: &[ReMatch], res: &[RestrictionEnzyme], data: &CircleData, unique_cutters_only: bool, sticky_ends_only: bool, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, re_match) in re_matches.iter().enumerate() { if re_match.lib_index >= res.len() { eprintln!("Invalid RE selected"); return result; } let re = &res[re_match.lib_index]; if (unique_cutters_only && re_match.match_count > 1) || (sticky_ends_only && re.makes_blunt_ends()) { continue; } let cut_i = re_match.seq_index + 1; // to display in the right place. let angle = seq_i_to_angle(cut_i + re.cut_after as usize, data.seq_len); let point_inner = angle_to_pixel(angle, data.radius - RE_LEN_DIV_2) + data.center.to_vec2(); let point_outer = angle_to_pixel(angle, data.radius + RE_LEN_DIV_2) + data.center.to_vec2(); result.push(Shape::line_segment( [data.to_screen * point_inner, data.to_screen * point_outer], Stroke::new(RE_WIDTH, COLOR_RE), )); let (mut label_pt, label_align) = if angle > TAU / 2. { ( point_outer + vec2(-RE_LABEL_OFFSET, 0.), Align2::RIGHT_CENTER, ) } else { (point_outer + vec2(RE_LABEL_OFFSET, 0.), Align2::LEFT_CENTER) }; // Alternate label vertical position, to reduce changes of overlaps. if i % 2 == 0 { label_pt.y += 22.; } result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * label_pt, label_align, &re.name, FontId::new(16., FontFamily::Proportional), COLOR_RE, ) })); } result } /// For drawing feature data in the center of the circle. This may be used for the feature hovered over, /// or selected. fn draw_feature_text(feature: &Feature, data: &CircleData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); let labels = vec![ feature.label.clone(), feature.location_descrip(data.seq_len), feature.feature_type.to_string(), ]; let (r, g, b) = feature.color(); let color = Color32::from_rgb(r, g, b); let mut i = 0; // Rows for label in &labels { result.push(draw_text( label, data.to_screen * pos2( data.center.x, data.center.y + i as f32 * CENTER_TEXT_ROW_SPACING - 60., ), 16., color, ui, )); // slightly below seq name, ui)); i += 1; } for note in &feature.notes { // Don't let a note overflow. Note: Wrapping would be preferred to this cutoff. let max_len = (0.2 * data.radius) as usize; // Note: This depends on font size. // Newlines will interfere with our current line-spacing system. let text: String = format!("{}: {}", note.0, note.1.replace('\n', " ")) .chars() .take(max_len) .collect(); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * pos2( data.center.x - data.radius * 0.8, data.center.y + i as f32 * CENTER_TEXT_ROW_SPACING - 60., ), Align2::LEFT_CENTER, &text, FontId::new(13., FontFamily::Proportional), TICK_COLOR, ) })); i += 1; } result } /// Similar to `draw_feature_text`. fn draw_primer_text(primer: &Primer, data: &CircleData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); let labels = vec![ primer.name.clone(), primer.location_descrip(), primer.description.clone().unwrap_or_default(), seq_to_str_lower(&primer.sequence), ]; // let color = match primer.direction { // PrimerDirection::Forward => PRIMER_FWD_COLOR, // PrimerDirection::Reverse => PRIMER_REV_COLOR, // }; // // todo: Rev or neutral A/R let color = PRIMER_FWD_COLOR; let mut i = 0; // Rows for label in &labels { result.push(draw_text( label, data.to_screen * pos2( data.center.x, data.center.y + i as f32 * CENTER_TEXT_ROW_SPACING - 60., ), 16., color, ui, )); // slightly below seq name, ui)); i += 1; } result } /// Draw text in the center of the circle; eg general plasmid information, or information /// about a feature. This is the selected feature if available; then hovered-over if available; /// then general plasmid information. fn draw_center_text(data: &CircleData, state: &mut State, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); // todo: This nesting is a bit complicated. match &state.ui.selected_item { Selection::Feature(feat_i) => { if state.generic[state.active].features.len() + 1 < *feat_i { eprintln!("Invalid selected feature"); } let feature = &state.generic[state.active].features[*feat_i]; result.append(&mut draw_feature_text(feature, data, ui)); } Selection::Primer(prim_i) => { if *prim_i >= state.generic[state.active].primers.len() { eprintln!("Invalid primer."); return result; } let primer = &state.generic[state.active].primers[*prim_i]; result.append(&mut draw_primer_text(primer, data, ui)); } Selection::None => { match &state.ui.feature_hover { Some(feat_i) => { if *feat_i >= state.generic[state.active].features.len() { eprintln!("Invalid hover feature"); } let feature = &state.generic[state.active].features[*feat_i]; result.append(&mut draw_feature_text(feature, data, ui)); } None => { // Display a summary of the plasmid result.push(draw_text( &state.generic[state.active].metadata.plasmid_name, data.center_rel, 16., TICK_COLOR, ui, )); result.push(draw_text( &format!("{} bp", data.seq_len), pos2(data.center_rel.x, data.center_rel.y + 20.), 13., TICK_COLOR, ui, )); } } } } result } // todo: Delete /// Draw a small view of the sequence under the cursor. fn _draw_mini_seq(data: &CircleData, state: &State, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); const OFFSET: Pos2 = pos2(4., 6.); let seq_full_len = state.get_seq().len(); if seq_full_len < 10 { return result; } if let Some(i) = state.ui.cursor_seq_i { let seq_mini_len = (ui.available_width() / 11.) as usize; let mut start = i as isize - seq_mini_len as isize / 2; let mut end = i + seq_mini_len / 2; if start < 0 { start = 0; } if end + 1 >= seq_full_len && seq_full_len > 0 { end = seq_full_len - 1; } let start = start as usize; let seq = &state.get_seq()[start..end]; let seq_text = seq_to_str_lower(seq); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, data.to_screen * OFFSET, Align2::LEFT_CENTER, &seq_text, FontId::new(16., FontFamily::Monospace), COLOR_SEQ, ) })); } result } pub fn circle_page(state: &mut State, ui: &mut Ui) { let mut shapes = Vec::new(); // todo: ABility to select light mode, and other tools useful for publication. if !state.ui.hide_map_feature_editor { // Limit the top section height. let screen_height = ui.ctx().available_rect().height(); let half_screen_height = screen_height / SPLIT_SCREEN_MAX_HEIGHT; Frame::none().show(ui, |ui| { ScrollArea::vertical() .max_height(half_screen_height) .show(ui, |ui| { feature_table(state, ui); }); }); ui.add_space(ROW_SPACING / 2.); ui.horizontal(|ui| { if ui .button(RichText::new("Hide editor").background_color(NAV_BUTTON_COLOR)) .clicked() { state.ui.hide_map_feature_editor = true; } top_details(state, ui); }); ui.add_space(ROW_SPACING / 2.); } else { ui.horizontal(|ui| { if ui .button(RichText::new("Show feature editor").background_color(NAV_BUTTON_COLOR)) .clicked() { state.ui.hide_map_feature_editor = false; } ui.add_space(COL_SPACING); top_details(state, ui); }); } ui.ctx() .set_cursor_icon(if state.ui.feature_hover.is_some() { CursorIcon::PointingHand } else { CursorIcon::Default }); Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let (response, _painter) = { let desired_size = vec2(ui.available_width(), ui.available_height()); ui.allocate_painter(desired_size, Sense::click()) }; let to_screen = RectTransform::from_to( // Rect::from_min_size(pos2(0., -VERITICAL_CIRCLE_OFFSET), response.rect.size()), Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); let rect_size = response.rect.size(); let center = pos2(rect_size.x / 2., rect_size.y / 2. + VERITICAL_CIRCLE_OFFSET); let width_min = rect_size.x < rect_size.y;
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
true
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/mod.rs
src/gui/mod.rs
//! GUI entry point //! //! [Useful emojis supported by EGUI](https://github.com/emilk/egui/blob/9a1e358a144b5d2af9d03a80257c34883f57cf0b/crates/egui/src/lib.rs#L557-L575) //! ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷ //! ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃 //! ☀☁★☆☐☑☜☝☞☟⛃⛶✔ //! ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫ //! ♡ //! 📅📆 //! 📈📉📊 //! 📋📌📎📤📥🔆 //! 🔈🔉🔊🔍🔎🔗🔘 //! 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓ //! //! Also maybe: http://jslegers.github.io/emoji-icon-font/ //! https://fonts.google.com/noto/specimen/Noto+Emoji //! //! Note: business logic should be kept out of this module (and its sub-modules), when practical. use std::path::PathBuf; use eframe::{ egui, egui::{Color32, Context, RichText, TextEdit, ThemePreference, Ui, ViewportCommand, pos2}, emath::RectTransform, }; use navigation::Page; use crate::{ Selection, external_websites, feature_db_load::find_features, gui::{ input::handle_input, navigation::Tab, primer_table::primer_details, theme::COLOR_ACTION, }, misc_types::{Feature, FeatureType}, primer::Primer, state::State, util, util::{get_window_title, merge_feature_sets}, }; mod ab1; mod alignment; mod circle; mod cloning; mod feature_table; mod input; mod ligation; mod lin_maps; mod metadata; pub mod navigation; mod pcr; mod portions; pub mod primer_table; mod protein; pub mod save; pub mod sequence; mod theme; pub const WINDOW_WIDTH: f32 = 1300.; pub const WINDOW_HEIGHT: f32 = 1_000.; pub const WINDOW_TITLE: &str = "PlasCAD"; pub const ROW_SPACING: f32 = 22.; pub const COL_SPACING: f32 = 30.; // Note: This is basically working, but doesn't seem to reflect this scaling factor accurately. pub const SPLIT_SCREEN_MAX_HEIGHT: f32 = 3.5; pub const PRIMER_FWD_COLOR: Color32 = Color32::from_rgb(255, 0, 255); pub const PRIMER_REV_COLOR: Color32 = Color32::LIGHT_YELLOW; pub const BACKGROUND_COLOR: Color32 = Color32::from_rgb(10, 20, 10); pub const COLOR_SEQ: Color32 = Color32::LIGHT_BLUE; // (0xAD, 0xD8, 0xE6) pub const COLOR_SEQ_DIMMED: Color32 = Color32::from_rgb(140, 160, 165); // Eg dim when there are search results pub const COLOR_RE: Color32 = Color32::LIGHT_RED; pub const COLOR_RE_HIGHLIGHTED: Color32 = Color32::YELLOW; // If using a dedicated canvas for a linear map. pub const LINEAR_MAP_HEIGHT: f32 = 60.; pub fn int_field(val: &mut usize, label: &str, ui: &mut Ui) { ui.label(label); let mut entry = val.to_string(); if ui .add(TextEdit::singleline(&mut entry).desired_width(40.)) .changed() { *val = entry.parse().unwrap_or(0); } } /// Get a text-representation of the cursor index (Mouse or text); a slightly processed version of the raw index. /// We use this on the sequence and circle views. pub fn get_cursor_text(cursor_seq_i: Option<usize>, seq_len: usize) -> String { match cursor_seq_i { Some(p) => { if p <= seq_len { p.to_string() // This occurs if the cursor is on the last row, right of the last NT. } else { String::new() } } None => String::new(), } } /// Handle an origin change. fn origin_change(state: &mut State, ui: &mut Ui) { if ui.button("Set origin").clicked() { state.ui.show_origin_change = !state.ui.show_origin_change; } if state.ui.show_origin_change { ui.horizontal(|ui| { ui.label("New origin:"); let mut entry = state.ui.new_origin.to_string(); if ui .add(TextEdit::singleline(&mut entry).desired_width(40.)) .changed() { state.ui.new_origin = entry.parse().unwrap_or(0); } if ui .button(RichText::new("Set").color(COLOR_ACTION)) .clicked() { util::change_origin(state); } // ui.add( // // egui::Slider::from_get_set(0.0..=state.get_seq().len() as f32, |v| { // egui::Slider::new(&mut 0, 0..=state.get_seq().len(), |v| { // if let Some(v_) = v { // // bases_modified.push(basis_i); // } // // v // .text("Wt"), // ); }); } } /// Find the index of the smallest feature that contains an index. Index is in our 1-based system. fn feature_from_index(index: &Option<usize>, features: &[Feature]) -> Option<usize> { if let Some(seq_i) = index { // If multiple features are in the cursor's region, choose the smallest. let mut matched = false; let mut smallest_feature = 0; let mut smallest_feature_size = 99999; for (i, feature) in features.iter().enumerate() { if feature.feature_type == FeatureType::Source { continue; // From GenBank; generally the whole seq. } if *seq_i > feature.range.start && *seq_i < feature.range.end { matched = true; let feature_size = feature.range.end - feature.range.start - 1; if feature_size < smallest_feature_size { smallest_feature = i; smallest_feature_size = feature_size; } } } if matched { return Some(smallest_feature); } } None } /// todo: DRY with `feature_from_index`. Combine. fn primer_from_index(index: &Option<usize>, primers: &[Primer]) -> Option<usize> { if let Some(seq_i) = index { // If multiple features are in the cursor's region, choose the smallest. let mut matched = false; let mut smallest_feature = 0; let mut smallest_feature_size = 99999; for (i, primer) in primers.iter().enumerate() { for p_match in &primer.volatile.matches { if *seq_i > p_match.range.start && *seq_i < p_match.range.end { matched = true; let feature_size = p_match.range.end - p_match.range.start - 1; if feature_size < smallest_feature_size { smallest_feature = i; smallest_feature_size = feature_size; } } } } if matched { return Some(smallest_feature); } } None } /// Selects a primer or feature, if there is a click in the appropriate canvas; used in both the sequence, /// and map views. Currently, if there is a primer and fetaure overlayed, it selects the primer. (This isn't ideal, /// but acceptable for now.) pub fn select_feature(state: &mut State, from_screen: &RectTransform) { let click_handle = match &mut state.ui.page { Page::Sequence => &mut state.ui.dblclick_pending_handle, Page::Map => &mut state.ui.click_pending_handle, _ => &mut false, }; if *click_handle { // Don't let clicks out of this canvas remove the selected item. if let Some(pos) = state.ui.cursor_pos { let pos_rel = from_screen * pos2(pos.0, pos.1); if pos_rel.x > 0. && pos_rel.y > 0. { let feature_i = feature_from_index( &state.ui.cursor_seq_i, &state.generic[state.active].features, ); let primer_i = primer_from_index(&state.ui.cursor_seq_i, &state.generic[state.active].primers); let mut toggled_off = false; if let Selection::Feature(j) = state.ui.selected_item { if primer_i.is_none() { // If primer_i is some, we select it vice selecting None. if j == feature_i.unwrap_or(999) { state.ui.selected_item = Selection::None; toggled_off = true; } } } // todo: DRY if let Selection::Primer(j) = state.ui.selected_item { if j == primer_i.unwrap_or(999) { state.ui.selected_item = Selection::None; toggled_off = true; } } if !toggled_off { state.ui.selected_item = if let Some(v) = primer_i { Selection::Primer(v) } else { match feature_i { Some(i) => Selection::Feature(i), None => Selection::None, } } } } } *click_handle = false; } } /// Update the tilebar to reflect the current path loaded or saved. pub fn set_window_title(tab: &Tab, ui: &mut Ui) { let title = match &tab.path { Some(path) => get_window_title(&path), None => WINDOW_TITLE.to_owned(), }; ui.ctx().send_viewport_cmd(ViewportCommand::Title(title)); } pub fn draw(state: &mut State, ctx: &Context) { ctx.options_mut(|o| o.theme_preference = ThemePreference::Dark); egui::CentralPanel::default().show(ctx, |ui| { handle_input(state, ui); // todo: This section DRY with seq viewx. let mut visuals = ctx.style().visuals.clone(); // visuals.override_text_color = Some(Color32::from_rgb(255, 0, 0)); visuals.override_text_color = Some(Color32::LIGHT_GRAY); ctx.set_visuals(visuals); navigation::tab_selector(state, ui); ui.add_space(ROW_SPACING / 2.); let ab1_mode = state.tabs_open[state.active].ab1; if ab1_mode { // Ensure that if an AB1 file is selected, we show the AB1 page and no tabs. // Otherwise, ensure we do not show the AB1 page. state.ui.page = Page::Ab1; } else { if state.ui.page == Page::Ab1 { state.ui.page = Page::Map; } ui.horizontal(|ui| { navigation::page_selector(state, ui); ui.add_space(COL_SPACING / 2.); ui.label("Name:"); ui.add( TextEdit::singleline(&mut state.generic[state.active].metadata.plasmid_name) .desired_width(260.), ); ui.label(format!("{} bp", state.get_seq().len())); }); } ui.add_space(ROW_SPACING / 2.); ui.horizontal(|ui| { save::save_section(state, ui); ui.add_space(COL_SPACING); origin_change(state, ui); if ui.button("Annotate").clicked() { // Don't add duplicates. let features = find_features(&state.get_seq()); merge_feature_sets(&mut state.generic[state.active].features, &features) } // todo: Kludge. if ui.button("Sync RE sites").clicked() { state.sync_re_sites(); } ui.add_space(COL_SPACING); ui.label("Edit lock:"); let (lock_text, lock_color) = if state.ui.seq_edit_lock { ("🔒", Color32::LIGHT_BLUE) } else { ("🔓", Color32::from_rgb(255, 210, 140)) }; // todo: IDeally bigger font size, but without making the whole line take up more vertical space. if ui .button(RichText::new(lock_text).color(lock_color)) .on_hover_text("Prevent edits to the sequence") .clicked() { state.ui.seq_edit_lock = !state.ui.seq_edit_lock; } // todo: YOu will need a better organization method. if state.ui.text_selection.is_some() || state.ui.selected_item != Selection::None { let text = if state.ui.text_selection.is_some() { "BLAST selection" } else { match state.ui.selected_item { Selection::Feature(_) => "BLAST feature", Selection::Primer(_) => "BLAST primer", Selection::None => unreachable!(), } }; if ui.button(RichText::new(text).color(COLOR_ACTION)).clicked() { external_websites::blast(state); } } ui.add_space(COL_SPACING); let mut selection_avail = false; if state.ui.text_selection.is_some() { selection_avail = true; } match state.ui.selected_item { Selection::None => (), _ => { selection_avail = true; } } if selection_avail { ui.add_space(COL_SPACING); if ui .button("🗐") .on_hover_text("Copy the selected selection, feature or primer. (Ctrl + C)") .clicked() { state.copy_seq() } } }); ui.add_space(ROW_SPACING / 2.); // ScrollArea::vertical().show(ui, |ui| match state.ui.page { match state.ui.page { Page::Sequence => sequence::seq_page(state, ui), Page::Map => circle::circle_page(state, ui), Page::Features => feature_table::features_page(state, ui), Page::Primers => primer_details(state, ui), Page::Pcr => pcr::pcr_page(state, ui), Page::Alignment => alignment::alignment_page(state, ui), Page::Cloning => cloning::cloning_page(state, ui), Page::Proteins => protein::protein_page(state, ui), Page::Ligation => ligation::ligation_page(state, ui), Page::Metadata => { metadata::metadata_page(&mut state.generic[state.active].metadata, ui) } Page::Portions => portions::portions_page(&mut state.portions[state.active], ui), Page::Ab1 => ab1::ab1_page(state, ui), } }); } pub fn select_color_text(text: &str, selected: bool) -> RichText { let color = if selected { Color32::GREEN } else { Color32::WHITE }; RichText::new(text).color(color) }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/pcr.rs
src/gui/pcr.rs
use std::str::FromStr; use eframe::egui::{Color32, ComboBox, Grid, RichText, TextEdit, Ui, Vec2}; use crate::{ gui::{ COL_SPACING, ROW_SPACING, lin_maps, theme::{COLOR_ACTION, COLOR_INFO}, }, pcr::{PcrUi, PolymeraseType, TempTime, make_amplicon_tab}, primer::{Primer, PrimerDirection, TM_TARGET}, state::State, util::RangeIncl, }; fn temp_time_disp(tt: &TempTime, label: &str, ui: &mut Ui) { ui.label(&format!("{label}:")); ui.label(RichText::new(format!("{:.0}°C", tt.temp)).color(COLOR_INFO)); ui.label(RichText::new(format!("{}s", tt.time)).color(COLOR_INFO)); ui.end_row(); } fn numerical_field<T>(label: &str, val: &mut T, default: T, ui: &mut Ui) -> bool where T: ToString + FromStr + Copy, <T as FromStr>::Err: std::fmt::Debug, { let mut changed = false; ui.label(&format!("{}: ", label)); let mut entry = val.to_string(); if ui .add(TextEdit::singleline(&mut entry).desired_width(30.)) .changed() { *val = entry.parse().unwrap_or(default); changed = true; } changed } fn primer_dropdown( val: &mut usize, primers: &[Primer], direction: Option<PrimerDirection>, id: usize, ui: &mut Ui, ) { // Reset primer selected if an invalid one is set. if *val > primers.len() { *val = 0; } let primer = &primers[*val]; ComboBox::from_id_salt(id) .width(80.) .selected_text(&primer.name) .show_ui(ui, |ui| { for (i, primer) in primers.iter().enumerate() { if let Some(dir) = direction { let mut dir_match = false; for match_ in &primer.volatile.matches { if match_.direction == dir { dir_match = true; } } if !dir_match { continue; } } ui.selectable_value(val, i, &primer.name); } }); } fn pcr_sim(state: &mut State, ui: &mut Ui) { let num_primers = state.generic[state.active].primers.len(); if state.ui.pcr.primer_fwd >= num_primers || state.ui.pcr.primer_rev >= num_primers { state.ui.pcr.primer_fwd = 0; state.ui.pcr.primer_rev = 0; } ui.heading("PCR product generation"); lin_maps::seq_lin_disp( &state.generic[state.active], false, state.ui.selected_item, &Vec::new(), None, &state.ui, &state.volatile[state.active].restriction_enzyme_matches, &state.restriction_enzyme_lib, ui, ); ui.add_space(ROW_SPACING / 2.); if num_primers >= 2 { ui.horizontal(|ui| { ui.label("Fwd:"); primer_dropdown( &mut state.ui.pcr.primer_fwd, &state.generic[state.active].primers, Some(PrimerDirection::Forward), 2, ui, ); ui.add_space(COL_SPACING); ui.label("Rev:"); primer_dropdown( &mut state.ui.pcr.primer_rev, &state.generic[state.active].primers, Some(PrimerDirection::Reverse), 3, ui, ); ui.add_space(COL_SPACING); // let fwd_primer = &state.generic[state.active].primers[state.ui.pcr.primer_fwd]; // let rev_primer = &state.generic[state.active].primers[state.ui.pcr.primer_rev]; // todo: Yikes on this syntax. if state.ui.pcr.primer_fwd == state.ui.pcr.primer_rev { ui.label("Select two different primers"); } else if state.generic[state.active].primers[state.ui.pcr.primer_fwd] .volatile .matches .len() == 1 && state.generic[state.active].primers[state.ui.pcr.primer_rev] .volatile .matches .len() == 1 { if ui .button(RichText::new("Simulate PCR").color(COLOR_ACTION)) .clicked() { let fwd_primer = state.generic[state.active].primers[state.ui.pcr.primer_fwd].clone(); let rev_primer = state.generic[state.active].primers[state.ui.pcr.primer_rev].clone(); // todo: Yikes. let range_fwd = fwd_primer.volatile.matches[0].range; let range_rev = rev_primer.volatile.matches[0].range; let range_combined = RangeIncl::new(range_fwd.start, range_rev.end); let product_seq = if range_combined.start > range_combined.end { range_combined .index_seq_wrap(&state.generic[state.active].seq) .unwrap() // todo unwrap is dicey. } else { range_combined .index_seq(&state.generic[state.active].seq) .unwrap() .to_vec() // todo unwrap is dicey. }; make_amplicon_tab(state, product_seq, range_combined, fwd_primer, rev_primer); } } else { ui.label("There must be exactly one match for each primer"); } }); } else { ui.label("(Add at least 2 primers to generate a PCR product)"); } } pub fn pcr_page(state: &mut State, ui: &mut Ui) { pcr_sim(state, ui); ui.add_space(ROW_SPACING * 2.); ui.horizontal(|ui| { ui.heading("PCR parameters"); if !state.generic[state.active].primers.is_empty() { ui.add_space(COL_SPACING); if ui.button("Load from primer: ").clicked() { let primer = &state.generic[state.active].primers[state.ui.pcr.primer_selected]; // todo: Overflow check? if let Some(metrics) = &primer.volatile.metrics { state.ui.pcr = PcrUi { primer_tm: metrics.melting_temp, product_len: state.get_seq().len(), primer_selected: state.ui.pcr.primer_selected, ..Default::default() }; } state.sync_pcr(); } primer_dropdown( &mut state.ui.pcr.primer_selected, &state.generic[state.active].primers, None, 1, ui, ); } }); // pub primer_tm: f32, // pub product_len: usize, // pub polymerase_type: PolymeraseType, // pub num_cycles: u16, ui.horizontal(|ui| { // todo: Allow TM decimals? // Not using our helper here due to int coercing. ui.label("Primer TM"); let mut entry = format!("{:.0}", state.ui.pcr.primer_tm); let response = ui.add(TextEdit::singleline(&mut entry).desired_width(20.)); if response.changed() { state.ui.pcr.primer_tm = entry.parse().unwrap_or(TM_TARGET); state.sync_pcr(); } // if numerical_field("Primer TM", &mut state.ui.pcr.primer_tm, TM_TARGET, ui) || if numerical_field( "Product size (bp)", &mut state.ui.pcr.product_len, 1_000, ui, ) || numerical_field("# cycles", &mut state.ui.pcr.num_cycles, 30, ui) { state.sync_pcr(); } ui.label("Polymerase:"); let prev_poly = state.ui.pcr.polymerase_type; ComboBox::from_id_salt(10) .width(80.) .selected_text(state.ui.pcr.polymerase_type.to_str()) .show_ui(ui, |ui| { ui.selectable_value( &mut state.ui.pcr.polymerase_type, PolymeraseType::NormalFidelity, PolymeraseType::NormalFidelity.to_str(), ); ui.selectable_value( &mut state.ui.pcr.polymerase_type, PolymeraseType::HighFidelity, PolymeraseType::HighFidelity.to_str(), ); }); if state.ui.pcr.polymerase_type != prev_poly { state.sync_pcr(); } }); ui.add_space(ROW_SPACING); Grid::new(0).spacing(Vec2::new(60., 0.)).show(ui, |ui| { temp_time_disp(&state.pcr.initial_denaturation, "Initial denaturation", ui); temp_time_disp(&state.pcr.denaturation, "Denaturation", ui); temp_time_disp(&state.pcr.annealing, "Annealing", ui); temp_time_disp(&state.pcr.extension, "Extension", ui); temp_time_disp(&state.pcr.final_extension, "Final extension", ui); ui.label("Number of cycles:".to_string()); ui.label(format!("{}", state.pcr.num_cycles)); ui.end_row(); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/save.rs
src/gui/save.rs
//! GUI code for saving and loading. Calls business logic in `file_io/save.rs`. use std::{env, path::Path}; use eframe::egui::Ui; use egui_file_dialog::FileDialog; use crate::{ file_io::{ genbank::export_genbank, save, save::{StateToSave, export_fasta, load_import}, snapgene::export_snapgene, }, gui::{navigation::Tab, set_window_title}, state::State, }; fn save_button( dialog: &mut FileDialog, plasmid_name: &str, extension: &str, text: &str, hover_text: &str, ui: &mut Ui, ) { if ui.button(text).on_hover_text(hover_text).clicked() { let filename = { let name = if plasmid_name.is_empty() { "a_plasmid".to_string() } else { plasmid_name.to_lowercase().replace(' ', "_") }; format!("{name}.{extension}") }; // save_path.push(Path::new(&filename)); dialog.config_mut().default_file_name = filename.to_string(); dialog.save_file(); } } fn load_button(dialog: &mut FileDialog, text: &str, hover_text: &str, ui: &mut Ui) { if ui.button(text).on_hover_text(hover_text).clicked() { dialog.pick_file(); } } /// Ui elements for saving and loading data in various file formats. This includes our own format, /// FASTA, and (eventually) SnapGene's DNA format. pub fn save_section(state: &mut State, ui: &mut Ui) { let button_text = if state.tabs_open[state.active].path.is_some() { "Save" } else { "Quicksave" }; if ui .button(button_text) .on_hover_text("Save data. (Ctrl + S)") .clicked() { save::save_current_file(state); } save_button( &mut state.ui.file_dialogs.save, &state.generic[state.active].metadata.plasmid_name, "pcad", "Save as", "Save data in the PlasCAD format. (Ctrl + Shift + S)", ui, ); load_button( &mut state.ui.file_dialogs.load, "Load/Import", "Load data in the PlasCAD, FASTA, GenBank, or .dna (SnapGene) formats (Ctrl + O)", ui, ); save_button( &mut state.ui.file_dialogs.export_fasta, &state.generic[state.active].metadata.plasmid_name, "fasta", "Exp FASTA", "Export the sequence in the FASTA format. This does not include features or primers.", ui, ); save_button( &mut state.ui.file_dialogs.export_genbank, &state.generic[state.active].metadata.plasmid_name, "gbk", "Exp GenBank", "Export data in the GenBank format.", ui, ); save_button( &mut state.ui.file_dialogs.export_dna, &state.generic[state.active].metadata.plasmid_name, "dna", "Exp SnapGene", "Export data in the .dna (SnapGene) format", ui, ); // todo: DRY. let ctx = ui.ctx(); state.ui.file_dialogs.save.update(ctx); state.ui.file_dialogs.load.update(ctx); state.ui.file_dialogs.export_fasta.update(ctx); state.ui.file_dialogs.export_genbank.update(ctx); state.ui.file_dialogs.export_dna.update(ctx); let mut sync = false; if let Some(path) = state.ui.file_dialogs.load.take_picked() { sync = true; if let Some(loaded) = load_import(&path) { state.load(&loaded); } } else if let Some(path) = state.ui.file_dialogs.save.take_picked() { match StateToSave::from_state(state, state.active).save_to_file(&path) { Ok(_) => { state.tabs_open[state.active] = Tab { path: Some(path.to_owned()), ab1: false, }; set_window_title(&state.tabs_open[state.active], ui); state.update_save_prefs(); // Save opened tabs. } Err(e) => eprintln!("Error saving in PlasCAD format: {:?}", e), }; } else if let Some(path) = state.ui.file_dialogs.export_fasta.take_picked() { match export_fasta( state.get_seq(), &state.generic[state.active].metadata.plasmid_name, &path, ) { Ok(_) => { state.tabs_open[state.active] = Tab { path: Some(path.to_owned()), ab1: false, }; set_window_title(&state.tabs_open[state.active], ui); state.update_save_prefs(); // Save opened tabs. } Err(e) => eprintln!("Error exporting to FASTA: {:?}", e), } } else if let Some(path) = state.ui.file_dialogs.export_genbank.take_picked() { let mut primer_matches = Vec::new(); for primer in &state.generic[state.active].primers { for prim_match in &primer.volatile.matches { primer_matches.push((prim_match.clone(), primer.name.clone())); } } match export_genbank(&state.generic[state.active], &primer_matches, &path) { Ok(_) => { state.tabs_open[state.active] = Tab { path: Some(path.to_owned()), ab1: false, }; set_window_title(&state.tabs_open[state.active], ui); state.update_save_prefs(); // Save opened tabs. } Err(e) => eprintln!("Error exporting to GenBank: {:?}", e), } } else if let Some(path) = state.ui.file_dialogs.export_dna.take_picked() { match export_snapgene(&state.generic[state.active], &path) { Ok(_) => { state.tabs_open[state.active] = Tab { path: Some(path.to_owned()), ab1: false, }; set_window_title(&state.tabs_open[state.active], ui); state.update_save_prefs(); // Save opened tabs. } Err(e) => eprintln!("Error exporting to SnapGene: {:?}", e), }; } if sync { state.sync_pcr(); state.sync_primer_metrics(); state.sync_seq_related(None); state.sync_portions(); state.reset_selections(); set_window_title(&state.tabs_open[state.active], ui); } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/portions.rs
src/gui/portions.rs
//! UI page for mixing portions. (growth media, stock solutions etc) use eframe::{ egui, egui::{Color32, ComboBox, RichText, TextEdit, Ui}, }; use crate::{ gui::{ COL_SPACING, ROW_SPACING, theme::{COLOR_ACTION, COLOR_INFO}, }, portions::{ MediaPrepInput, PlateSize, PortionsState, Reagent, ReagentPrep, ReagentType, Solution, media_prep, }, }; // todo: Make a non-gui portions module once this becomes unweildy. // todo: Store solutions. Save to file, and mix solutions from other solutions. const DEFAULT_REAGENT_MOLARITY: f32 = 1.; const DEFAULT_TOTAL_VOLUME: f32 = 1.; // L fn solutions_disp(portions: &mut PortionsState, ui: &mut Ui) { let mut sol_removed = None; for (i, solution) in portions.solutions.iter_mut().enumerate() { ui.horizontal(|ui| { // ui.heading(RichText::new(&solution.name).color(Color32::LIGHT_BLUE)); ui.add(TextEdit::singleline(&mut solution.name).desired_width(200.)); ui.label("Total volume (mL):"); // todo: Float field, or can we do ml? let mut val_ml = ((solution.total_volume * 1_000.) as u32).to_string(); let response = ui.add(TextEdit::singleline(&mut val_ml).desired_width(40.)); if response.changed() { let val_int: u32 = val_ml.parse().unwrap_or_default(); solution.total_volume = val_int as f32 / 1_000.; solution.calc_amounts(); } if ui .button(RichText::new("➕ Add reagent").color(COLOR_ACTION)) .clicked() { solution.reagents.push(Reagent::default()); } if ui .button(RichText::new("Delete solution 🗑").color(Color32::RED)) .clicked() { sol_removed = Some(i); } }); ui.add_space(ROW_SPACING / 2.); let mut reagent_removed = None; for (j, reagent) in solution.reagents.iter_mut().enumerate() { ui.horizontal(|ui| { let type_prev = reagent.type_; ComboBox::from_id_salt(100 + i * 100 + j) .width(140.) .selected_text(reagent.type_.to_string()) .show_ui(ui, |ui| { for type_ in [ ReagentType::Custom(0.), ReagentType::SodiumChloride, ReagentType::TrisHcl, ReagentType::Iptg, ReagentType::SodiumPhosphateMonobasic, ReagentType::SodiumPhosphateDibasic, ReagentType::SodiumPhosphateDibasicHeptahydrate, ReagentType::PotassiumPhosphateMonobasic, ReagentType::PotassiumPhosphateDibasic, ReagentType::Imidazole, ReagentType::Lysozyme, ReagentType::Mes, ReagentType::Bes, ReagentType::Tes, ReagentType::CitricAcid, ReagentType::Edta, ReagentType::HydrochloricAcid, ReagentType::SodiumHydroxide, ReagentType::BromophenolBlue, ReagentType::Dtt, ReagentType::MagnesiumChloride, ReagentType::Sds, ReagentType::Glycine, ReagentType::Tris, ] { ui.selectable_value(&mut reagent.type_, type_, type_.to_string()); } // ui.selectable_value(val, Reagent::Custom(_), Reagent::Custom(_).to_string()); }); if let ReagentType::Custom(weight) = &mut reagent.type_ { let mut val = format!("{:.2}", weight); if ui .add(TextEdit::singleline(&mut val).desired_width(40.)) .changed() { // let molarity_int: u32 = val.parse().unwrap_or_default(); *weight = val.parse().unwrap_or_default(); // *v = molarity_int as f32 / 1_000.; reagent.calc_amount(solution.total_volume); } ui.label("g/mol"); } else { ui.add_sized( [80.0, 20.0], egui::Label::new(format!("{:.2} g/mol", reagent.type_.weight())), ); } let prep_prev = reagent.prep; ComboBox::from_id_salt(2000 + i * 100 + j) .width(80.) .selected_text(reagent.prep.to_string()) .show_ui(ui, |ui| { for prep in [ ReagentPrep::Mass, ReagentPrep::Volume(DEFAULT_REAGENT_MOLARITY), ] { ui.selectable_value(&mut reagent.prep, prep, prep.to_string()); } }); // todo: This effect on water volume added? if let ReagentPrep::Volume(v) = &mut reagent.prep { ui.label("reagant Molarity (mM):"); let mut val = ((*v * 1_000.) as u32).to_string(); if ui .add(TextEdit::singleline(&mut val).desired_width(40.)) .changed() { let molarity_int: u32 = val.parse().unwrap_or_default(); *v = molarity_int as f32 / 1_000.; reagent.calc_amount(solution.total_volume); } } if type_prev != reagent.type_ || prep_prev != reagent.prep { reagent.calc_amount(solution.total_volume); } ui.add_space(COL_SPACING / 2.); ui.label("Molarity (mM):"); // Convert to a mM integer. let mut val = ((reagent.molarity * 1_000.) as u32).to_string(); if ui .add(TextEdit::singleline(&mut val).desired_width(40.)) .changed() { let molarity_int: u32 = val.parse().unwrap_or_default(); reagent.molarity = molarity_int as f32 / 1_000.; reagent.calc_amount(solution.total_volume); } ui.add_space(COL_SPACING / 2.); let result_label = if let ReagentPrep::Volume(_) = reagent.prep { "Volume" } else { "Mass" }; ui.label(result_label); ui.add_sized( [80.0, 20.0], egui::Label::new( RichText::new(reagent.amount_calc.to_string()).color(COLOR_INFO), ), ); ui.add_space(COL_SPACING); if ui.button(RichText::new("🗑").color(Color32::RED)).clicked() { reagent_removed = Some(j); } }); } if let Some(rem_i) = reagent_removed { solution.reagents.remove(rem_i); } ui.add_space(ROW_SPACING * 2.); } if let Some(rem_i) = sol_removed { portions.solutions.remove(rem_i); } } fn media_disp(portions: &mut PortionsState, ui: &mut Ui) { let type_prev = portions.media_input.clone(); let mut run_calc = false; ui.horizontal(|ui| { ComboBox::from_id_salt(3_000) .width(110.) .selected_text(portions.media_input.to_string()) .show_ui(ui, |ui| { for type_ in [ MediaPrepInput::Plates((PlateSize::D90, 6)), MediaPrepInput::Liquid(0.), ] { ui.selectable_value( &mut portions.media_input, type_.clone(), type_.to_string(), ); } }); ui.add_space(COL_SPACING); if portions.media_input != type_prev { run_calc = true; } match &mut portions.media_input { MediaPrepInput::Plates((plate_size, num)) => { ui.label("Plate diameter:"); let dia_prev = *plate_size; ComboBox::from_id_salt(3_001) .width(70.) .selected_text(plate_size.to_string()) .show_ui(ui, |ui| { for size in [ PlateSize::D60, PlateSize::D90, PlateSize::D100, PlateSize::D150, ] { ui.selectable_value(plate_size, size, size.to_string()); } }); if *plate_size != dia_prev { run_calc = true; } ui.label("Num plates:"); let mut val = num.to_string(); if ui .add(TextEdit::singleline(&mut val).desired_width(40.)) .changed() { *num = val.parse().unwrap_or_default(); run_calc = true; } } MediaPrepInput::Liquid(volume) => { ui.label("Volume (mL):"); let mut val_ml = (*volume * 1_000.).to_string(); if ui .add(TextEdit::singleline(&mut val_ml).desired_width(50.)) .changed() { let val_int: u32 = val_ml.parse().unwrap_or_default(); *volume = val_int as f32 / 1_000.; run_calc = true; } } } }); ui.add_space(ROW_SPACING); // todo: Adjust units etc A/R for higherh values. let result = &portions.media_result; ui.horizontal(|ui| { ui.label("Water: "); ui.label(format!("{:.1} mL", result.water * 1_000.)); ui.add_space(COL_SPACING); ui.label("LB: "); ui.label(format!("{:.2} g", result.food)); ui.add_space(COL_SPACING); if result.agar > 0. { ui.label("Agar: "); ui.label(format!("{:.2} g", result.agar)); ui.add_space(COL_SPACING); } ui.label("Antibiotic (1000×): "); ui.label(format!("{:.1} μL", result.antibiotic * 1_000.)); }); if run_calc { portions.media_result = media_prep(&portions.media_input); } } pub fn portions_page(portions: &mut PortionsState, ui: &mut Ui) { ui.add_space(ROW_SPACING / 2.); ui.horizontal(|ui| { ui.heading("Mixing portions"); ui.add_space(COL_SPACING); if ui .button(RichText::new("➕ Add solution").color(COLOR_ACTION)) .clicked() { portions.solutions.push(Solution { total_volume: DEFAULT_TOTAL_VOLUME, reagents: vec![Reagent::default()], ..Default::default() }); } }); ui.add_space(ROW_SPACING); solutions_disp(portions, ui); ui.add_space(ROW_SPACING); ui.heading("Growth media"); media_disp(portions, ui); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/feature_table.rs
src/gui/feature_table.rs
//! GUI code for the features editor and related. use eframe::egui::{ Color32, ComboBox, CursorIcon, Frame, RichText, ScrollArea, Stroke, TextEdit, Ui, }; use crate::{ Color, Selection, gui::{COL_SPACING, ROW_SPACING, int_field, theme::COLOR_ACTION}, misc_types::{ Feature, FeatureDirection::{self, Forward, Reverse}, FeatureType, }, state::State, util::RangeIncl, }; const LABEL_EDIT_WIDTH: f32 = 140.; /// A color selector for use with feature addition and editing. fn color_picker(val: &mut Option<Color>, feature_color: Color, ui: &mut Ui) { let mut color_override = val.is_some(); if ui.checkbox(&mut color_override, "").changed() { if color_override { // Default to the feature color when checking. *val = Some(feature_color); } else { *val = None; return; } } // Only show the color picker if choosing to override. if val.is_none() { return; } let (r, g, b) = val.unwrap(); let mut color = Color32::from_rgb(r, g, b); if ui.color_edit_button_srgba(&mut color).changed() { *val = Some((color.r(), color.g(), color.b())); } } /// A selector for use with feature addition and editing. /// todo: Generic selector creator? pub fn direction_picker(val: &mut FeatureDirection, id: usize, ui: &mut Ui) { ComboBox::from_id_salt(id) .width(74.) .selected_text(val.to_string()) .show_ui(ui, |ui| { for dir in [FeatureDirection::None, Forward, Reverse] { ui.selectable_value(val, dir, dir.to_string()); } }); } /// A selector for use with feature addition and editing. /// todo: Generic selector creator? fn feature_type_picker(val: &mut FeatureType, id: usize, ui: &mut Ui) { ComboBox::from_id_salt(id) .width(140.) .selected_text(val.to_string()) .show_ui(ui, |ui| { for feature_type in [ FeatureType::Generic, FeatureType::CodingRegion, FeatureType::Ori, // FeatureType::RnaPolyBindSite, FeatureType::RibosomeBindSite, FeatureType::AntibioticResistance, FeatureType::LongTerminalRepeat, FeatureType::Exon, FeatureType::Transcript, // todo: Source? ] { ui.selectable_value(val, feature_type, feature_type.to_string()); } }); } pub fn feature_table(state: &mut State, ui: &mut Ui) { feature_add_disp(state, ui); ui.add_space(ROW_SPACING); let mut removed = None; for (i, feature) in state.generic[state.active].features.iter_mut().enumerate() { let mut border_width = 0.; if let Selection::Feature(j) = state.ui.selected_item { if i == j { border_width = 1.; } } Frame::none() .stroke(Stroke::new(border_width, Color32::LIGHT_RED)) .inner_margin(border_width) .show(ui, |ui| { if ui .heading(RichText::new(&feature.label).color(COLOR_ACTION)) .on_hover_cursor(CursorIcon::PointingHand) .clicked() { state.ui.selected_item = Selection::Feature(i); } ui.horizontal(|ui| { int_field(&mut feature.range.start, "Start:", ui); int_field(&mut feature.range.end, "End:", ui); ui.label("Label:"); ui.add( TextEdit::singleline(&mut feature.label).desired_width(LABEL_EDIT_WIDTH), ); ui.label("Type:"); feature_type_picker(&mut feature.feature_type, 100 + i, ui); ui.label("Dir:"); direction_picker(&mut feature.direction, 300 + i, ui); ui.label("Custom color:"); color_picker( &mut feature.color_override, feature.feature_type.color(), ui, ); if ui.button("Add note").clicked() { feature.notes.push((String::new(), String::new())); } // todo: This section repetative with primers. let mut selected = false; if let Selection::Feature(sel_i) = state.ui.selected_item { if sel_i == i { selected = true; } } if selected { if ui .button(RichText::new("🔘").color(Color32::GREEN)) .clicked() { state.ui.selected_item = Selection::None; } } else if ui.button("🔘").clicked() { state.ui.selected_item = Selection::Feature(i); } ui.add_space(COL_SPACING); // Less likely to accidentally delete. if ui .button(RichText::new("Delete 🗑").color(Color32::RED)) .clicked() { removed = Some(i); } }); for (key, value) in &mut feature.notes { ui.horizontal(|ui| { ui.label("Note:"); ui.add(TextEdit::singleline(key).desired_width(140.)); ui.label("Value:"); ui.add(TextEdit::singleline(value).desired_width(600.)); }); } }); ui.add_space(ROW_SPACING); } if let Some(rem_i) = removed { state.generic[state.active].features.remove(rem_i); } } pub fn feature_add_disp(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { if ui.button("➕ Add feature").clicked() { if state.ui.feature_add.start_posit == 0 { state.ui.feature_add.start_posit = 1; } if state.ui.feature_add.end_posit == 0 { state.ui.feature_add.end_posit = 1; } if state.ui.feature_add.start_posit > state.ui.feature_add.end_posit { std::mem::swap( &mut state.ui.feature_add.start_posit, &mut state.ui.feature_add.end_posit, ); } state.generic[state.active].features.push(Feature { range: RangeIncl::new( state.ui.feature_add.start_posit, state.ui.feature_add.end_posit, ), feature_type: FeatureType::Generic, direction: FeatureDirection::None, label: state.ui.feature_add.label.clone(), color_override: None, notes: Default::default(), }); } }); } pub fn features_page(state: &mut State, ui: &mut Ui) { ScrollArea::vertical().show(ui, |ui| { feature_table(state, ui); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/metadata.rs
src/gui/metadata.rs
//! Contains references, comments, etc about the plasmid. use chrono::NaiveDate; use eframe::egui::{Color32, RichText, ScrollArea, TextEdit, Ui}; use crate::{ gui::{COL_SPACING, ROW_SPACING}, misc_types::Metadata, }; const WIDTH_RATIO: f32 = 0.6; const ROW_HEIGHT: usize = 1; const HEADING_COLOR: Color32 = Color32::from_rgb(40, 180, 255); /// A convenience function to create a text edit for Option<String> fn option_edit( val: &mut Option<String>, label: &str, multi: bool, width_: Option<f32>, ui: &mut Ui, ) { ui.horizontal(|ui| { // ui.allocate_exact_size(Vec2::new(LABEL_WIDTH, 0.0), egui::Sense::hover()); // Reserve space ui.label(label); let width = match width_ { Some(w) => w, None => ui.available_width() * WIDTH_RATIO, }; // todo: Way without cloning? let mut v = val.clone().unwrap_or_default(); // Don't use these margins if there is a narrow window. let response = if multi { ui.add( TextEdit::multiline(&mut v) .desired_width(width) .desired_rows(ROW_HEIGHT), ) } else { ui.add(TextEdit::singleline(&mut v).desired_width(width)) }; if response.changed() { *val = if !v.is_empty() { Some(v.to_owned()) } else { None }; } }); ui.add_space(ROW_SPACING / 2.); } pub fn metadata_page(data: &mut Metadata, ui: &mut Ui) { // todo: YOu need neat grid alignment. How can we make the labels take up constant space? // todo: Examine which fields should be single vs multiline, and the order. ScrollArea::vertical().show(ui, |ui| { ui.heading(RichText::new("General:").color(HEADING_COLOR)); ui.add_space(ROW_SPACING / 2.); ui.horizontal(|ui| { ui.label("Plasmid name:"); ui.text_edit_singleline(&mut data.plasmid_name); }); ui.add_space(ROW_SPACING); option_edit(&mut data.definition, "Definition:", false, None, ui); ui.horizontal(|ui| { ui.label("Division:"); ui.add(TextEdit::singleline(&mut data.division).desired_width(60.)); ui.add_space(COL_SPACING); option_edit( &mut data.molecule_type, "Molecule type:", false, Some(80.), ui, ); if let Some(date) = data.date { ui.add_space(COL_SPACING); // todo: Allow the date to be editable, and not just when present. let date = NaiveDate::from_ymd(date.0, date.1.into(), date.2.into()); ui.label(format!("Date: {}", date)); } }); ui.add_space(ROW_SPACING / 2.); option_edit(&mut data.accession, "Accession:", true, None, ui); option_edit(&mut data.version, "Version:", true, None, ui); option_edit(&mut data.keywords, "Keywords:", true, None, ui); option_edit(&mut data.source, "Source:", true, None, ui); option_edit(&mut data.organism, "Organism:", true, None, ui); ui.add_space(ROW_SPACING); // pub locus: String, // pub definition: Option<String>, // pub accession: Option<String>, // pub version: Option<String>, // // pub keywords: Vec<String>, // pub keywords: Option<String>, // todo vec? // pub source: Option<String>, // pub organism: Option<String>, ui.heading(RichText::new("References:").color(HEADING_COLOR)); ui.add_space(ROW_SPACING / 2.); for ref_ in &mut data.references { ui.horizontal(|ui| { ui.label("Title:"); ui.add( TextEdit::multiline(&mut ref_.title) .desired_width(ui.available_width() * WIDTH_RATIO) .desired_rows(ROW_HEIGHT), ); }); ui.add_space(ROW_SPACING / 2.); ui.horizontal(|ui| { ui.label("Description:"); ui.add( TextEdit::multiline(&mut ref_.description) .desired_width(ui.available_width() * WIDTH_RATIO) .desired_rows(ROW_HEIGHT), ); }); ui.add_space(ROW_SPACING / 2.); option_edit(&mut ref_.authors, "Authors:", true, None, ui); option_edit(&mut ref_.consortium, "Consortium:", true, None, ui); option_edit(&mut ref_.journal, "Journal:", true, None, ui); option_edit(&mut ref_.pubmed, "Pubmed:", true, None, ui); option_edit(&mut ref_.remark, "Remarks:", true, None, ui); ui.add_space(ROW_SPACING); } // egui::Shape::hline(2, 2., Stroke::new(2., Color32::WHITE)); ui.heading(RichText::new("Comments:").color(HEADING_COLOR)); ui.add_space(ROW_SPACING); if ui.button("➕ Add").clicked() { data.comments.push(String::new()); } for comment in &mut data.comments { let response = ui.add( TextEdit::multiline(comment) .desired_width(ui.available_width() * WIDTH_RATIO) .desired_rows(ROW_HEIGHT), ); // if response.changed() { // } ui.add_space(ROW_SPACING / 2.); } }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/cloning.rs
src/gui/cloning.rs
use core::fmt; use std::borrow::Cow; use eframe::egui::{ Color32, ComboBox, Frame, Grid, RichText, ScrollArea, Stroke, TextEdit, Ui, Vec2, }; use na_seq::{Nucleotide, insert_into_seq, seq_from_str, seq_to_str_lower}; use strum::IntoEnumIterator; use crate::{ backbones::{Backbone, BackboneFilters, CloningTechnique}, cloning::{ BackboneSelected, CloneStatus, CloningInsertData, RE_INSERT_BUFFER, Status, make_product_tab, setup_insert_seqs, }, file_io::{GenericData, save::load_import}, gui::{ COL_SPACING, ROW_SPACING, find_features, lin_maps::seq_lin_disp, navigation::get_tab_names, select_color_text, theme::{COLOR_ACTION, COLOR_INFO}, }, misc_types::{Feature, FeatureType}, state::State, util::{RangeIncl, merge_feature_sets}, }; const PASS_COLOR: Color32 = Color32::LIGHT_GREEN; const FAIL_COLOR: Color32 = Color32::LIGHT_RED; const NA_COLOR: Color32 = Color32::GOLD; fn filter_selector<T: fmt::Display + PartialEq + Copy + IntoEnumIterator>( name: &str, val: &mut Option<T>, id: u32, ui: &mut Ui, ) { ui.label(name); let text = match val { Some(v) => v.to_string(), None => "Any".to_string(), }; ComboBox::from_id_salt(id) .width(80.) .selected_text(text) .show_ui(ui, |ui| { ui.selectable_value(val, None, "Any"); for variant in T::iter() { ui.selectable_value(val, Some(variant), variant.to_string()); } }); ui.add_space(COL_SPACING); } /// Descriptive text about a feature; ie for insert selection. Used to display the one selected, and in the selector. fn draw_insert_descrip(feature: &Feature, seq_loaded: &[Nucleotide], ui: &mut Ui) { if !feature.label.is_empty() { ui.label(&feature.label); ui.add_space(COL_SPACING); } let (r, g, b) = feature.feature_type.color(); ui.label(RichText::new(feature.feature_type.to_string()).color(Color32::from_rgb(r, g, b))); ui.add_space(COL_SPACING); ui.label(feature.location_descrip(seq_loaded.len())); ui.add_space(COL_SPACING); // +1 because it's inclusive. ui.label(feature.location_descrip(seq_loaded.len())); } /// Draw a selector for the insert, based on loading from a file. /// This buffer is in nucleotides, and is on either side of the insert. A buffer of 4-6 nts is ideal /// for restriction-enzyme cloning, while no buffer is required for PCR-based cloning. fn insert_selector(data: &mut CloningInsertData, buffer: usize, ui: &mut Ui) -> bool { let mut clicked = false; for (i, feature) in data.features_loaded.iter().enumerate() { // match feature.feature_type { // FeatureType::CodingRegion | FeatureType::Generic | FeatureType::Gene => (), // _ => continue, // } let mut selected = false; if let Some(j) = data.feature_selected { if i == j { selected = true; } } let (border_width, btn_color) = if selected { (1., Color32::GREEN) } else { (0., Color32::WHITE) }; Frame::none() .stroke(Stroke::new(border_width, Color32::LIGHT_RED)) .inner_margin(border_width) .show(ui, |ui| { ui.horizontal(|ui| { if ui .button(RichText::new("Select").color(btn_color)) .clicked() { data.feature_selected = Some(i); // todo: Handle wraps with this for circular plasmids instead of truncating. let start = if buffer + 1 < feature.range.start { feature.range.start - buffer } else { 1 }; let end_ = feature.range.end + buffer; let end = if end_ + 1 < data.seq_loaded.len() { end_ } else { data.seq_loaded.len() }; let buffered_range = RangeIncl::new(start, end); if let Some(seq_this_ft) = buffered_range.index_seq(&data.seq_loaded) { seq_this_ft.clone_into(&mut data.seq_insert); } clicked = true; } draw_insert_descrip(feature, &data.seq_loaded, ui); }); }); } clicked } /// Choose from tabs to select an insert from. fn insert_tab_selection(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { ui.label("Choose insert from:"); let plasmid_names: &Vec<_> = &state .generic .iter() .map(|v| v.metadata.plasmid_name.as_str()) .collect(); // Add buttons for each opened tab for (name, i) in get_tab_names(&state.tabs_open, plasmid_names, true) { if ui .button(name) .on_hover_text("Select an insert from this sequence") .clicked() { let gen_ = &state.generic[i]; // This setup, including the break and variables, prevents borrow errors. let g = gen_.features.clone(); let s = gen_.seq.clone(); setup_insert_seqs(state, g, s); state.ui.cloning_insert.show_insert_picker = true; break; } } ui.add_space(COL_SPACING); if ui .button("Pick insert from file") .on_hover_text( "Choose a GenBank, PlasCAD, SnapGene, or FASTA file to \ select an insert from. FASTA files require manual index selection.", ) .clicked() { state.ui.file_dialogs.cloning_load.pick_file(); state.ui.cloning_insert.show_insert_picker = true; } ui.add_space(COL_SPACING); state.ui.file_dialogs.cloning_load.update(ui.ctx()); if let Some(path) = state.ui.file_dialogs.cloning_load.take_picked() { if let Some(state_loaded) = load_import(&path) { // todo: Is there a way to do this without cloning? setup_insert_seqs( state, state_loaded.generic.features.clone(), state_loaded.generic.seq.clone(), ); } } if !state.ui.cloning_insert.features_loaded.is_empty() { let hide_text = if state.ui.cloning_insert.show_insert_picker { "Hide inserts" } else { "Show inserts" }; ui.add_space(COL_SPACING); if ui.button(hide_text).clicked() { state.ui.cloning_insert.show_insert_picker = !state.ui.cloning_insert.show_insert_picker } } }); // ui.add_space(ROW_SPACING); ui.horizontal(|ui| { // A short summary of the selected feature; useful if the picker is hidden. for (i, feature) in state.ui.cloning_insert.features_loaded.iter().enumerate() { let mut border_width = 0.; if let Some(j) = state.ui.cloning_insert.feature_selected { if i == j { ui.label(RichText::new("Insert selected:").color(COLOR_INFO)); draw_insert_descrip(feature, &state.ui.cloning_insert.seq_loaded, ui); } } } }); } fn text_from_status(status: Status) -> RichText { match status { Status::Pass => RichText::new("Pass").color(PASS_COLOR), Status::Fail => RichText::new("Fail").color(FAIL_COLOR), Status::NotApplicable => RichText::new("N/A").color(NA_COLOR), } } fn checklist(status: &CloneStatus, rbs_dist: Option<isize>, ui: &mut Ui) { ui.heading("Product checklist:"); ui.horizontal(|ui| { // ui.label("Reading frame:").on_hover_text("The coding region is in-frame with respect to (todo: RBS? Promoter?)"); // ui.label(RichText::new("Fail").color(FAIL_COLOR)); ui.label("Distance from RBS:").on_hover_text("Insert point is a suitabel distance (eg 5-10 nucleotides) downstream of the Ribosome Bind Site."); ui.label(text_from_status(status.rbs_dist)); if let Some(rd) = rbs_dist { ui.label(format!("({rd}nt)")); } ui.add_space(COL_SPACING); ui.label("Downstream of promoter:").on_hover_text("Is downstream of the appropriate expression promoter."); ui.label(text_from_status(status.downstream_of_promoter)); ui.add_space(COL_SPACING); ui.label("Upstream of terminator:").on_hover_text("Is upstream of the appropriate expression terminator."); ui.label(text_from_status(status.upstream_of_terminator)); ui.add_space(COL_SPACING); ui.label("Direction:"); ui.label(text_from_status(status.direction)); ui.add_space(COL_SPACING); ui.label("In frame with His tag:"); ui.label(text_from_status(status.tag_frame)); ui.add_space(COL_SPACING); // ui.label("Primer quality:"); // ui.label(RichText::new("Fail").color(FAIL_COLOR)); // ui.add_space(COL_SPACING); // // ui.label("RE distance:"); // ui.label(RichText::new("Fail").color(FAIL_COLOR)); // ui.add_space(COL_SPACING); }); } fn backbone_filters(filters: &mut BackboneFilters, ui: &mut Ui) { // todo: Allow selecting multiple options. // todo: HElper fn for these ui.horizontal(|ui| { filter_selector("Host", &mut filters.host, 0, ui); filter_selector("Ab resistance", &mut filters.antibiotic_resistance, 1, ui); filter_selector("Expression", &mut filters.expression_system, 2, ui); filter_selector("Copy", &mut filters.copy_number, 3, ui); ui.label("His tagged:"); ui.checkbox(&mut filters.his_tagged, ""); ui.add_space(COL_SPACING); }); } /// A UI element that allows the user to choose which backbone to clone into. fn backbone_selector( backbone_selected: &mut BackboneSelected, backbones: &[&Backbone], plasmid_name: &str, data: &GenericData, bb_cache: &mut Option<Backbone>, ui: &mut Ui, ) -> bool { let mut changed = false; ui.horizontal(|ui| { if ui .button(select_color_text( &format!("This plasmid ({})", plasmid_name), *backbone_selected == BackboneSelected::Opened, )) .clicked() { // Cache this, since we don't have it in the library to reference. *bb_cache = Some(Backbone::from_opened(data)); *backbone_selected = BackboneSelected::Opened; changed = true; } ui.add_space(COL_SPACING); if backbones.is_empty() { eprintln!("Error: Empty backbone library"); return; } if ui .button(select_color_text( "Library:", *backbone_selected != BackboneSelected::Opened, )) .clicked() { *backbone_selected = BackboneSelected::Library(0); changed = true } ui.add_space(COL_SPACING); let bb_selected = match backbone_selected { BackboneSelected::Opened => backbones[0], BackboneSelected::Library(i) => backbones[*i], }; let bb_prev = &backbone_selected.clone(); // todo: Don't like this clone. ComboBox::from_id_salt(1000) .width(80.) .selected_text(&bb_selected.name) .show_ui(ui, |ui| { for (i, backbone) in backbones.iter().enumerate() { ui.selectable_value( backbone_selected, BackboneSelected::Library(i), &backbone.name, ); } }); if *backbone_selected != *bb_prev { changed = true; } ui.add_space(COL_SPACING); if let Some(addgene_url) = bb_selected.addgene_url() { if ui.button("View on AddGene").clicked() { if let Err(e) = webbrowser::open(&addgene_url) { eprintln!("Failed to open the web browser: {:?}", e); } } } }); ui.add_space(ROW_SPACING); changed } pub fn cloning_page(state: &mut State, ui: &mut Ui) { ScrollArea::vertical().id_salt(100).show(ui, |ui| { let mut sync = false; ui.heading("Cloning (Currently supports PCR-based cloning only"); // ui.label("For a given insert, automatically select a backbone, and either restriction enzymes, or PCR primers to use\ // to clone the insert into the backbone."); ui.add_space(ROW_SPACING); ui.horizontal(|ui| { ui.label( "Remove stop coding prior to tags. (Useful if there is a tag on the backbone)", ) .on_hover_text( "If there is a stop coding at the end of the insert, and a His or similar tag, \ remove the codon, so the tag is coded for", ); if ui .checkbox(&mut state.cloning.remove_stop_codons, "") .changed() { sync = true; } }); ui.add_space(ROW_SPACING); // todo: DRY with below getting the backbone, but we have a borrow error when moving that up. let data_vec = match state.cloning.backbone_selected { BackboneSelected::Library(i) => { if i >= state.backbone_lib.len() { eprintln!("Invalid index in backbone lib"); None } else { Some(&state.backbone_lib[i].data) } } BackboneSelected::Opened => Some(&state.generic[state.active]), }; // Draw the linear map regardless of if there's a vector (Empty map otherwise). This prevents // a layout shift when selecting. let data_vec_ = if let Some(data_) = data_vec { data_ } else { &Default::default() }; // A minimap for the vector. seq_lin_disp( data_vec_, true, state.ui.selected_item, &state.ui.re.res_selected, Some(state.cloning.insert_loc), &state.ui, &state.cloning.re_matches_vec_common, &state.restriction_enzyme_lib, ui, ); ui.add_space(ROW_SPACING); // A minimap for the insert if let Some(data) = &state.cloning.data_insert { seq_lin_disp( data, true, state.ui.selected_item, &state.ui.re.res_selected, None, &state.ui, &state.cloning.re_matches_insert_common, &state.restriction_enzyme_lib, ui, ); } ui.add_space(ROW_SPACING); insert_tab_selection(state, ui); ui.add_space(ROW_SPACING); if state.ui.cloning_insert.show_insert_picker { let insert_just_picked = insert_selector(&mut state.ui.cloning_insert, RE_INSERT_BUFFER, ui); if insert_just_picked { sync = true; } ui.add_space(ROW_SPACING); } ui.heading("Backbones (vectors)"); backbone_filters(&mut state.ui.backbone_filters, ui); ui.add_space(ROW_SPACING); // todo: Cache this? let backbones_filtered = state.ui.backbone_filters.apply(&state.backbone_lib); let plasmid_name = &state.generic[state.active].metadata.plasmid_name; let backbone_just_picked = backbone_selector( &mut state.cloning.backbone_selected, &backbones_filtered, plasmid_name, &state.generic[state.active], &mut state.cloning.backbone, ui, ); if backbone_just_picked { sync = true; } // todo: This is DRY with get_backbone due to borrow error. // let backbone = state.cloning.get_backbone(&state.backbone_lib); let backbone = match state.cloning.backbone_selected { BackboneSelected::Library(i) => { if i >= state.backbone_lib.len() { eprintln!("Invalid index in backbone lib"); None } else { Some(&state.backbone_lib[i]) } } BackboneSelected::Opened => match state.cloning.backbone.as_ref() { Some(bb) => Some(bb), None => None, }, }; // These variables prevent borrow errors on backbone. let mut clone_initiated = false; if let Some(backbone) = backbone { let rbs_dist = backbone .rbs .map(|r| state.cloning.insert_loc as isize - r.end as isize); ui.add_space(ROW_SPACING); ui.label("Restriction enzymes:"); if state.cloning.res_common.is_empty() { ui.label("(None)"); } for candidate in &state.cloning.res_common { ui.label(&candidate.name); } ui.add_space(ROW_SPACING); if ui .button( RichText::new("Auto set insert location (PCR; expression)").color(COLOR_ACTION), ) .clicked() { if let Some(insert_loc) = backbone.insert_loc(CloningTechnique::Pcr) { state.cloning.insert_loc = insert_loc; } sync = true; } ui.horizontal(|ui| { ui.label("Insert location:"); ui.label(RichText::new(format!("{}", state.cloning.insert_loc)).color(COLOR_INFO)); }); ui.add_space(ROW_SPACING); // todo: Only if there is a result if true { ui.add_space(ROW_SPACING); checklist(&state.cloning.status, rbs_dist, ui); ui.add_space(ROW_SPACING); if ui .button(RichText::new("Clone (PCR)").color(COLOR_ACTION)) .clicked() { clone_initiated = true; } } ui.add_space(ROW_SPACING); ui.horizontal(|ui| { ui.label("Insert location: "); let mut entry = state.cloning.insert_loc.to_string(); if ui .add(TextEdit::singleline(&mut entry).desired_width(40.)) .changed() { state.cloning.insert_loc = entry.parse().unwrap_or(0); sync = true; } ui.add_space(COL_SPACING); }); if clone_initiated { make_product_tab(state, Some(backbone.data.clone())); // Annotate the vector, for now at least. let features = find_features(&state.get_seq()); // We assume the product has been made active. merge_feature_sets(&mut state.generic[state.active].features, &features) } } let resp_insert_editor = ui.add( TextEdit::multiline(&mut state.ui.cloning_insert.seq_input) .desired_width(ui.available_width()), ); if resp_insert_editor.changed() { // Forces only valid NTs to be included in the string. state.ui.cloning_insert.seq_insert = seq_from_str(&state.ui.cloning_insert.seq_input); state.ui.cloning_insert.seq_input = seq_to_str_lower(&state.ui.cloning_insert.seq_insert); sync = true; } if sync { state.cloning.sync( &mut state.ui.cloning_insert.seq_insert, &state.backbone_lib, &state.restriction_enzyme_lib, ); } }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/ab1.rs
src/gui/ab1.rs
//! Contains code for viewing AB1 sequencing data, e.g. from Sanger sequencing. use bio_files::SeqRecordAb1; use copypasta::{ClipboardContext, ClipboardProvider}; use eframe::{ egui::{ Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, RichText, Sense, Shape, Slider, Stroke, Ui, pos2, vec2, }, emath::RectTransform, epaint::PathShape, }; use na_seq::{Nucleotide, seq_to_str_lower}; use crate::{ feature_db_load::find_features, file_io::GenericData, gui::{BACKGROUND_COLOR, COL_SPACING, ROW_SPACING}, misc_types::Metadata, state::State, util::merge_feature_sets, }; const NT_COLOR: Color32 = Color32::from_rgb(180, 220, 220); const NT_WIDTH: f32 = 8.; // pixels const STROKE_WIDTH_PEAK: f32 = 1.; const PEAK_WIDTH_DIV2: f32 = 2.; // Peak heights are normallized, so that the maximum value is this. const PEAK_MAX_HEIGHT: f32 = 120.; const COLOR_A: Color32 = Color32::from_rgb(20, 220, 20); const COLOR_C: Color32 = Color32::from_rgb(130, 130, 255); const COLOR_T: Color32 = Color32::from_rgb(255, 100, 100); const COLOR_G: Color32 = Color32::from_rgb(200, 200, 200); /// This mapping is based off conventions in other software. fn nt_color_map(nt: Nucleotide) -> Color32 { match nt { Nucleotide::A => COLOR_A, Nucleotide::C => COLOR_C, Nucleotide::T => COLOR_T, Nucleotide::G => COLOR_G, } } /// Map sequence index to a horizontal pixel. fn index_to_posit(i: usize, num_nts: usize, ui: &Ui) -> f32 { // todo: Cap if width too small for nt len. Varying zoom, etc. // let width = ui.available_width(); // // let num_nts_disp = width / NT_WIDTH; // let scale_factor = width / num_nts as f32; i as f32 * NT_WIDTH } /// Plot the peaks and confidence values; draw letters fn plot(data: &SeqRecordAb1, to_screen: &RectTransform, start_i: usize, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); let nt_y = 160.; let plot_y = nt_y - 20.; // todo: Don't run this calc every time. let data_scaler = { let mut max_peak = 0; for i in 0..data.data_ch1.len() { if i > 40 { // todo: Sloppy performance saver. continue; } let ch1 = data.data_ch1[i]; let ch2 = data.data_ch2[i]; let ch3 = data.data_ch3[i]; let ch4 = data.data_ch4[i]; for ch in [ch1, ch2, ch3, ch4] { if ch > max_peak { max_peak = ch; } } } PEAK_MAX_HEIGHT / max_peak as f32 }; let width = ui.available_width(); let num_nts_disp = width / NT_WIDTH; // Display nucleotides and quality values. for i_pos in 0..num_nts_disp as usize { let i = start_i + i_pos; if data.sequence.is_empty() || i > data.sequence.len() - 1 { break; } let nt = data.sequence[i]; let x_pos = index_to_posit(i_pos, data.sequence.len(), ui); if x_pos > ui.available_width() - 15. { continue; // todo: QC the details, if you need to_screen here etc. } let nt_color = nt_color_map(nt); result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, to_screen * pos2(x_pos, nt_y), Align2::CENTER_CENTER, &nt.to_str_lower(), FontId::new(12., FontFamily::Monospace), nt_color, ) })); // todo: Display quality values below. // let quality = data.quality[i]; // todo: Index check. } // Display data. for i_pos in 0..num_nts_disp as usize * 4 { let i = start_i * 4 + i_pos; if data.data_ch1.is_empty() || i > data.data_ch1.len() - 1 { break; } let x_pos = index_to_posit(i_pos, data.sequence.len(), ui) / 4.; if x_pos > ui.available_width() - 15. { continue; // todo: QC the details, if you need to_screen here etc. } let ch1 = data.data_ch1[i]; let ch2 = data.data_ch2[i]; let ch3 = data.data_ch3[i]; let ch4 = data.data_ch4[i]; // todo: Index error handling. for (ch, color) in [ (ch1, COLOR_G), (ch2, COLOR_A), (ch3, COLOR_T), (ch4, COLOR_C), ] { let stroke = Stroke::new(STROKE_WIDTH_PEAK, color); // todo: Autoscale height let base_pos = pos2(x_pos, plot_y); // todo: These may get too thin. let top_left = base_pos + vec2(-PEAK_WIDTH_DIV2, ch as f32 * -data_scaler); let top_right = base_pos + vec2(PEAK_WIDTH_DIV2, ch as f32 * -data_scaler); let bottom_left = base_pos + vec2(-PEAK_WIDTH_DIV2, 0.); let bottom_right = base_pos + vec2(PEAK_WIDTH_DIV2, 0.); result.push(ui.ctx().fonts(|fonts| { // Shape::Path(PathShape::convex_polygon( Shape::Path(PathShape::closed_line( vec![ to_screen * top_left, to_screen * bottom_left, to_screen * bottom_right, to_screen * top_right, ], // color, stroke, )) })); } } result } pub fn ab1_page(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { let data = &state.ab1_data[state.active]; ui.heading("AB1 sequencing view"); ui.add_space(COL_SPACING * 2.); if ui.button(RichText::new("🗐 Copy sequence")).on_hover_text("Copy this sequence to the clipboard.").clicked() { let mut ctx = ClipboardContext::new().unwrap(); ctx.set_contents(seq_to_str_lower(&data.sequence)).unwrap(); } ui.add_space(COL_SPACING); if ui .button("➕ Create data (e.g. Genbank, PCAD etc) as a new tab.") .on_hover_text("Create a new non-AB1 data set\ that may include features, primers, etc. May be edited, and saved to Genbank, PCAD, or SnapGene formats.") .clicked() { // Note: This segment is almost a duplicate of `State::add_tab` and the similar section in `cloning`. let plasmid_name = match &state.tabs_open[state.active].path { Some(p) => p.file_name().unwrap().to_str().unwrap_or_default(), None => "Plasmid from AB1", // This shouldn't happen, I believe. }.to_owned().replace(".ab1", ""); let generic = GenericData { seq: data.sequence.clone(), metadata: Metadata { plasmid_name, ..Default::default() }, ..Default::default() }; state.generic.push(generic); state.portions.push(Default::default()); state.volatile.push(Default::default()); state.tabs_open.push(Default::default()); state.ab1_data.push(Default::default()); state.active = state.generic.len() - 1; // state.sync_seq_related(None); // Annotate. Don't add duplicates. let features = find_features(&state.get_seq()); merge_feature_sets(&mut state.generic[state.active].features, &features) } }); ui.add_space(ROW_SPACING / 2.); let data = &state.ab1_data[state.active]; let width = ui.available_width(); let num_nts_disp = width / NT_WIDTH; ui.spacing_mut().slider_width = width - 60.; let slider_max = { let v = data.sequence.len() as isize - num_nts_disp as isize + 1; if v > 0 { v as usize } else { 0 } }; ui.add(Slider::new(&mut state.ui.ab1_start_i, 0..=slider_max)); ui.add_space(ROW_SPACING / 2.); let mut shapes = Vec::new(); Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let data = &state.ab1_data[state.active]; let (response, _painter) = { let desired_size = vec2(ui.available_width(), ui.available_height()); ui.allocate_painter(desired_size, Sense::click()) }; let to_screen = RectTransform::from_to( // Rect::from_min_size(pos2(0., -VERITICAL_CIRCLE_OFFSET), response.rect.size()), Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); let rect_size = response.rect.size(); shapes.append(&mut plot(data, &to_screen, state.ui.ab1_start_i, ui)); ui.painter().extend(shapes); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/input.rs
src/gui/input.rs
//! Code related to mouse and keyboard input handling. use std::{mem, path::PathBuf}; use eframe::egui::{Event, InputState, Key, PointerButton, Ui}; use na_seq::{Nucleotide, seq_from_str}; use crate::{ StateUi, file_io::{ save, save::{QUICKSAVE_FILE, StateToSave, load_import}, }, gui::{ navigation::{Page, Tab}, set_window_title, }, state::State, util::RangeIncl, }; /// Handle hotkeys and clicks that affect all pages. fn handle_global(state: &mut State, ip: &InputState) { if ip.key_pressed(Key::A) && ip.modifiers.ctrl && !state.ui.text_edit_active { if !state.get_seq().is_empty() { state.ui.text_selection = Some(RangeIncl::new(1, state.get_seq().len())) } } if ip.key_pressed(Key::S) && ip.modifiers.ctrl && !ip.modifiers.shift { save::save_current_file(state); } if ip.key_pressed(Key::N) && ip.modifiers.ctrl { state.add_tab(); state.tabs_open.push(Tab { path: None, ab1: false, }); } if ip.key_pressed(Key::F) && ip.modifiers.ctrl { state.ui.highlight_search_input = true; // Disable the cursor, so we don't insert nucleotides while searching! state.ui.text_cursor_i = None; } if ip.key_pressed(Key::S) && ip.modifiers.ctrl && ip.modifiers.shift { state.ui.file_dialogs.save.pick_file(); } if ip.key_pressed(Key::O) && ip.modifiers.ctrl { state.ui.file_dialogs.load.pick_file(); } state.ui.cursor_pos = ip.pointer.hover_pos().map(|pos| (pos.x, pos.y)); if ip.pointer.button_clicked(PointerButton::Primary) { // todo: Not working for fixing our fast-sel off-by-one bug. // if let Some(i) = &state.ui.cursor_seq_i { // state.ui.text_selection = Some(*i..=*i); // 1-based indexing. Second value is a placeholder. // } state.ui.click_pending_handle = true; } if ip.pointer.button_double_clicked(PointerButton::Primary) { state.ui.dblclick_pending_handle = true; } } /// Handle sequence selection on the sequence page, as when dragging the mouse. fn handle_seq_selection(state_ui: &mut StateUi, dragging: bool) { if dragging { // A drag has started. if !state_ui.dragging { state_ui.dragging = true; // We are handling in the seq view after setting cursor seq i. Still glitchy. if let Some(i) = &state_ui.cursor_seq_i { state_ui.text_selection = Some(RangeIncl::new(*i, *i)); // The end value is a placeholder. } } else { // The drag is in progress; continually update the selection, for visual feedback. if let Some(i) = &state_ui.cursor_seq_i { if let Some(sel_range) = &mut state_ui.text_selection { sel_range.end = *i; } } } } else { // A drag has ended. if state_ui.dragging { state_ui.dragging = false; // This logic allows for reverse-order selecting, ie dragging the cursor from the end to // the start of the region. Handle in the UI how to display this correctly while the drag is in process, // since this only resolves once it's complete. if let Some(sel_range) = &mut state_ui.text_selection { if sel_range.start > sel_range.end { mem::swap(&mut sel_range.start, &mut sel_range.end); } } } } } /// Handles keyboard and mouse input not associated with a widget. /// todo: MOve to a separate module if this becomes complex. pub fn handle_input(state: &mut State, ui: &mut Ui) { let mut reset_window_title = false; // This setup avoids borrow errors. ui.ctx().input(|ip| { // Check for file drop if let Some(dropped_files) = ip.raw.dropped_files.first() { if let Some(path) = &dropped_files.path { if let Some(loaded) = load_import(path) { state.load(&loaded); reset_window_title = true; } } } handle_global(state, ip); if state.ui.text_edit_active && !reset_window_title { return; } // This event match is not specific to the seqe page for event in &ip.events { match event { Event::Cut => state.copy_seq(), Event::Copy => state.copy_seq(), Event::Paste(pasted_text) => {} _ => (), } } if let Page::Sequence = state.ui.page { // This is a bit awk; borrow errors. let mut move_cursor: Option<i32> = None; // todo: How can we control the rate? if state.ui.text_cursor_i.is_some() { if ip.key_pressed(Key::ArrowLeft) { move_cursor = Some(-1); } if ip.key_pressed(Key::ArrowRight) { move_cursor = Some(1); } if ip.key_pressed(Key::ArrowUp) { move_cursor = Some(-(state.ui.nt_chars_per_row as i32)); } if ip.key_pressed(Key::ArrowDown) { move_cursor = Some(state.ui.nt_chars_per_row as i32); } // Escape key: Remove the text cursor. if ip.key_pressed(Key::Escape) { move_cursor = None; state.ui.text_cursor_i = None; state.ui.text_selection = None; } } if ip.key_pressed(Key::Escape) { state.ui.text_selection = None; } // Insert nucleotides A/R. if let Some(mut i) = state.ui.text_cursor_i { if !state.ui.seq_edit_lock { if i > state.get_seq().len() { i = 0; // todo?? Having an overflow when backspacing near origin. } let i = i + 1; // Insert after this nucleotide; not before. // Don't allow accidental nt insertion when the user is entering into the search bar. // Add NTs. if ip.key_pressed(Key::A) && !ip.modifiers.ctrl { state.insert_nucleotides(&[Nucleotide::A], i); } if ip.key_pressed(Key::T) { state.insert_nucleotides(&[Nucleotide::T], i); } if ip.key_pressed(Key::C) && !ip.modifiers.ctrl { state.insert_nucleotides(&[Nucleotide::C], i); } if ip.key_pressed(Key::G) { state.insert_nucleotides(&[Nucleotide::G], i); } if ip.key_pressed(Key::Backspace) && i > 1 { state.remove_nucleotides(RangeIncl::new(i - 2, i - 2)); } if ip.key_pressed(Key::Delete) { state.remove_nucleotides(RangeIncl::new(i - 1, i - 1)); } // Paste nucleotides for event in &ip.events { match event { Event::Cut => { // state.remove_nucleotides(); // move_cursor = Some(pasted_text.len() as i32); } Event::Copy => {} Event::Paste(pasted_text) => { state.insert_nucleotides(&seq_from_str(pasted_text), i); move_cursor = Some(pasted_text.len() as i32); } _ => (), } } } } if !state.ui.seq_edit_lock { if ip.key_pressed(Key::A) && !ip.modifiers.ctrl { move_cursor = Some(1); } if ip.key_pressed(Key::T) { move_cursor = Some(1); } if ip.key_pressed(Key::C) && !ip.modifiers.ctrl { move_cursor = Some(1); } if ip.key_pressed(Key::G) { move_cursor = Some(1); } if ip.key_pressed(Key::Backspace) { move_cursor = Some(-1); } } if let Some(i) = &mut state.ui.text_cursor_i { if let Some(amt) = move_cursor { let val = *i as i32 + amt; // If val is 0, the cursor is before the first character; this is OK. // If it's < 0, we will get an overflow when converting to usize. if val >= 0 { let new_posit = val as usize; if new_posit <= state.generic[state.active].seq.len() { *i = new_posit; } } } } handle_seq_selection(&mut state.ui, ip.pointer.is_decidedly_dragging()); } }); if reset_window_title { set_window_title(&state.tabs_open[state.active], ui); } }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/sequence/primer_overlay.rs
src/gui/sequence/primer_overlay.rs
//! This module contains code related to drawing primer arrows in the sequence view. use eframe::egui::{Pos2, Shape, Ui}; use crate::{ Selection, gui::sequence::{feature_overlay, seq_view::SeqViewData}, misc_types::FeatureType, primer::{Primer, PrimerDirection}, util, util::RangeIncl, }; pub const STROKE_WIDTH: f32 = 2.; pub const VERTICAL_OFFSET_PRIMER: f32 = 18.; // A fudge factor? pub const LABEL_OFFSET: f32 = 7.; pub const HEIGHT: f32 = 16.; pub const SLANT: f32 = 12.; // slant different, in pixels, for the arrow. pub const SLANT_DIV2: f32 = SLANT / 2.; /// Add primer arrows to the display. pub fn draw_primers( primers: &[Primer], selected_item: Selection, data: &SeqViewData, ui: &mut Ui, ) -> Vec<Shape> { let mut shapes = Vec::new(); for (i, primer) in primers.iter().enumerate() { let primer_matches = &primer.volatile.matches; // todo: Do not run these calcs each time. Cache. for prim_match in primer_matches { // We currently index primers relative to the end they started. // Note: Because if we're displaying above the seq and below, the base of the arrow must match, // hence the offset. let seq_range = match prim_match.direction { PrimerDirection::Forward => { // todo: Getting an underflow, but not sure why yet. let end = if prim_match.range.end > 0 { prim_match.range.end - 1 } else { prim_match.range.end }; RangeIncl::new(prim_match.range.start, end) } PrimerDirection::Reverse => { RangeIncl::new(prim_match.range.start + 1, prim_match.range.end) } }; let feature_ranges = util::get_feature_ranges(&seq_range, &data.row_ranges, data.seq_len); let feature_ranges_px: Vec<(Pos2, Pos2)> = feature_ranges .iter() .map(|r| (data.seq_i_to_px_rel(r.start), data.seq_i_to_px_rel(r.end))) .collect(); let color = prim_match.direction.color(); let selected = match selected_item { Selection::Primer(j) => i == j, _ => false, }; // todo: PUt back; temp check on compiling. shapes.append(&mut feature_overlay::feature_seq_overlay( &feature_ranges_px, FeatureType::Primer, color, VERTICAL_OFFSET_PRIMER, (prim_match.direction).into(), &primer.name, selected, ui, )); } } shapes }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/sequence/seq_view.rs
src/gui/sequence/seq_view.rs
//! This module contains GUI code related to the sequence visulization. use eframe::{ egui::{ Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, ScrollArea, Sense, Shape, Stroke, Ui, pos2, vec2, }, emath::RectTransform, epaint::PathStroke, }; use na_seq::amino_acids::{AminoAcid, CodingResult}; use crate::{ Nucleotide, Selection, StateUi, gui::{ BACKGROUND_COLOR, COL_SPACING, COLOR_RE, COLOR_SEQ, COLOR_SEQ_DIMMED, feature_from_index, get_cursor_text, navigation::page_button, select_feature, sequence::{ feature_overlay::{draw_features, draw_selection}, primer_overlay, }, }, reading_frame::ReadingFrame, state::State, util::{RangeIncl, get_row_ranges, pixel_to_seq_i, seq_i_to_pixel}, }; // Pub for use in `util` functions. pub const FONT_SIZE_SEQ: f32 = 14.; pub const COLOR_CODING_REGION: Color32 = Color32::from_rgb(255, 0, 170); pub const COLOR_STOP_CODON: Color32 = Color32::from_rgb(255, 170, 100); pub const COLOR_CURSOR: Color32 = Color32::from_rgb(255, 255, 0); pub const COLOR_SEARCH_RESULTS: Color32 = Color32::from_rgb(255, 255, 130); pub const COLOR_SELECTED_NTS: Color32 = Color32::from_rgb(255, 60, 255); pub const NT_WIDTH_PX: f32 = 8.; // todo: Automatic way? This is valid for monospace font, size 14. pub const VIEW_AREA_PAD_LEFT: f32 = 60.; // Bigger to accomodate the index display. pub const VIEW_AREA_PAD_RIGHT: f32 = 20.; // pub const SEQ_ROW_SPACING_PX: f32 = 34.; pub const SEQ_ROW_SPACING_PX: f32 = 40.; pub const TEXT_X_START: f32 = VIEW_AREA_PAD_LEFT; pub const TEXT_Y_START: f32 = TEXT_X_START; /// These aguments define the circle, and are used in many places in this module. pub struct SeqViewData { pub seq_len: usize, pub row_ranges: Vec<RangeIncl>, pub to_screen: RectTransform, pub from_screen: RectTransform, // /// This is `from_screen * center`. We store it here to cache. // pub center_rel: Pos2, } impl SeqViewData { pub fn seq_i_to_px_rel(&self, i: usize) -> Pos2 { self.to_screen * seq_i_to_pixel(i, &self.row_ranges) } } fn draw_re_sites(state: &State, data: &SeqViewData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); for (i_match, re_match) in state.volatile[state.active] .restriction_enzyme_matches .iter() .enumerate() { if re_match.lib_index >= state.restriction_enzyme_lib.len() { eprintln!("Invalid RE selected"); return result; } let re = &state.restriction_enzyme_lib[re_match.lib_index]; if (state.ui.re.unique_cutters_only && re_match.match_count > 1) || (state.ui.re.sticky_ends_only && re.makes_blunt_ends()) { continue; } let cut_i = re_match.seq_index + 1; // to display in the right place. let cut_pos = data.seq_i_to_px_rel(cut_i + re.cut_after as usize); let bottom = pos2(cut_pos.x, cut_pos.y + 20.); result.push(Shape::LineSegment { points: [cut_pos, bottom], stroke: Stroke::new(2., COLOR_RE), }); let label_text = &re.name; let mut label_pos = pos2(cut_pos.x + 2., cut_pos.y - 4.); // Move the label position left if there is a nearby RE site on the right. // todo: Not appearing to be working well. let mut neighbor_on_right = false; for (i_other, re_match_other) in state.volatile[state.active] .restriction_enzyme_matches .iter() .enumerate() { if i_other != i_match && re_match_other.seq_index > re_match.seq_index && re_match_other.seq_index - re_match.seq_index < 10 { neighbor_on_right = true; break; } } if neighbor_on_right { // label_pos.x -= 300.; } // Alternate above and below for legibility. // This requires the RE site list to be sorted by seq index, which it currently is. if i_match % 2 == 0 { label_pos.y += 30.; } // Add the label let label = ui.ctx().fonts(|fonts| { Shape::text( fonts, label_pos, Align2::LEFT_CENTER, label_text, FontId::new(16., FontFamily::Proportional), COLOR_RE, ) }); result.push(label) } result } /// Checkboxes to show or hide features. pub fn display_filters(state_ui: &mut StateUi, ui: &mut Ui) { ui.horizontal(|ui| { let name = if state_ui.re.unique_cutters_only { "Single cut sites" } else { "RE sites" } .to_owned(); ui.label(name); ui.checkbox(&mut state_ui.seq_visibility.show_res, ""); ui.add_space(COL_SPACING / 2.); ui.label("Features:"); ui.checkbox(&mut state_ui.seq_visibility.show_features, ""); ui.add_space(COL_SPACING / 2.); ui.label("Primers:"); ui.checkbox(&mut state_ui.seq_visibility.show_primers, ""); ui.add_space(COL_SPACING / 2.); ui.label("Reading frame:"); ui.checkbox(&mut state_ui.seq_visibility.show_reading_frame, ""); ui.add_space(COL_SPACING / 2.); }); } /// Draw each row's start sequence range to its left. fn draw_seq_indexes(data: &SeqViewData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); for range in &data.row_ranges { let mut pos = data.seq_i_to_px_rel(range.start); pos.x -= VIEW_AREA_PAD_LEFT; let text = range.start; result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, pos, Align2::LEFT_TOP, text, FontId::new(FONT_SIZE_SEQ, FontFamily::Proportional), Color32::WHITE, ) })); } result } fn orf_selector(state: &mut State, ui: &mut Ui) { ui.label("Reading frame:"); let orf = &mut state.reading_frame; let orig = *orf; page_button(orf, ReadingFrame::Fwd0, ui, false); page_button(orf, ReadingFrame::Fwd1, ui, false); page_button(orf, ReadingFrame::Fwd2, ui, false); page_button(orf, ReadingFrame::Rev0, ui, false); page_button(orf, ReadingFrame::Rev1, ui, false); page_button(orf, ReadingFrame::Rev2, ui, false); if *orf != orig { state.sync_reading_frame() } } /// Find the sequence index under the cursor, if it is over the sequence. fn find_cursor_i(cursor_pos: Option<(f32, f32)>, data: &SeqViewData) -> Option<usize> { match cursor_pos { Some(p) => { // We've had issues where cursor above the seq would be treated as first row. let p_rel = pos2(p.0, p.1); let p_abs = data.from_screen * p_rel; // println!("P rel: {:?}", p_rel); // println!("P abs: {:?}", p_abs); // todo: How can we accurately get this? let view_start_y = 200.; // See note on the pad below; this is for clicking before seq start. if p_abs.x > (VIEW_AREA_PAD_LEFT - 2. * NT_WIDTH_PX) && p_rel.y > view_start_y { let result = pixel_to_seq_i(p_abs, &data.row_ranges); if let Some(i) = result { if i > data.seq_len + 2 { // This pad allows setting the cursor a bit past the seq end. return None; } else if i > data.seq_len { return Some(data.seq_len); } } result } else { None } } None => None, } } /// Draw the DNA sequence nucleotide by nucleotide. This allows fine control over color, and other things. fn draw_nts(state: &State, data: &SeqViewData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); for (i, nt) in state.get_seq().iter().enumerate() { let i = i + 1; // 1-based indexing. let pos = data.seq_i_to_px_rel(i); let mut in_rf = false; if state.ui.seq_visibility.show_reading_frame { for orf_match in &state.volatile[state.active].reading_frame_matches { if orf_match.range.contains(i) { // todo: This only works for forward reading frames. let i_orf = i - 1; // Back to 0-based indexing for this. // todo: Cache this; don't run it every update. if (i_orf - orf_match.frame.offset()) % 3 == 0 { let mut codons: [Nucleotide; 3] = state.get_seq()[i_orf..i_orf + 3].try_into().unwrap(); if state.reading_frame.is_reverse() { codons = [ codons[2].complement(), codons[1].complement(), codons[0].complement(), ]; } match CodingResult::from_codons(codons) { CodingResult::AminoAcid(aa) => { result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, pos, Align2::LEFT_TOP, aa.to_str_offset(), // Note: Monospace is important for sequences. FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace), COLOR_CODING_REGION, ) })); } CodingResult::StopCodon => { result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, pos, Align2::LEFT_TOP, "STP", FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace), COLOR_STOP_CODON, ) })); } } } in_rf = true; } } if in_rf { continue; } } let letter_color = { let mut r = COLOR_SEQ; let mut highlighted = false; if state.ui.seq_visibility.show_reading_frame { for rf in &state.volatile[state.active].reading_frame_matches { if rf.range.contains(i) { r = COLOR_CODING_REGION; highlighted = true; } } } // If a feature is selected, highlight its text, so it's more visible against the potentially // bright fill. match state.ui.selected_item { Selection::Feature(i_ft) => { if i_ft + 1 < state.generic[state.active].features.len() { let range = &state.generic[state.active].features[i_ft].range; if range.contains(i) { r = COLOR_SELECTED_NTS; } } } Selection::Primer(i_ft) => { if i_ft + 1 < state.generic[state.active].primers.len() { for p_match in &state.generic[state.active].primers[i_ft].volatile.matches { let range = p_match.range; if range.contains(i) { r = COLOR_SELECTED_NTS; break; } } } } _ => (), } // todo: We have inconsistencies in how we index across the board. // todo: Try resolving using the inclusive range type, and standardizing to 1-based. // todo: Resolve this one field at a time, from a working state. if let Some(sel_range) = &state.ui.text_selection { // This reversal should only occur during reverse dragging; it should resolve when dragging is complete. let range = if sel_range.start > sel_range.end { RangeIncl::new(sel_range.end, sel_range.start) } else { *sel_range }; if range.contains(i) { r = COLOR_SELECTED_NTS; } } // This overrides reading frame matches and text selection. for search_result in &state.volatile[state.active].search_matches { // Origin wrap. if search_result.range.end < search_result.range.start { if RangeIncl::new(0, search_result.range.end).contains(i) || RangeIncl::new(search_result.range.start, data.seq_len).contains(i) { r = COLOR_SEARCH_RESULTS; highlighted = true; } } else { if search_result.range.contains(i) { r = COLOR_SEARCH_RESULTS; highlighted = true; } } } // Dim normal text if there are search results. if state.volatile[state.active].search_matches.len() > 0 && !highlighted { r = COLOR_SEQ_DIMMED; } r }; result.push(ui.ctx().fonts(|fonts| { Shape::text( fonts, pos, Align2::LEFT_TOP, &nt.to_str_lower(), // Note: Monospace is important for sequences. FontId::new(FONT_SIZE_SEQ, FontFamily::Monospace), letter_color, ) })); } result } fn draw_text_cursor(cursor_i: Option<usize>, data: &SeqViewData) -> Vec<Shape> { let mut result = Vec::new(); if let Some(i) = cursor_i { let mut top = data.seq_i_to_px_rel(i); // Draw the cursor after this NT, not before. top.x += NT_WIDTH_PX; top.y -= 3.; let bottom = pos2(top.x, top.y + 23.); result.push(Shape::line_segment( [top, bottom], Stroke::new(2., COLOR_CURSOR), )); } result } /// Draw the sequence with primers, insertion points, and other data visible, A/R pub fn sequence_vis(state: &mut State, ui: &mut Ui) { let mut shapes = vec![]; let seq_len = state.get_seq().len(); state.ui.nt_chars_per_row = ((ui.available_width() - (VIEW_AREA_PAD_LEFT + VIEW_AREA_PAD_RIGHT)) / NT_WIDTH_PX) as usize; let row_ranges = get_row_ranges(seq_len, state.ui.nt_chars_per_row); let mouse_posit_lbl = get_cursor_text(state.ui.cursor_seq_i, seq_len); let text_posit_lbl = get_cursor_text(state.ui.text_cursor_i, seq_len); ui.horizontal(|ui| { orf_selector(state, ui); ui.add_space(COL_SPACING); display_filters(&mut state.ui, ui); ui.add_space(COL_SPACING); ui.label("Cursor:"); ui.heading(text_posit_lbl); ui.label("Mouse:"); ui.heading(mouse_posit_lbl); ui.label("Selection:"); if let Some(selection) = state.ui.text_selection { ui.heading(format!("{selection}")); } }); ScrollArea::vertical().show(ui, |ui| { Frame::canvas(ui.style()) .fill(BACKGROUND_COLOR) .show(ui, |ui| { let (response, _painter) = { // Estimate required height, based on seq len. let total_seq_height = row_ranges.len() as f32 * SEQ_ROW_SPACING_PX + 60.; let height = total_seq_height; let desired_size = vec2(ui.available_width(), height); // ui.allocate_painter(desired_size, Sense::click()) ui.allocate_painter(desired_size, Sense::click_and_drag()) }; let to_screen = RectTransform::from_to( Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); let from_screen = to_screen.inverse(); let data = SeqViewData { seq_len, row_ranges, to_screen, from_screen, }; let prev_cursor_i = state.ui.cursor_seq_i; state.ui.cursor_seq_i = find_cursor_i(state.ui.cursor_pos, &data); if prev_cursor_i != state.ui.cursor_seq_i { state.ui.feature_hover = feature_from_index( &state.ui.cursor_seq_i, &state.generic[state.active].features, ); } // Removed: We select cursor position instead now. select_feature(state, &from_screen); // todo: Move this into a function A/R. if state.ui.click_pending_handle { // This is set up so that a click outside the text area won't reset the cursor. if state.ui.cursor_seq_i.is_some() { state.ui.text_cursor_i = state.ui.cursor_seq_i; state.ui.text_edit_active = false; } state.ui.click_pending_handle = false; } shapes.extend(draw_seq_indexes(&data, ui)); if state.ui.seq_visibility.show_primers { shapes.append(&mut primer_overlay::draw_primers( &state.generic[state.active].primers, state.ui.selected_item, &data, ui, )); } if state.ui.seq_visibility.show_features { shapes.append(&mut draw_features( &state.generic[state.active].features, state.ui.selected_item, &data, ui, )); } if state.ui.seq_visibility.show_res { shapes.append(&mut draw_re_sites(state, &data, ui)); } if let Some(selection) = &state.ui.text_selection { shapes.append(&mut draw_selection(*selection, &data, ui)); } // Draw nucleotides arfter the selection, so it shows through the fill. shapes.append(&mut draw_nts(state, &data, ui)); shapes.append(&mut draw_text_cursor(state.ui.text_cursor_i, &data)); ui.painter().extend(shapes); }); }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/sequence/mod.rs
src/gui/sequence/mod.rs
//! This module contains GUI code related to the sequence view. use eframe::egui::{Color32, Frame, RichText, ScrollArea, TextEdit, Ui, text::CursorRange}; use na_seq::{seq_complement, seq_from_str, seq_to_str_lower}; // todo: monospace font for all seqs. use crate::gui::{COL_SPACING, ROW_SPACING}; // todo: monospace font for all seqs. use crate::misc_types::{Feature, FeatureDirection, MIN_SEARCH_LEN}; // todo: monospace font for all seqs. use crate::state::State; use crate::{ Selection, gui::{ PRIMER_FWD_COLOR, SPLIT_SCREEN_MAX_HEIGHT, circle::feature_range_sliders, feature_table::{direction_picker, feature_table}, navigation::{PageSeq, PageSeqTop, page_seq_selector, page_seq_top_selector}, primer_table::primer_details, sequence::seq_view::sequence_vis, theme::COLOR_ACTION, }, primer::{Primer, PrimerData}, util::RangeIncl, }; mod feature_overlay; mod primer_overlay; pub mod seq_view; fn seq_editor_raw(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { ui.heading("Sequence:"); ui.label(&format!("len: {}", state.ui.seq_input.len())); }); ScrollArea::vertical().id_salt(200).show(ui, |ui| { let response = ui.add(TextEdit::multiline(&mut state.ui.seq_input).desired_width(800.)); if response.changed() { state.generic[state.active].seq = seq_from_str(&state.ui.seq_input); state.ui.seq_input = seq_to_str_lower(state.get_seq()); state.sync_seq_related(None); } }); } /// Displays text of the feature under the cursor, or selected, as required. fn feature_text(i: usize, features: &[Feature], seq_len: usize, ui: &mut Ui) { if i >= features.len() { eprintln!("Invalid selected feature"); return; // todo: Ideally set the feature to none. } let feature = &features[i]; ui.label(&feature.label); ui.label(feature.location_descrip(seq_len)); let (r, g, b) = feature.color(); ui.label(RichText::new(feature.feature_type.to_string()).color(Color32::from_rgb(r, g, b))); // todo? for note in &feature.notes { // ui.label(&format!("{}: {}", note.0, note.1)); } } fn primer_text(i: usize, primers: &[Primer], seq_len: usize, ui: &mut Ui) { if i >= primers.len() { eprintln!("Invalid selected primer"); return; // todo: Ideally set the feature to none. } let primer = &primers[i]; ui.label(&primer.name); ui.label(&primer.location_descrip()); // todo: Rev color A/R ui.label(RichText::new(seq_to_str_lower(&primer.sequence)).color(PRIMER_FWD_COLOR)); ui.label(&primer.description.clone().unwrap_or_default()); } /// Add a toolbar to create a feature from selection, if appropriate. fn feature_from_sel(state: &mut State, ui: &mut Ui) { if let Some(text_sel) = state.ui.text_selection { if ui .button(RichText::new("➕ Add feature from sel").color(COLOR_ACTION)) .clicked() { state.generic[state.active].features.push(Feature { range: text_sel, label: state.ui.quick_feature_add_name.clone(), direction: state.ui.quick_feature_add_dir, ..Default::default() }); state.ui.text_selection = None; state.ui.quick_feature_add_name = String::new(); } if ui .button(RichText::new("➕ Add primer from sel").color(COLOR_ACTION)) .clicked() { // todo: DRY with genbank parsing; common fn A/R. let seq = state.get_seq(); let compl = &seq_complement(seq); let seq_primer = match state.ui.quick_feature_add_dir { FeatureDirection::Reverse => { let range = RangeIncl::new( seq.len() - text_sel.end + 1, seq.len() - text_sel.start + 1, ); range.index_seq(compl).unwrap_or_default() } _ => text_sel.index_seq(seq).unwrap_or_default(), } .to_vec(); let volatile = PrimerData::new(&seq_primer); state.generic[state.active].primers.push(Primer { sequence: seq_primer, name: state.ui.quick_feature_add_name.clone(), description: None, volatile, }); state.ui.quick_feature_add_name = String::new(); state.sync_primer_matches(None); state.sync_primer_metrics(); } direction_picker(&mut state.ui.quick_feature_add_dir, 200, ui); ui.label("Name:"); if ui .add(TextEdit::singleline(&mut state.ui.quick_feature_add_name).desired_width(80.)) .gained_focus() { state.ui.text_edit_active = true; // Disable character entries in the sequence. } ui.add_space(COL_SPACING) } } /// Component for the sequence page. pub fn seq_page(state: &mut State, ui: &mut Ui) { ui.horizontal(|ui| { page_seq_top_selector(state, ui); ui.add_space(COL_SPACING); feature_from_sel(state, ui); // Sliders to edit the feature. feature_range_sliders(state, ui); }); // Limit the top section height. let screen_height = ui.ctx().available_rect().height(); let half_screen_height = screen_height / SPLIT_SCREEN_MAX_HEIGHT; match state.ui.page_seq_top { PageSeqTop::Primers => { Frame::none().show(ui, |ui| { ScrollArea::vertical() .max_height(half_screen_height) .id_salt(69) .show(ui, |ui| primer_details(state, ui)); }); } PageSeqTop::Features => { Frame::none().show(ui, |ui| { ScrollArea::vertical() .max_height(half_screen_height) .id_salt(70) .show(ui, |ui| { feature_table(state, ui); }); }); } PageSeqTop::None => (), } ui.add_space(ROW_SPACING); ui.horizontal(|ui| { page_seq_selector(state, ui); ui.add_space(COL_SPACING); ui.label("🔍").on_hover_text( "Search the sequence and its complement for this term. (Ctrl + F to highlight)", ); // This nonstandard way of adding the text input is required for the auto-highlight on ctrl+F behavior. let mut output = TextEdit::singleline(&mut state.ui.search_input) .desired_width(400.) .show(ui); let response = output.response; if state.ui.highlight_search_input { state.ui.highlight_search_input = false; state.ui.text_edit_active = true; // Disable character entries in the sequence. response.request_focus(); output.cursor_range = Some(CursorRange::select_all(&output.galley)); // todo: Not working } if response.gained_focus() { state.ui.text_edit_active = true; // Disable character entries in the sequence. println!("GF"); } if response.changed() { state.ui.text_edit_active = true; state.search_seq = seq_from_str(&state.ui.search_input); state.ui.search_input = seq_to_str_lower(&state.search_seq); // Ensures only valid NTs are present. // todo: This still adds a single char, then blanks the cursor... state.ui.text_cursor_i = None; // Make sure we are not adding chars. state.sync_search(); }; if state.ui.search_input.len() >= MIN_SEARCH_LEN { let len = state.volatile[state.active].search_matches.len(); let text = if len == 1 { "1 match".to_string() } else { format!("{} matches", len) }; ui.label(text); } ui.add_space(COL_SPACING); let mut feature_to_disp = None; let mut primer_to_disp = None; match state.ui.selected_item { Selection::Feature(i) => feature_to_disp = Some(i), Selection::Primer(i) => primer_to_disp = Some(i), Selection::None => { if state.ui.feature_hover.is_some() { feature_to_disp = Some(state.ui.feature_hover.unwrap()); } } } if let Some(feature_i) = feature_to_disp { feature_text( feature_i, &state.generic[state.active].features, state.get_seq().len(), ui, ); } if let Some(primer_i) = primer_to_disp { primer_text( primer_i, &state.generic[state.active].primers, state.get_seq().len(), ui, ); } }); ui.add_space(ROW_SPACING / 2.); ScrollArea::vertical() .id_salt(100) .show(ui, |ui| match state.ui.page_seq { PageSeq::EditRaw => { state.ui.text_cursor_i = None; // prevents double-edits seq_editor_raw(state, ui); } PageSeq::View => { sequence_vis(state, ui); } }); }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
David-OConnor/plascad
https://github.com/David-OConnor/plascad/blob/717459dcd780ec4266e9a2aa15297eae31956da5/src/gui/sequence/feature_overlay.rs
src/gui/sequence/feature_overlay.rs
//! This module is related to drawing features on the sequence view. It is similar to `primer_overlay`. // todo: Abstract out diffs between this and the primer arrow; avoid repeated code. use std::mem; use eframe::{ egui::{Align2, Color32, FontFamily, FontId, Pos2, Shape, Stroke, Ui, pos2}, epaint::PathShape, }; use crate::{ Selection, gui::sequence::{ primer_overlay::{HEIGHT, LABEL_OFFSET, SLANT_DIV2, STROKE_WIDTH}, seq_view::{COLOR_CURSOR, NT_WIDTH_PX, SEQ_ROW_SPACING_PX, SeqViewData}, }, misc_types::{ Feature, FeatureDirection, FeatureDirection::{Forward, Reverse}, FeatureType, }, util::{RangeIncl, get_feature_ranges}, }; const VERTICAL_OFFSET_FEATURE: f32 = 18.; // A fudge factor? /// We include this in this module because visually, it is very similar to the overlay. /// Note: At least for now, selection uses 1-based indexing. pub fn draw_selection(mut selection: RangeIncl, data: &SeqViewData, ui: &mut Ui) -> Vec<Shape> { let mut result = Vec::new(); // This reversal should only occur during reverse dragging; it should resolve when dragging is complete. if selection.start > selection.end { mem::swap(&mut selection.start, &mut selection.end); } if selection.start < 1 || selection.end > data.seq_len { eprintln!("Invalid sequence index"); return result; } // Todo: Cache this, and only update it if row_ranges change. See what else you can optimize // todo in this way. let selection_ranges = get_feature_ranges(&selection, &data.row_ranges, data.seq_len); let selection_ranges_px: Vec<(Pos2, Pos2)> = selection_ranges .iter() .map(|r| (data.seq_i_to_px_rel(r.start), data.seq_i_to_px_rel(r.end))) .collect(); result.append(&mut feature_seq_overlay( &selection_ranges_px, FeatureType::Selection, COLOR_CURSOR, VERTICAL_OFFSET_FEATURE, FeatureDirection::None, "", true, ui, )); result } pub fn draw_features( features: &[Feature], selected_item: Selection, data: &SeqViewData, ui: &mut Ui, ) -> Vec<Shape> { let mut result = Vec::new(); for (i, feature) in features.iter().enumerate() { // Source features generally take up the whole plasmid length. // Alternative: Filter by features that take up the whole length. if feature.feature_type == FeatureType::Source { continue; } if feature.range.start < 1 { eprintln!("Invalid sequence index"); continue; // 0 is invalid, in 1-based indexing, and will underflow. } // Todo: Cache this, and only update it if row_ranges change. See what else you can optimize // todo in this way. let feature_ranges = get_feature_ranges(&feature.range, &data.row_ranges, data.seq_len); let feature_ranges_px: Vec<(Pos2, Pos2)> = feature_ranges .iter() .map(|r| (data.seq_i_to_px_rel(r.start), data.seq_i_to_px_rel(r.end))) .collect(); let selected = match selected_item { Selection::Feature(j) => i == j, _ => false, }; let (r, g, b) = feature.color(); let color = Color32::from_rgb(r, g, b); result.append(&mut feature_seq_overlay( &feature_ranges_px, feature.feature_type, color, VERTICAL_OFFSET_FEATURE, feature.direction, &feature.label(), selected, ui, )); } result } /// Make a visual indicator on the sequence view for a feature, including primers. /// For use inside a Frame::canvas. pub fn feature_seq_overlay( feature_ranges_px: &[(Pos2, Pos2)], feature_type: FeatureType, color: Color32, vertical_offset: f32, direction: FeatureDirection, label: &str, filled: bool, ui: &mut Ui, ) -> Vec<Shape> { if feature_ranges_px.is_empty() { return Vec::new(); } let stroke = Stroke::new(STROKE_WIDTH, color); let color_label = Color32::LIGHT_GREEN; let v_offset_rev = 2. * vertical_offset; // Apply a vertical offset from the sequence. let feature_ranges_px: Vec<(Pos2, Pos2)> = feature_ranges_px .iter() .map(|(start, end)| { ( pos2(start.x, start.y - vertical_offset), pos2(end.x, end.y - vertical_offset), ) }) .collect(); let mut result = Vec::new(); // Depends on font size. let rev_primer_offset = -1.; for (i, &(mut start, mut end)) in feature_ranges_px.iter().enumerate() { // Display the overlay centered around the NT letters, vice above, for non-primer features. if feature_type != FeatureType::Primer { start.y += SEQ_ROW_SPACING_PX / 2. - 2.; end.y += SEQ_ROW_SPACING_PX / 2. - 2.; } let mut top_left = start; let mut top_right = pos2(end.x + NT_WIDTH_PX, end.y); let mut bottom_left = pos2(start.x, start.y + HEIGHT); let mut bottom_right = pos2(end.x + NT_WIDTH_PX, end.y + HEIGHT); // Display reverse primers below the sequence; this vertically mirrors. if feature_type == FeatureType::Primer && direction == Reverse { top_left.y += 3. * HEIGHT - rev_primer_offset; top_right.y += 3. * HEIGHT - rev_primer_offset; bottom_left.y += HEIGHT - rev_primer_offset; bottom_right.y += HEIGHT - rev_primer_offset; } // Add a slant, if applicable. match direction { Forward => { if i + 1 == feature_ranges_px.len() { top_right.x -= SLANT_DIV2; bottom_right.x += SLANT_DIV2; } } Reverse => { if i == 0 { top_left.x += SLANT_DIV2; bottom_left.x -= SLANT_DIV2; } } _ => (), } // let shape = match feature_type { let shape = if filled { Shape::Path(PathShape::convex_polygon( vec![top_left, bottom_left, bottom_right, top_right], stroke.color, stroke, )) } else { Shape::Path(PathShape::closed_line( vec![top_left, bottom_left, bottom_right, top_right], stroke, )) }; result.push(shape); } // todo: Examine. let label_start_x = match direction { Forward => feature_ranges_px[0].0.x, Reverse => feature_ranges_px[feature_ranges_px.len() - 1].1.x, FeatureDirection::None => feature_ranges_px[0].0.x, } + LABEL_OFFSET; let mut label_pos = match direction { Forward => pos2(label_start_x, feature_ranges_px[0].0.y + LABEL_OFFSET), Reverse => pos2( label_start_x, feature_ranges_px[0].0.y + LABEL_OFFSET + v_offset_rev, ), FeatureDirection::None => pos2(label_start_x, feature_ranges_px[0].0.y + LABEL_OFFSET), // todo: Examine }; let label_align = if feature_type == FeatureType::Primer && direction == Reverse { label_pos.y -= 2.; Align2::RIGHT_CENTER } else { Align2::LEFT_CENTER }; let label = ui.ctx().fonts(|fonts| { Shape::text( fonts, label_pos, label_align, label, FontId::new(13., FontFamily::Proportional), color_label, ) }); result.push(label); result }
rust
MIT
717459dcd780ec4266e9a2aa15297eae31956da5
2026-01-04T20:22:11.154589Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/build.rs
ext/build.rs
use std::{ env, error::Error, fs::{create_dir_all, File}, io::{Read, Write}, path::PathBuf, }; fn main() -> Result<(), Box<dyn Error>> { // Propogate linking from rb-sys for usage in the wasmtime-rb Rust crate let _ = rb_sys_env::activate()?; bundle_ruby_file("lib/wasmtime/error.rb")?; bundle_ruby_file("lib/wasmtime/component.rb")?; Ok(()) } fn bundle_ruby_file(filename: &str) -> Result<(), Box<dyn Error>> { let out_dir = PathBuf::from(env::var("OUT_DIR")?).join("bundled"); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); let file = manifest_dir.join("..").join(filename); println!("cargo:rerun-if-changed={}", file.display()); let out_path = file.file_name().unwrap(); let out_path = out_path.to_string_lossy().replace(".rb", ".rs"); let out_path = out_dir.join(out_path); create_dir_all(out_dir)?; let mut out = File::create(out_path)?; let contents = { let mut file = File::open(file)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; contents }; let template = r##" // This file is generated by build.rs use magnus::eval; pub fn init() -> Result<(), magnus::Error> { let _: magnus::Value = eval!( r#" __FILE_CONTENTS__ "# )?; Ok(()) } "##; let contents = template.replace("__FILE_CONTENTS__", &contents); out.write_all(contents.as_bytes())?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/lib.rs
ext/src/lib.rs
#![allow(clippy::doc_lazy_continuation)] use magnus::{Error, Ruby}; mod helpers; mod ruby_api; pub(crate) use ruby_api::*; rb_sys::set_global_tracking_allocator!(); #[magnus::init] pub fn init(ruby: &Ruby) -> Result<(), Error> { #[cfg(ruby_gte_3_0)] unsafe { rb_sys::rb_ext_ractor_safe(true); } ruby_api::init(ruby) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/config.rs
ext/src/ruby_api/config.rs
use crate::{define_rb_intern, helpers::SymbolEnum, PoolingAllocationConfig}; use lazy_static::lazy_static; use magnus::{ prelude::*, r_hash::ForEach, try_convert, typed_data::Obj, Error, RHash, Ruby, Symbol, TryConvert, Value, }; use std::{ convert::{TryFrom, TryInto}, ops::Deref, sync::Arc, }; use wasmtime::{ Config, InstanceAllocationStrategy, OptLevel, ProfilingStrategy, Strategy, WasmBacktraceDetails, }; define_rb_intern!( DEBUG_INFO => "debug_info", WASM_BACKTRACE_DETAILS => "wasm_backtrace_details", NATIVE_UNWIND_INFO => "native_unwind_info", CONSUME_FUEL => "consume_fuel", EPOCH_INTERRUPTION => "epoch_interruption", MAX_WASM_STACK => "max_wasm_stack", WASM_THREADS => "wasm_threads", WASM_MULTI_MEMORY => "wasm_multi_memory", WASM_MEMORY64 => "wasm_memory64", PROFILER => "profiler", CRANELIFT_OPT_LEVEL => "cranelift_opt_level", STRATEGY => "strategy", PARALLEL_COMPILATION => "parallel_compilation", NONE => "none", JITDUMP => "jitdump", VTUNE => "vtune", PERFMAP => "perfmap", SPEED => "speed", SPEED_AND_SIZE => "speed_and_size", TARGET => "target", GENERATE_ADDRESS_MAP => "generate_address_map", AUTO => "auto", CRANELIFT => "cranelift", WINCH => "winch", ALLOCATION_STRATEGY => "allocation_strategy", POOLING => "pooling", ON_DEMAND => "on_demand", WASM_REFERENCE_TYPES => "wasm_reference_types", ASYNC_STACK_ZEROING => "async_stack_zeroing", ); lazy_static! { static ref OPT_LEVEL_MAPPING: SymbolEnum<'static, OptLevel> = { let mapping = vec![ (*NONE, OptLevel::None), (*SPEED, OptLevel::Speed), (*SPEED_AND_SIZE, OptLevel::SpeedAndSize), ]; SymbolEnum::new(":cranelift_opt_level", mapping) }; static ref PROFILING_STRATEGY_MAPPING: SymbolEnum<'static, ProfilingStrategy> = { let mapping = vec![ (*NONE, ProfilingStrategy::None), (*JITDUMP, ProfilingStrategy::JitDump), (*VTUNE, ProfilingStrategy::VTune), (*PERFMAP, ProfilingStrategy::PerfMap), ]; SymbolEnum::new(":profiler", mapping) }; static ref STRATEGY_MAPPING: SymbolEnum<'static, Strategy> = { let mapping = vec![ (*AUTO, Strategy::Auto), (*CRANELIFT, Strategy::Cranelift), (*WINCH, Strategy::Winch), ]; SymbolEnum::new(":strategy", mapping) }; } pub fn hash_to_config(hash: RHash) -> Result<Config, Error> { let ruby = Ruby::get_with(hash); let mut config = Config::default(); hash.foreach(|name: Symbol, value: Value| { let id = magnus::value::Id::from(name); let entry = ConfigEntry(name, value); if *DEBUG_INFO == id { config.debug_info(entry.try_into()?); } else if *WASM_BACKTRACE_DETAILS == id { config.wasm_backtrace_details(entry.try_into()?); } else if *NATIVE_UNWIND_INFO == id { config.native_unwind_info(entry.try_into()?); } else if *CONSUME_FUEL == id { config.consume_fuel(entry.try_into()?); } else if *EPOCH_INTERRUPTION == id { config.epoch_interruption(entry.try_into()?); } else if *MAX_WASM_STACK == id { config.max_wasm_stack(entry.try_into()?); } else if *WASM_THREADS == id { config.wasm_threads(entry.try_into()?); } else if *WASM_MULTI_MEMORY == id { config.wasm_multi_memory(entry.try_into()?); } else if *WASM_MEMORY64 == id { config.wasm_memory64(entry.try_into()?); } else if *PARALLEL_COMPILATION == id { config.parallel_compilation(entry.try_into()?); } else if *WASM_REFERENCE_TYPES == id { config.wasm_reference_types(entry.try_into()?); } else if *PROFILER == id { config.profiler(entry.try_into()?); } else if *CRANELIFT_OPT_LEVEL == id { config.cranelift_opt_level(entry.try_into()?); } else if *STRATEGY == id && cfg!(feature = "winch") { config.strategy(entry.try_into()?); } else if *TARGET == id { let target: Option<String> = entry.try_into()?; if let Some(target) = target { config.target(&target).map_err(|e| { Error::new( ruby.exception_arg_error(), format!("Invalid target: {target}: {e}"), ) })?; } } else if *GENERATE_ADDRESS_MAP == id { config.generate_address_map(entry.try_into()?); } else if *ALLOCATION_STRATEGY == id { let strategy: InstanceAllocationStrategy = entry.try_into()?; config.allocation_strategy(strategy); } else if *ASYNC_STACK_ZEROING == id { config.async_stack_zeroing(entry.try_into()?); } else { return Err(Error::new( ruby.exception_arg_error(), format!("Unknown option: {}", name.inspect()), )); } Ok(ForEach::Continue) })?; Ok(config) } struct ConfigEntry(Symbol, Value); impl ConfigEntry { fn invalid_type(&self) -> Error { let ruby = Ruby::get_with(self.0); Error::new( ruby.exception_type_error(), format!("Invalid option {}: {}", self.1, self.0), ) } } impl TryFrom<ConfigEntry> for bool { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Self::Error> { Self::try_convert(value.1).map_err(|_| value.invalid_type()) } } impl TryFrom<ConfigEntry> for usize { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Self::Error> { Self::try_convert(value.1).map_err(|_| value.invalid_type()) } } impl TryFrom<ConfigEntry> for String { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Self::Error> { Self::try_convert(value.1).map_err(|_| value.invalid_type()) } } impl TryFrom<ConfigEntry> for Option<String> { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Self::Error> { <Option<String>>::try_convert(value.1).map_err(|_| value.invalid_type()) } } impl TryFrom<ConfigEntry> for WasmBacktraceDetails { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<WasmBacktraceDetails, Error> { Ok(match value.1.to_bool() { true => WasmBacktraceDetails::Enable, false => WasmBacktraceDetails::Disable, }) } } impl TryFrom<ConfigEntry> for wasmtime::ProfilingStrategy { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Error> { PROFILING_STRATEGY_MAPPING.get(value.1) } } impl TryFrom<ConfigEntry> for wasmtime::OptLevel { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Error> { OPT_LEVEL_MAPPING.get(value.1) } } impl TryFrom<ConfigEntry> for wasmtime::Strategy { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Error> { STRATEGY_MAPPING.get(value.1) } } impl TryFrom<ConfigEntry> for InstanceAllocationStrategy { type Error = magnus::Error; fn try_from(value: ConfigEntry) -> Result<Self, Error> { let ruby = Ruby::get_with(value.0); if let Ok(strategy) = Obj::<PoolingAllocationConfig>::try_convert(value.1) { return Ok(InstanceAllocationStrategy::Pooling(strategy.to_inner()?)); } if let Ok(symbol) = Symbol::try_convert(value.1) { if symbol.equal(ruby.sym_new("pooling"))? { return Ok(InstanceAllocationStrategy::Pooling(Default::default())); } else if symbol.equal(ruby.sym_new("on_demand"))? { return Ok(InstanceAllocationStrategy::OnDemand); } } Err(Error::new( ruby.exception_arg_error(), format!( "invalid instance allocation strategy: {}", value.1.inspect() ), )) } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/errors.rs
ext/src/ruby_api/errors.rs
use crate::ruby_api::root; use magnus::{error::ErrorType, value::Lazy, Error, ExceptionClass, Module, Ruby}; use std::borrow::Cow; /// Base error class for all Wasmtime errors. pub fn base_error() -> ExceptionClass { static ERR: Lazy<ExceptionClass> = Lazy::new(|_| root().const_get("Error").unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ERR) } /// Raised when failing to convert the return value of a Ruby-backed Func to /// Wasm types. pub fn result_error() -> ExceptionClass { static ERR: Lazy<ExceptionClass> = Lazy::new(|_| root().const_get("ResultError").unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ERR) } /// Raised when converting an {Extern} to its concrete type fails. pub fn conversion_error() -> ExceptionClass { static ERR: Lazy<ExceptionClass> = Lazy::new(|_| root().const_get("ConversionError").unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ERR) } /// Raised when a WASI program terminates early by calling +exit+. pub fn wasi_exit_error() -> ExceptionClass { static ERR: Lazy<ExceptionClass> = Lazy::new(|_| root().const_get("WasiExit").unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ERR) } #[macro_export] macro_rules! err { ($($arg:expr),*) => { Result::Err($crate::error!($($arg),*)) }; } #[macro_export] macro_rules! error { ($($arg:expr),*) => { Error::new($crate::ruby_api::errors::base_error(), format!($($arg),*)) }; } #[macro_export] macro_rules! not_implemented { ($ruby:expr, $($arg:expr),*) => { Err(Error::new($ruby.exception_not_imp_error(), format!($($arg),*))) }; } #[macro_export] macro_rules! conversion_err { ($($arg:expr),*) => { Err(Error::new($crate::ruby_api::errors::conversion_error(), format!("cannot convert {} to {}", $($arg),*))) }; } /// Utilities for reformatting error messages pub trait ExceptionMessage { /// Append a message to an exception fn append<T>(self, extra: T) -> Self where T: Into<Cow<'static, str>>; } impl ExceptionMessage for magnus::Error { fn append<T>(self, extra: T) -> Self where T: Into<Cow<'static, str>>, { match self.error_type() { ErrorType::Error(class, msg) => Error::new(*class, format!("{}{}", msg, extra.into())), ErrorType::Exception(exception) => Error::new( exception.exception_class(), format!("{}{}", exception, extra.into()), ), _ => self, } } } pub(crate) fn missing_wasi_ctx_error(callee: &str) -> String { missing_wasi_error(callee, "WASI", "P2", "wasi_config") } pub(crate) fn missing_wasi_p1_ctx_error() -> String { missing_wasi_error("linker.instantiate", "WASI p1", "P1", "wasi_p1_config") } fn missing_wasi_error( callee: &str, wasi_text: &str, add_wasi_call: &str, option_name: &str, ) -> String { format!( "Store is missing {wasi_text} configuration.\n\n\ When using `WASI::{add_wasi_call}::add_to_linker_sync(linker)`, the Store given to\n\ `{callee}` must have a {wasi_text} configuration.\n\ To fix this, provide the `{option_name}` when creating the Store:\n\ Wasmtime::Store.new(engine, {option_name}: WasiConfig.new)" ) } mod bundled { include!(concat!(env!("OUT_DIR"), "/bundled/error.rs")); } pub fn init() -> Result<(), Error> { bundled::init()?; let _ = base_error(); let _ = result_error(); let _ = conversion_error(); let _ = wasi_exit_error(); Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/func.rs
ext/src/ruby_api/func.rs
use super::{ convert::{ToRubyValue, ToSym, ToValTypeVec, ToWasmVal}, engine, errors::result_error, params::Params, root, store::{Store, StoreContextValue, StoreData}, }; use crate::{error, Caller}; use magnus::{ block::Proc, class, function, gc::Marker, method, prelude::*, scan_args::scan_args, typed_data::Obj, value::Opaque, DataTypeFunctions, Error, IntoValue, Object, RArray, Ruby, TypedData, Value, }; use wasmtime::{Caller as CallerImpl, Func as FuncImpl, Val}; /// @yard /// @rename Wasmtime::FuncType /// Represents a WebAssembly Function Type /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.FuncType.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus( class = "Wasmtime::FuncType", size, mark, free_immediately, unsafe_generics )] pub struct FuncType { inner: wasmtime::FuncType, } impl DataTypeFunctions for FuncType {} impl FuncType { pub fn from_inner(inner: wasmtime::FuncType) -> Self { Self { inner } } /// @yard /// @return [Array<Symbol>] The function's parameter types. pub fn params(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> { let len = rb_self.inner.params().len(); let mut params = rb_self.inner.params(); params.try_fold(ruby.ary_new_capa(len), |array, p| { array.push(p.to_sym()?)?; Ok(array) }) } /// @yard /// @return [Array<Symbol>] The function's result types. pub fn results(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> { let len = rb_self.inner.results().len(); let mut results = rb_self.inner.results(); results.try_fold(ruby.ary_new_capa(len), |array, r| { array.push(r.to_sym()?)?; Ok(array) }) } } impl From<&FuncType> for wasmtime::ExternType { fn from(func: &FuncType) -> Self { Self::Func(func.inner.clone()) } } /// @yard /// @rename Wasmtime::Func /// Represents a WebAssembly Function /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Func.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus( class = "Wasmtime::Func", size, mark, free_immediately, unsafe_generics )] pub struct Func<'a> { store: StoreContextValue<'a>, inner: FuncImpl, } impl DataTypeFunctions for Func<'_> { fn mark(&self, marker: &Marker) { self.store.mark(marker) } } impl<'a> Func<'a> { /// @yard /// /// Creates a WebAssembly function from a Ruby block. WebAssembly functions /// can have 0 or more parameters and results. Each param and result must be a /// valid WebAssembly type represented as a symbol. The valid symbols are: /// +:i32+, +:i64+, +:f32+, +:f64+, +:v128+, +:funcref+, +:externref+. /// /// @def new(store, params, results, &block) /// @param store [Store] /// @param params [Array<Symbol>] The function's parameters. /// @param results [Array<Symbol>] The function's results. /// @param block [Block] The function's implementation. /// /// @yield [caller, *args] The function's body /// @yieldparam caller [Caller] Caller which can be used to interact with the {Store}. /// @yieldparam *args [Object] Splat of Ruby objects matching the function’s params arity. /// @yieldreturn [nil, Object, Array<Object>] The return type depends on function’s results arity: /// * 0 => +nil+ /// * 1 => +Object+ /// * > 1 => +Array<Object>+ /// /// @return [Func] /// /// @example Function that increments an i32: /// store = Wasmtime::Store.new(Wasmtime::Engine.new) /// Wasmtime::Func.new(store, [:i32], [:i32]) do |_caller, arg1| /// arg1.succ /// end /// /// @example Function with 2 params and 2 results: /// store = Wasmtime::Store.new(Wasmtime::Engine.new) /// Wasmtime::Func.new(store, [:i32, :i32], [:i32, :i32]) do |_caller, arg1, arg2| /// [arg1.succ, arg2.succ] /// end pub fn new(args: &[Value]) -> Result<Self, Error> { let args = scan_args::<(Obj<Store>, RArray, RArray), (), (), (), (), Proc>(args)?; let (store, params, results) = args.required; let callable = args.block; store.retain(callable.as_value()); let context = store.context_mut(); let engine = context.engine(); let ty = wasmtime::FuncType::new( engine, params.to_val_type_vec()?, results.to_val_type_vec()?, ); let func_closure = make_func_closure(&ty, callable.into()); let inner = wasmtime::Func::new(context, ty, func_closure); Ok(Self { store: store.into(), inner, }) } pub fn from_inner(store: StoreContextValue<'a>, inner: FuncImpl) -> Self { Self { store, inner } } pub fn get(&self) -> FuncImpl { // Makes a copy (wasmtime::Func implements Copy) self.inner } /// @yard /// Calls a Wasm function. /// /// @def call(*args) /// @param args [Object] /// The arguments to send to the Wasm function. Raises if the arguments do /// not conform to the Wasm function's parameters. /// /// @return [nil, Object, Array<Object>] The return type depends on the function's results arity: /// * 0 => +nil+ /// * 1 => +Object+ /// * > 1 => +Array<Object>+ /// @example /// store = Wasmtime::Store.new(Wasmtime::Engine.new) /// func = Wasmtime::Func.new(store, [:i32, :i32], [:i32, :i32]) do |_caller, arg1, arg2| /// [arg1.succ, arg2.succ] /// end /// func.call(1, 2) # => [2, 3] pub fn call(&self, args: &[Value]) -> Result<Value, Error> { let ruby = Ruby::get().unwrap(); Self::invoke(&ruby, &self.store, &self.inner, args) } pub fn inner(&self) -> &FuncImpl { &self.inner } /// @yard /// @return [Array<Symbol>] The function's parameter types. pub fn params(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> { let ty = rb_self.inner.ty(rb_self.store.context()?); let len = ty.params().len(); let mut params = ty.params(); params.try_fold(ruby.ary_new_capa(len), |array, p| { array.push(p.to_sym()?)?; Ok(array) }) } /// @yard /// @return [Array<Symbol>] The function's result types. pub fn results(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> { let ty = rb_self.inner.ty(rb_self.store.context()?); let len = ty.results().len(); let mut results = ty.results(); results.try_fold(ruby.ary_new_capa(len), |array, r| { array.push(r.to_sym()?)?; Ok(array) }) } pub fn invoke( ruby: &Ruby, store: &StoreContextValue, func: &wasmtime::Func, args: &[Value], ) -> Result<Value, Error> { let mut context = store.context_mut()?; let func_ty = func.ty(&mut context); let params = Params::new(ruby, &func_ty, args)?.to_vec(ruby, store)?; let mut results = vec![Val::null_func_ref(); func_ty.results().len()]; func.call(context, &params, &mut results) .map_err(|e| store.handle_wasm_error(ruby, e))?; match results.as_slice() { [] => Ok(().into_value_with(ruby)), [result] => result.to_ruby_value(ruby, store), _ => { let ary = ruby.ary_new_capa(results.len()); for result in results { let val = result.to_ruby_value(ruby, store)?; ary.push(val)?; } Ok(ary.into_value_with(ruby)) } } } } impl From<&Func<'_>> for wasmtime::Extern { fn from(func: &Func) -> Self { Self::Func(func.get()) } } macro_rules! caller_error { ($store:expr, $caller:expr, $error:expr) => {{ $store.set_last_error($error); $caller.expire(); Err(wasmtime::Error::msg("")) }}; } macro_rules! result_error { ($store:expr, $caller:expr, $msg:expr) => {{ let error = Error::new(result_error(), $msg); caller_error!($store, $caller, error) }}; } pub fn make_func_closure( ty: &wasmtime::FuncType, callable: Opaque<Proc>, ) -> impl Fn(CallerImpl<'_, StoreData>, &[Val], &mut [Val]) -> wasmtime::Result<()> + Send + Sync + 'static { let ty = ty.to_owned(); // The error handling here is a bit tricky. We want to return a Ruby exception, // but doing so directly can easily cause an early Ruby GC and segfault. So to // be safe, we store all Ruby errors on the store context so it can be marked. // We then return a generic error here. The caller will check for a stored error // and raise it if it exists. move |caller_impl: CallerImpl<'_, StoreData>, params: &[Val], results: &mut [Val]| { let ruby = Ruby::get().unwrap(); let wrapped_caller = ruby.obj_wrap(Caller::new(caller_impl)); let store_context = StoreContextValue::from(wrapped_caller); let rparams = ruby.ary_new_capa(params.len() + 1); rparams .push(wrapped_caller.as_value()) .map_err(|e| wasmtime::Error::msg(format!("failed to push caller: {e}")))?; for (i, param) in params.iter().enumerate() { let val = param .to_ruby_value(&ruby, &store_context) .map_err(|e| wasmtime::Error::msg(format!("invalid argument at index {i}: {e}")))?; rparams.push(val).map_err(|e| { wasmtime::Error::msg(format!("failed to push argument at index {i}: {e}")) })?; } let callable = ruby.get_inner(callable); match (callable.call(rparams), results.len()) { (Ok(_proc_result), 0) => { wrapped_caller.expire(); Ok(()) } (Ok(proc_result), n) => { // For len=1, accept both `val` and `[val]` let Ok(proc_result) = RArray::to_ary(proc_result) else { return result_error!( store_context, wrapped_caller, format!("could not convert {} to results array", callable) ); }; if proc_result.len() != results.len() { return result_error!( store_context, wrapped_caller, format!( "wrong number of results (given {}, expected {}) in {}", proc_result.len(), n, callable ) ); } for (i, ((rb_val, wasm_val), ty)) in unsafe { proc_result.as_slice() } .iter() .zip(results.iter_mut()) .zip(ty.results()) .enumerate() { match rb_val.to_wasm_val(&store_context, ty) { Ok(val) => *wasm_val = val, Err(e) => { return result_error!( store_context, wrapped_caller, format!("invalid result at index {i}: {e} in {callable}") ); } } } wrapped_caller.expire(); Ok(()) } (Err(e), _) => { caller_error!(store_context, wrapped_caller, e) } } } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let func_type = root().define_class("FuncType", ruby.class_object())?; func_type.define_method("params", method!(FuncType::params, 0))?; func_type.define_method("results", method!(FuncType::results, 0))?; let func = root().define_class("Func", ruby.class_object())?; func.define_singleton_method("new", function!(Func::new, -1))?; func.define_method("call", method!(Func::call, -1))?; func.define_method("params", method!(Func::params, 0))?; func.define_method("results", method!(Func::results, 0))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/engine.rs
ext/src/ruby_api/engine.rs
use super::{config::hash_to_config, root}; use crate::{ error, helpers::{nogvl, Tmplock}, }; use magnus::{ class, function, method, prelude::*, scan_args, typed_data::Obj, value::LazyId, Error, Module, Object, RHash, RString, Ruby, TryConvert, Value, }; use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, sync::Mutex, }; use wasmtime::{Config, Engine as EngineImpl}; #[cfg(feature = "tokio")] lazy_static::lazy_static! { static ref TOKIO_RT: tokio::runtime::Runtime = tokio::runtime::Builder::new_multi_thread() .thread_name("wasmtime-engine-timers") .worker_threads(1) .enable_io() .build() .unwrap(); } /// @yard /// Represents a Wasmtime execution engine. /// /// @example Disabling parallel compilation /// # Many Ruby servers use a pre-forking mechanism to allow parallel request /// # processing. Unfortunately, this can causes processes to deadlock if you /// # use parallel compilation to compile Wasm prior to calling /// # `Process::fork`. To avoid this issue, any compilations that need to be /// # done before forking need to disable the `parallel_compilation` option. /// /// prefork_engine = Wasmtime::Engine.new(parallel_compilation: false) /// wasm_module = Wasmtime::Module.new(prefork_engine, "(module)") /// /// fork do /// # We can enable parallel compilation now that we've forked. /// engine = Wasmtime::Engine.new(parallel_compilation: true) /// store = Wasmtime::Store.new(engine) /// instance = Wasmtime::Instance.new(store, wasm_module) /// # ... /// end /// /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Engine.html Wasmtime's Rust doc #[magnus::wrap(class = "Wasmtime::Engine", free_immediately, frozen_shareable)] pub struct Engine { inner: EngineImpl, #[cfg(feature = "tokio")] timer_task: Mutex<Option<tokio::task::JoinHandle<()>>>, } #[cfg(feature = "tokio")] impl Drop for Engine { fn drop(&mut self) { self.stop_epoch_interval() } } impl Engine { /// @yard /// @def new(config = {}) /// @param config [Hash] The engine's config. /// See the {https://docs.rs/wasmtime/latest/wasmtime/struct.Engine.html +Config+‘s Rust doc} for detailed description of /// the different options and the defaults. /// @option config [Boolean] :async_stack_zeroing Configures whether or not stacks used for async futures are zeroed before (re)use. /// @option config [Boolean] :debug_info /// @option config [Boolean] :wasm_backtrace_details /// @option config [Boolean] :native_unwind_info /// @option config [Boolean] :consume_fuel /// @option config [Boolean] :epoch_interruption /// @option config [Integer] :max_wasm_stack /// @option config [Boolean] :wasm_threads /// @option config [Boolean] :wasm_multi_memory /// @option config [Boolean] :wasm_memory64 /// @option config [Boolean] :wasm_reference_types /// @option config [Boolean] :parallel_compilation (true) Whether compile Wasm using multiple threads /// @option config [Boolean] :generate_address_map Configures whether compiled artifacts will contain information to map native program addresses back to the original wasm module. This configuration option is `true` by default. Disabling this feature can result in considerably smaller serialized modules. /// @option config [Symbol] :cranelift_opt_level One of +none+, +speed+, +speed_and_size+. /// @option config [Symbol] :profiler One of +none+, +jitdump+, +vtune+. /// @option config [Symbol] :strategy One of +auto+, +cranelift+, +winch+ /// @option config [String] :target /// /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Engine.html /// Wasmtime's Rust doc for details of the configuration options. pub fn new(args: &[Value]) -> Result<Self, Error> { let args = scan_args::scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?; let (config,) = args.optional; let config = config.and_then(|v| if v.is_nil() { None } else { Some(v) }); let inner = match config { Some(config) => { let config = RHash::try_convert(config).and_then(hash_to_config)?; EngineImpl::new(&config).map_err(|e| error!("{}", e))? } None => EngineImpl::new(&Config::default()).map_err(|e| error!("{}", e))?, }; Ok(Self { inner, #[cfg(feature = "tokio")] timer_task: Default::default(), }) } /// @yard /// Starts a timer that will increment the engine's epoch every +milliseconds+. /// Waits +milliseconds+ before incrementing for the first time. /// /// If a prior timer was started, it will be stopped. /// @def start_epoch_interval(milliseconds) /// @param milliseconds [Integer] /// @return [nil] #[cfg(feature = "tokio")] pub fn start_epoch_interval(&self, milliseconds: u64) { self.stop_epoch_interval(); let engine = self.inner.clone(); let handle = TOKIO_RT.spawn(async move { let tick_every = tokio::time::Duration::from_millis(milliseconds); let mut interval = async_timer::Interval::platform_new(tick_every); loop { interval.wait().await; engine.increment_epoch(); } }); *self.timer_task.lock().unwrap() = Some(handle); } /// @yard /// Stops a previously started timer with {#start_epoch_interval}. /// Does nothing if there is no running timer. /// @return [nil] #[cfg(feature = "tokio")] pub fn stop_epoch_interval(&self) { let maybe_handle = self.timer_task.lock().unwrap().take(); if let Some(handle) = maybe_handle { handle.abort(); } } /// @yard /// Manually increment the engine's epoch. /// Note: this cannot be used from a different thread while WebAssembly is /// running because the Global VM lock (GVL) is not released. /// Using {#start_epoch_interval} is recommended because it sidesteps the GVL. /// @return [nil] pub fn increment_epoch(&self) { self.inner.increment_epoch(); } pub fn is_equal(&self, other: &Engine) -> bool { EngineImpl::same(self.get(), other.get()) } /// @yard /// AoT compile a WebAssembly text or WebAssembly binary module for later use. /// /// The compiled module can be instantiated using {Module.deserialize}. /// /// @def precompile_module(wat_or_wasm) /// @param wat_or_wasm [String] The String of WAT or Wasm. /// @return [String] Binary String of the compiled module. /// @see Module.deserialize pub fn precompile_module( ruby: &Ruby, rb_self: Obj<Self>, wat_or_wasm: RString, ) -> Result<RString, Error> { let (wat_or_wasm, _guard) = wat_or_wasm.as_locked_slice()?; nogvl(|| rb_self.inner.precompile_module(wat_or_wasm)) .map(|bytes| ruby.str_from_slice(&bytes)) .map_err(|e| error!("{}", e.to_string())) } /// @yard /// AoT compile a WebAssembly text or WebAssembly binary component for later use. /// /// The compiled component can be instantiated using {Component::Component.deserialize}. /// /// @def precompile_component(wat_or_wasm) /// @param wat_or_wasm [String] The String of WAT or Wasm component. /// @return [String] Binary String of the compiled component. /// @see Component::Component.deserialize pub fn precompile_component( ruby: &Ruby, rb_self: Obj<Self>, wat_or_wasm: RString, ) -> Result<RString, Error> { let (wat_or_wasm, _guard) = wat_or_wasm.as_locked_slice()?; nogvl(|| rb_self.inner.precompile_component(wat_or_wasm)) .map(|bytes| ruby.str_from_slice(&bytes)) .map_err(|e| error!("{}", e.to_string())) } /// @yard /// If two engines have a matching {Engine.precompile_compatibility_key}, /// then serialized modules from one engine can be deserialized by the /// other. /// @return [String] The hex formatted string that can be used to check precompiled module compatibility. pub fn precompile_compatibility_key(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RString, Error> { static ID: LazyId = LazyId::new("precompile_compatibility_key"); let ivar_id = LazyId::get_inner_with(&ID, ruby); if let Ok(cached) = rb_self.ivar_get::<_, RString>(ivar_id) { return Ok(cached); } let mut hasher = DefaultHasher::new(); let engine = rb_self.inner.clone(); engine.precompile_compatibility_hash().hash(&mut hasher); let hex_encoded = format!("{:x}", hasher.finish()); let key = ruby.str_new(&hex_encoded); key.freeze(); rb_self.ivar_set(ivar_id, key)?; Ok(key) } pub fn get(&self) -> &EngineImpl { &self.inner } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("Engine", ruby.class_object())?; class.define_singleton_method("new", function!(Engine::new, -1))?; #[cfg(feature = "tokio")] class.define_method( "start_epoch_interval", method!(Engine::start_epoch_interval, 1), )?; #[cfg(feature = "tokio")] class.define_method( "stop_epoch_interval", method!(Engine::stop_epoch_interval, 0), )?; class.define_method("increment_epoch", method!(Engine::increment_epoch, 0))?; class.define_method("==", method!(Engine::is_equal, 1))?; class.define_method("precompile_module", method!(Engine::precompile_module, 1))?; class.define_method( "precompile_component", method!(Engine::precompile_component, 1), )?; class.define_method( "precompile_compatibility_key", method!(Engine::precompile_compatibility_key, 0), )?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/global.rs
ext/src/ruby_api/global.rs
use super::{ convert::{ToRubyValue, ToSym, ToValType, ToWasmVal}, root, store::{Store, StoreContextValue}, }; use crate::error; use magnus::{ class, function, gc::Marker, method, prelude::*, typed_data::Obj, DataTypeFunctions, Error, Object, Ruby, Symbol, TypedData, Value, }; use wasmtime::{Extern, Global as GlobalImpl, Mutability}; #[derive(TypedData)] #[magnus( class = "Wasmtime::GlobalType", free_immediately, mark, unsafe_generics )] pub struct GlobalType { inner: wasmtime::GlobalType, } impl DataTypeFunctions for GlobalType { fn mark(&self, _marker: &Marker) {} } impl GlobalType { pub fn from_inner(inner: wasmtime::GlobalType) -> Self { Self { inner } } /// @yard /// @def const? /// @return [Boolean] pub fn is_const(&self) -> bool { self.inner.mutability() == Mutability::Const } /// @yard /// @def var? /// @return [Boolean] pub fn is_var(&self) -> bool { self.inner.mutability() == Mutability::Var } /// @yard /// @def type /// @return [Symbol] The Wasm type of the global‘s content. pub fn type_(&self) -> Result<Symbol, Error> { self.inner.content().to_sym() } } impl From<&GlobalType> for wasmtime::ExternType { fn from(global_type: &GlobalType) -> Self { Self::Global(global_type.inner.clone()) } } /// @yard /// @rename Wasmtime::Global /// Represents a WebAssembly global. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Global.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus(class = "Wasmtime::Global", free_immediately, mark, unsafe_generics)] pub struct Global<'a> { store: StoreContextValue<'a>, inner: GlobalImpl, } impl DataTypeFunctions for Global<'_> { fn mark(&self, marker: &Marker) { self.store.mark(marker) } } impl<'a> Global<'a> { /// @yard /// @def const(store, type, default) /// @param store [Store] /// @param type [Symbol] The WebAssembly type of the value held by this global. /// @param default [Object] The default value of this global. /// @return [Global] A constant global. pub fn const_(store: Obj<Store>, value_type: Symbol, default: Value) -> Result<Self, Error> { Self::new(store, value_type, default, Mutability::Const) } /// @yard /// @def var(store, type, default:) /// @param store [Store] /// @param type [Symbol] The WebAssembly type of the value held by this global. /// @param default [Object] The default value of this global. /// @return [Global] A variable global. pub fn var(store: Obj<Store>, value_type: Symbol, default: Value) -> Result<Self, Error> { Self::new(store, value_type, default, Mutability::Var) } fn new( store: Obj<Store>, value_type: Symbol, default: Value, mutability: Mutability, ) -> Result<Self, Error> { let wasm_type = value_type.to_val_type()?; let wasm_default = default.to_wasm_val(&store.into(), wasm_type.clone())?; let inner = GlobalImpl::new( store.context_mut(), wasmtime::GlobalType::new(wasm_type, mutability), wasm_default, ) .map_err(|e| error!("{}", e))?; let global = Self { store: store.into(), inner, }; global.retain_non_nil_extern_ref(default)?; Ok(global) } pub fn from_inner(store: StoreContextValue<'a>, inner: GlobalImpl) -> Self { Self { store, inner } } /// @yard /// @def const? /// @return [Boolean] pub fn is_const(&self) -> Result<bool, Error> { self.ty().map(|ty| ty.mutability() == Mutability::Const) } /// @yard /// @def var? /// @return [Boolean] pub fn is_var(&self) -> Result<bool, Error> { self.ty().map(|ty| ty.mutability() == Mutability::Var) } /// @yard /// @def type /// @return [Symbol] The Wasm type of the global‘s content. pub fn type_(&self) -> Result<Symbol, Error> { self.ty()?.content().to_sym() } /// @yard /// @return [Object] The current value of the global. pub fn get(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { rb_self .inner .get(rb_self.store.context_mut()?) .to_ruby_value(ruby, &rb_self.store) } /// @yard /// Sets the value of the global. Raises if the global is a +const+. /// @def set(value) /// @param value [Object] An object that can be converted to the global's type. /// @return [nil] pub fn set(&self, value: Value) -> Result<(), Error> { self.inner .set( self.store.context_mut()?, value.to_wasm_val(&self.store, self.value_type()?)?, ) .map_err(|e| error!("{}", e)) .and_then(|result| { self.retain_non_nil_extern_ref(value)?; Ok(result) }) } fn ty(&self) -> Result<wasmtime::GlobalType, Error> { Ok(self.inner.ty(self.store.context()?)) } fn value_type(&self) -> Result<wasmtime::ValType, Error> { self.ty().map(|ty| ty.content().clone()) } fn retain_non_nil_extern_ref(&self, value: Value) -> Result<(), Error> { if !value.is_nil() && self.value_type()?.matches(&wasmtime::ValType::EXTERNREF) { self.store.retain(value)?; } Ok(()) } pub fn inner(&self) -> GlobalImpl { self.inner } } impl From<&Global<'_>> for Extern { fn from(global: &Global) -> Self { Self::Global(global.inner()) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let type_class = root().define_class("GlobalType", ruby.class_object())?; type_class.define_method("const?", method!(GlobalType::is_const, 0))?; type_class.define_method("var?", method!(GlobalType::is_var, 0))?; type_class.define_method("type", method!(GlobalType::type_, 0))?; let class = root().define_class("Global", ruby.class_object())?; class.define_singleton_method("var", function!(Global::var, 3))?; class.define_singleton_method("const", function!(Global::const_, 3))?; class.define_method("const?", method!(Global::is_const, 0))?; class.define_method("var?", method!(Global::is_var, 0))?; class.define_method("type", method!(Global::type_, 0))?; class.define_method("get", method!(Global::get, 0))?; class.define_method("set", method!(Global::set, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/wasi.rs
ext/src/ruby_api/wasi.rs
use crate::{ruby_api::component, Linker}; use super::root; use magnus::{class, function, typed_data::Obj, Error, Module, Object, RModule, Ruby}; #[magnus::wrap(class = "Wasmtime::WASI::P1", free_immediately)] struct P1; impl P1 { pub fn add_to_linker_sync(linker: Obj<Linker>) -> Result<(), Error> { linker.add_wasi_p1() } } #[magnus::wrap(class = "Wasmtime::WASI::P2", free_immediately)] struct P2; impl P2 { pub fn add_to_linker_sync(linker: Obj<component::Linker>) -> Result<(), Error> { linker.add_wasi_p2() } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let namespace = root().define_module("WASI")?; let p1_class = namespace.define_class("P1", ruby.class_object())?; p1_class.define_singleton_method("add_to_linker_sync", function!(P1::add_to_linker_sync, 1))?; let p2_class = namespace.define_class("P2", ruby.class_object())?; p2_class.define_singleton_method("add_to_linker_sync", function!(P2::add_to_linker_sync, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/store.rs
ext/src/ruby_api/store.rs
use super::errors::wasi_exit_error; use super::{caller::Caller, engine::Engine, root, trap::Trap}; use crate::{define_rb_intern, error, WasiConfig}; use magnus::value::StaticSymbol; use magnus::{ class, function, gc::{Compactor, Marker}, method, scan_args, typed_data::Obj, value::Opaque, DataTypeFunctions, Error, IntoValue, Module, Object, Ruby, TypedData, Value, }; use magnus::{Class, RHash}; use rb_sys::tracking_allocator::{ManuallyTracked, TrackingAllocator}; use std::borrow::Borrow; use std::cell::UnsafeCell; use std::convert::TryFrom; use wasmtime::{ AsContext, AsContextMut, ResourceLimiter, Store as StoreImpl, StoreContext, StoreContextMut, StoreLimits, StoreLimitsBuilder, }; use wasmtime_wasi::p1::WasiP1Ctx; use wasmtime_wasi::{I32Exit, ResourceTable}; use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView}; define_rb_intern!( WASI_CONFIG => "wasi_config", WASI_P1_CONFIG => "wasi_p1_config", LIMITS => "limits", ); pub struct StoreData { user_data: Value, wasi_p1: Option<WasiP1Ctx>, wasi: Option<WasiCtx>, refs: Vec<Value>, last_error: Option<Error>, store_limits: TrackingResourceLimiter, resource_table: ResourceTable, } impl StoreData { pub fn user_data(&self) -> Value { self.user_data } pub fn has_wasi_p1_ctx(&self) -> bool { self.wasi_p1.is_some() } pub fn has_wasi_ctx(&self) -> bool { self.wasi.is_some() } pub fn wasi_p1_ctx_mut(&mut self) -> &mut WasiP1Ctx { self.wasi_p1 .as_mut() .expect("Store must have a WASI context") } pub fn retain(&mut self, value: Value) { self.refs.push(value); } pub fn set_error(&mut self, error: Error) { self.last_error = Some(error); } pub fn take_error(&mut self) -> Option<Error> { self.last_error.take() } pub fn mark(&self, marker: &Marker) { marker.mark_movable(self.user_data); if let Some(ref error) = self.last_error { if let Some(val) = error.value() { marker.mark(val); } } for value in self.refs.iter() { marker.mark_movable(*value); } } pub fn compact(&mut self, compactor: &Compactor) { self.user_data = compactor.location(self.user_data); for value in self.refs.iter_mut() { *value = compactor.location(*value); } } } /// @yard /// Represents a WebAssembly store. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Store.html Wasmtime's Rust doc #[derive(Debug, TypedData)] #[magnus(class = "Wasmtime::Store", size, mark, compact, free_immediately)] pub struct Store { inner: UnsafeCell<StoreImpl<StoreData>>, } impl DataTypeFunctions for Store { fn mark(&self, marker: &Marker) { self.context().data().mark(marker); } fn compact(&self, compactor: &Compactor) { self.context_mut().data_mut().compact(compactor); } } unsafe impl Send for Store {} unsafe impl Send for StoreData {} impl Store { /// @yard /// /// @def new(engine, data = nil, wasi_config: nil, wasi_p1_config: nil, limits: nil) /// @param engine [Wasmtime::Engine] /// The engine for this store. /// @param data [Object] /// The data attached to the store. Can be retrieved through {Wasmtime::Store#data} and {Wasmtime::Caller#data}. /// @param wasi_config [Wasmtime::WasiConfig] /// The WASI config to use in this store. /// @param wasi_p1_config [Wasmtime::WasiConfig] /// The WASI config to use in this store for WASI preview 1. /// @param limits [Hash] /// See the {https://docs.rs/wasmtime/latest/wasmtime/struct.StoreLimitsBuilder.html +StoreLimitsBuilder+'s Rust doc} /// for detailed description of the different options and the defaults. /// @option limits memory_size [Integer] /// The maximum number of bytes a linear memory can grow to. /// @option limits table_elements [Integer] /// The maximum number of elements in a table. /// @option limits instances [Integer] /// The maximum number of instances that can be created for a Store. /// @option limits tables [Integer] /// The maximum number of tables that can be created for a Store. /// @option limits memories [Integer] /// The maximum number of linear memories that can be created for a Store. /// @return [Wasmtime::Store] /// /// @example /// store = Wasmtime::Store.new(Wasmtime::Engine.new) /// /// @example /// store = Wasmtime::Store.new(Wasmtime::Engine.new, {}) pub fn new(args: &[Value]) -> Result<Self, Error> { let ruby = Ruby::get().unwrap(); let args = scan_args::scan_args::<(&Engine,), (Option<Value>,), (), (), _, ()>(args)?; let kw = scan_args::get_kwargs::< _, (), (Option<&WasiConfig>, Option<&WasiConfig>, Option<RHash>), (), >( args.keywords, &[], &[*WASI_CONFIG, *WASI_P1_CONFIG, *LIMITS], )?; let (engine,) = args.required; let (user_data,) = args.optional; let user_data = user_data.unwrap_or_else(|| ().into_value_with(&ruby)); let wasi_config = kw.optional.0; let wasi_p1_config = kw.optional.1; let wasi = wasi_config .map(|wasi_config| wasi_config.build(&ruby)) .transpose()?; let wasi_p1 = wasi_p1_config .map(|wasi_config| wasi_config.build_p1(&ruby)) .transpose()?; let limiter = match kw.optional.2 { None => StoreLimitsBuilder::new(), Some(limits) => hash_to_store_limits_builder(&ruby, limits)?, } .build(); let limiter = TrackingResourceLimiter::new(limiter); let eng = engine.get(); let store_data = StoreData { user_data, wasi_p1, wasi, refs: Default::default(), last_error: Default::default(), store_limits: limiter, resource_table: Default::default(), }; let store = Self { inner: UnsafeCell::new(StoreImpl::new(eng, store_data)), }; unsafe { &mut *store.inner.get() }.limiter(|data| &mut data.store_limits); Ok(store) } /// @yard /// @return [Object] The passed in value in {.new} pub fn data(&self) -> Value { self.context().data().user_data() } /// @yard /// Returns the amount of fuel in the {Store}. /// /// @return [Integer] /// @raise [Error] if fuel consumption is not enabled via {Wasmtime::Engine#new} pub fn get_fuel(&self) -> Result<u64, Error> { self.inner_ref().get_fuel().map_err(|e| error!("{}", e)) } /// @yard /// Sets fuel to the {Store}. /// @param fuel [Integer] The new fuel amount. /// @def set_fuel(fuel) /// @raise [Error] if fuel consumption is not enabled via {Wasmtime::Engine#new} pub fn set_fuel(&self, fuel: u64) -> Result<(), Error> { unsafe { &mut *self.inner.get() } .set_fuel(fuel) .map_err(|e| error!("{}", e))?; Ok(()) } /// @yard /// Sets the epoch deadline to a certain number of ticks in the future. /// /// Raises if there isn't enough fuel left in the {Store}, or /// when the {Engine}'s config does not have fuel enabled. /// /// @see ttps://docs.rs/wasmtime/latest/wasmtime/struct.Store.html#method.set_epoch_deadline Rust's doc on +set_epoch_deadline_ for more details. /// @def set_epoch_deadline(ticks_beyond_current) /// @param ticks_beyond_current [Integer] The number of ticks before this store reaches the deadline. /// @return [nil] pub fn set_epoch_deadline(&self, ticks_beyond_current: u64) { unsafe { &mut *self.inner.get() }.set_epoch_deadline(ticks_beyond_current); } /// @yard /// @def linear_memory_limit_hit? /// Returns whether the linear memory limit has been hit. /// /// @return [Boolean] pub fn linear_memory_limit_hit(&self) -> bool { self.context().data().store_limits.linear_memory_limit_hit() } /// @yard /// Returns the maximum linear memory consumed. /// /// @return [Integer] pub fn max_linear_memory_consumed(&self) -> usize { self.context() .data() .store_limits .max_linear_memory_consumed() } pub fn context(&self) -> StoreContext<'_, StoreData> { unsafe { (*self.inner.get()).as_context() } } pub fn context_mut(&self) -> StoreContextMut<'_, StoreData> { unsafe { (*self.inner.get()).as_context_mut() } } pub fn retain(&self, value: Value) { self.context_mut().data_mut().retain(value); } pub fn take_last_error(&self) -> Option<Error> { self.context_mut().data_mut().take_error() } fn inner_ref(&self) -> &StoreImpl<StoreData> { unsafe { &*self.inner.get() } } } /// A wrapper around a Ruby Value that has a store context. /// Used in places where both Store or Caller can be used. #[derive(Clone, Copy)] pub enum StoreContextValue<'a> { Store(Opaque<Obj<Store>>), Caller(Opaque<Obj<Caller<'a>>>), } impl From<Obj<Store>> for StoreContextValue<'_> { fn from(store: Obj<Store>) -> Self { StoreContextValue::Store(store.into()) } } impl<'a> From<Obj<Caller<'a>>> for StoreContextValue<'a> { fn from(caller: Obj<Caller<'a>>) -> Self { StoreContextValue::Caller(caller.into()) } } impl StoreContextValue<'_> { pub fn mark(&self, marker: &Marker) { match self { Self::Store(store) => marker.mark(*store), Self::Caller(_) => { // The Caller is on the stack while it's "live". Right before the end of a host call, // we remove the Caller form the Ruby object, thus there is no need to mark. } } } pub fn context(&self) -> Result<StoreContext<'_, StoreData>, Error> { let ruby = Ruby::get().unwrap(); match self { Self::Store(store) => Ok(ruby.get_inner_ref(store).context()), Self::Caller(caller) => ruby.get_inner_ref(caller).context(), } } pub fn context_mut(&self) -> Result<StoreContextMut<'_, StoreData>, Error> { let ruby = Ruby::get().unwrap(); match self { Self::Store(store) => Ok(ruby.get_inner_ref(store).context_mut()), Self::Caller(caller) => ruby.get_inner_ref(caller).context_mut(), } } pub fn set_last_error(&self, error: Error) { let ruby = Ruby::get().unwrap(); match self { Self::Store(store) => ruby .get_inner(*store) .context_mut() .data_mut() .set_error(error), Self::Caller(caller) => { if let Ok(mut context) = ruby.get_inner(*caller).context_mut() { context.data_mut().set_error(error); } } }; } pub fn handle_wasm_error(&self, ruby: &Ruby, error: wasmtime::Error) -> Error { if let Ok(Some(error)) = self.take_last_error() { error } else if let Some(exit) = error.downcast_ref::<I32Exit>() { wasi_exit_error().new_instance((exit.0,)).unwrap().into() } else { Trap::try_from(error) .map(|trap| trap.into_error(ruby)) .unwrap_or_else(|e| error!("{}", e)) } } pub fn retain(&self, value: Value) -> Result<(), Error> { self.context_mut()?.data_mut().retain(value); Ok(()) } fn take_last_error(&self) -> Result<Option<Error>, Error> { let ruby = Ruby::get().unwrap(); match self { Self::Store(store) => Ok(ruby.get_inner(*store).take_last_error()), Self::Caller(caller) => Ok(ruby .get_inner(*caller) .context_mut()? .data_mut() .take_error()), } } } fn hash_to_store_limits_builder(ruby: &Ruby, limits: RHash) -> Result<StoreLimitsBuilder, Error> { let mut limiter: StoreLimitsBuilder = StoreLimitsBuilder::new(); if let Some(memory_size) = limits.lookup::<_, Option<usize>>(ruby.sym_new("memory_size"))? { limiter = limiter.memory_size(memory_size); } if let Some(table_elements) = limits.lookup::<_, Option<usize>>(ruby.sym_new("table_elements"))? { limiter = limiter.table_elements(table_elements); } if let Some(instances) = limits.lookup::<_, Option<u64>>(ruby.sym_new("instances"))? { limiter = limiter.instances(instances as usize); } if let Some(tables) = limits.lookup::<_, Option<u64>>(ruby.sym_new("tables"))? { limiter = limiter.tables(tables as usize); } if let Some(memories) = limits.lookup::<_, Option<u64>>(ruby.sym_new("memories"))? { limiter = limiter.memories(memories as usize); } Ok(limiter) } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("Store", ruby.class_object())?; class.define_singleton_method("new", function!(Store::new, -1))?; class.define_method("data", method!(Store::data, 0))?; class.define_method("get_fuel", method!(Store::get_fuel, 0))?; class.define_method("set_fuel", method!(Store::set_fuel, 1))?; class.define_method("set_epoch_deadline", method!(Store::set_epoch_deadline, 1))?; class.define_method( "linear_memory_limit_hit?", method!(Store::linear_memory_limit_hit, 0), )?; class.define_method( "max_linear_memory_consumed", method!(Store::max_linear_memory_consumed, 0), )?; Ok(()) } /// A resource limiter proxy used to report memory usage to Ruby's GC. struct TrackingResourceLimiter { inner: StoreLimits, tracker: ManuallyTracked<()>, linear_memory_limit_hit: bool, max_linear_memory_consumed: usize, } impl TrackingResourceLimiter { /// Create a new tracking limiter around an inner limiter. pub fn new(resource_limiter: StoreLimits) -> Self { Self { inner: resource_limiter, tracker: ManuallyTracked::new(0), linear_memory_limit_hit: false, max_linear_memory_consumed: 0, } } pub fn linear_memory_limit_hit(&self) -> bool { self.linear_memory_limit_hit } pub fn max_linear_memory_consumed(&self) -> usize { self.max_linear_memory_consumed } } impl ResourceLimiter for TrackingResourceLimiter { fn memory_growing( &mut self, current: usize, desired: usize, maximum: Option<usize>, ) -> wasmtime::Result<bool> { let res = self.inner.memory_growing(current, desired, maximum); // Update max_linear_memory_consumed self.max_linear_memory_consumed = self.max_linear_memory_consumed.max(desired); if res.is_ok() { self.tracker.increase_memory_usage(desired - current); } else { self.linear_memory_limit_hit = true; } if let Ok(allowed) = res { if !allowed { self.linear_memory_limit_hit = true; } } res } fn table_growing( &mut self, current: usize, desired: usize, maximum: Option<usize>, ) -> wasmtime::Result<bool> { self.inner.table_growing(current, desired, maximum) } fn memory_grow_failed(&mut self, error: wasmtime::Error) -> wasmtime::Result<()> { self.linear_memory_limit_hit = true; self.inner.memory_grow_failed(error) } fn table_grow_failed(&mut self, error: wasmtime::Error) -> wasmtime::Result<()> { self.inner.table_grow_failed(error) } fn instances(&self) -> usize { self.inner.instances() } fn tables(&self) -> usize { self.inner.tables() } fn memories(&self) -> usize { self.inner.memories() } } impl WasiView for StoreData { fn ctx(&mut self) -> WasiCtxView<'_> { let ctx = self .wasi .as_mut() .expect("Should have WASI context defined if using WASI p2"); let table = &mut self.resource_table; WasiCtxView { ctx, table } } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/convert.rs
ext/src/ruby_api/convert.rs
use crate::{define_rb_intern, err, error, helpers::SymbolEnum}; use lazy_static::lazy_static; use magnus::{ prelude::*, try_convert, Error, IntoValue, RArray, Ruby, Symbol, TryConvert, TypedData, Value, }; use wasmtime::{ExternRef, RefType, Val, ValType}; use super::{ func::{Func, FuncType}, global::{Global, GlobalType}, memory::{Memory, MemoryType}, store::StoreContextValue, table::{Table, TableType}, }; define_rb_intern!( I32 => "i32", I64 => "i64", F32 => "f32", F64 => "f64", V128 => "v128", FUNCREF => "funcref", EXTERNREF => "externref", ); lazy_static! { static ref VALTYPE_MAPPING: SymbolEnum<'static, ValType> = { let mapping = vec![ (*I32, ValType::I32), (*I64, ValType::I64), (*F32, ValType::F32), (*F64, ValType::F64), (*V128, ValType::V128), (*FUNCREF, ValType::FUNCREF), (*EXTERNREF, ValType::EXTERNREF), ]; SymbolEnum::new("WebAssembly type", mapping) }; } pub trait ToRubyValue { fn to_ruby_value(&self, ruby: &Ruby, store: &StoreContextValue) -> Result<Value, Error>; } impl ToRubyValue for Val { fn to_ruby_value(&self, ruby: &Ruby, store: &StoreContextValue) -> Result<Value, Error> { match self { Val::I32(i) => Ok(i.into_value_with(ruby)), Val::I64(i) => Ok(i.into_value_with(ruby)), Val::F32(f) => Ok(f32::from_bits(*f).into_value_with(ruby)), Val::F64(f) => Ok(f64::from_bits(*f).into_value_with(ruby)), Val::ExternRef(eref) => match eref { None => Ok(().into_value_with(ruby)), Some(eref) => { let inner = eref.data(store.context()?).map_err(|e| error!("{e}"))?; match inner { Some(v) => v .downcast_ref::<ExternRefValue>() .map(|v| v.0) .ok_or_else(|| error!("failed to extract externref")), None => Ok(().into_value_with(ruby)), } } }, Val::FuncRef(funcref) => match funcref { None => Ok(().into_value_with(ruby)), Some(funcref) => Ok(Func::from_inner(*store, *funcref).into_value_with(ruby)), }, Val::V128(_) => err!("converting from v128 to Ruby unsupported"), t => err!("cannot convert value: {t:?} to Ruby value"), } } } pub trait ToWasmVal { fn to_wasm_val(&self, store: &StoreContextValue, ty: ValType) -> Result<Val, Error>; } impl ToWasmVal for Value { fn to_wasm_val(&self, store: &StoreContextValue, ty: ValType) -> Result<Val, Error> { if ty.matches(&ValType::EXTERNREF) { // Don't special case `nil` in order to ensure that it's always // a rooted value. Even though it's `nil` from Ruby's perspective, // it's a host managed object. let extern_ref_value = Some( ExternRef::new( store.context_mut().map_err(|e| error!("{e}"))?, ExternRefValue::from(*self), ) .map_err(|e| error!("{e}"))?, ); return Ok(Val::ExternRef(extern_ref_value)); } if ty.matches(&ValType::FUNCREF) { let func_ref_value = match self.is_nil() { true => None, false => Some(*<&Func>::try_convert(*self)?.inner()), }; return Ok(Val::FuncRef(func_ref_value)); } match ty { ValType::I32 => Ok(i32::try_convert(*self)?.into()), ValType::I64 => Ok(i64::try_convert(*self)?.into()), ValType::F32 => Ok(f32::try_convert(*self)?.into()), ValType::F64 => Ok(f64::try_convert(*self)?.into()), ValType::V128 => err!("converting from Ruby to v128 not supported"), // TODO: to be filled in once typed function references and/or GC // are enabled by default. t => err!("unsupported type: {t:?}"), } } } struct ExternRefValue(Value); impl From<Value> for ExternRefValue { fn from(v: Value) -> Self { Self(v) } } unsafe impl Send for ExternRefValue {} unsafe impl Sync for ExternRefValue {} pub trait ToExtern { fn to_extern(&self, ruby: &Ruby) -> Result<wasmtime::Extern, Error>; } impl ToExtern for Value { fn to_extern(&self, ruby: &Ruby) -> Result<wasmtime::Extern, Error> { if self.is_kind_of(Func::class(ruby)) { Ok(<&Func>::try_convert(*self)?.into()) } else if self.is_kind_of(Memory::class(ruby)) { Ok(<&Memory>::try_convert(*self)?.into()) } else if self.is_kind_of(Table::class(ruby)) { Ok(<&Table>::try_convert(*self)?.into()) } else if self.is_kind_of(Global::class(ruby)) { Ok(<&Global>::try_convert(*self)?.into()) } else { Err(Error::new( ruby.exception_type_error(), format!("unexpected extern: {}", self.inspect()), )) } } } pub trait ToSym { fn to_sym(&self) -> Result<Symbol, Error>; } impl ToSym for ValType { fn to_sym(&self) -> Result<Symbol, Error> { if self.matches(&ValType::EXTERNREF) { return Ok(Symbol::from(*EXTERNREF)); } if self.matches(&ValType::FUNCREF) { return Ok(Symbol::from(*FUNCREF)); } match self { &ValType::I32 => Ok(Symbol::from(*I32)), &ValType::I64 => Ok(Symbol::from(*I64)), &ValType::F32 => Ok(Symbol::from(*F32)), &ValType::F64 => Ok(Symbol::from(*F64)), &ValType::V128 => Ok(Symbol::from(*V128)), t => Err(error!("Unsupported type {t:?}")), } } } impl ToSym for RefType { fn to_sym(&self) -> Result<Symbol, Error> { if self.matches(&RefType::FUNCREF) { return Ok(Symbol::from(*FUNCREF)); } if self.matches(&RefType::EXTERNREF) { return Ok(Symbol::from(*EXTERNREF)); } Err(error!("Unsupported RefType {self:}")) } } pub trait ToValType { fn to_val_type(&self) -> Result<ValType, Error>; } impl ToValType for Value { fn to_val_type(&self) -> Result<ValType, Error> { VALTYPE_MAPPING.get(*self) } } impl ToValType for Symbol { fn to_val_type(&self) -> Result<ValType, Error> { self.as_value().to_val_type() } } pub trait ToValTypeVec { fn to_val_type_vec(&self) -> Result<Vec<ValType>, Error>; } impl ToValTypeVec for RArray { fn to_val_type_vec(&self) -> Result<Vec<ValType>, Error> { unsafe { self.as_slice() } .iter() .map(ToValType::to_val_type) .collect::<Result<Vec<ValType>, Error>>() } } pub trait WrapWasmtimeType<'a, T> where T: TypedData, { fn wrap_wasmtime_type(&self, ruby: &Ruby, store: StoreContextValue<'a>) -> Result<T, Error>; } pub trait WrapWasmtimeExternType<T> where T: TypedData, { fn wrap_wasmtime_type(&self, ruby: &Ruby) -> Result<T, Error>; }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/caller.rs
ext/src/ruby_api/caller.rs
use super::{convert::WrapWasmtimeType, externals::Extern, root, store::StoreData}; use crate::error; use magnus::{class, method, typed_data::Obj, Error, Module as _, RString, Ruby, Value}; use std::cell::UnsafeCell; use wasmtime::{AsContext, AsContextMut, Caller as CallerImpl, StoreContext, StoreContextMut}; /// A handle to a [`wasmtime::Caller`] that's only valid during a Func execution. /// [`UnsafeCell`] wraps the wasmtime::Caller because the Value's lifetime can't /// be tied to the Caller: the Value is handed back to Ruby and we can't control /// whether the user keeps a handle to it or not. #[derive(Debug)] pub struct CallerHandle<'a> { caller: UnsafeCell<Option<CallerImpl<'a, StoreData>>>, } impl<'a> CallerHandle<'a> { pub fn new(caller: CallerImpl<'a, StoreData>) -> Self { Self { caller: UnsafeCell::new(Some(caller)), } } // Note that the underlying implemenation relies on `UnsafeCell`, which // provides some gurantees around interior mutability, therefore we're // opting to allow this lint. #[allow(clippy::mut_from_ref)] pub fn get_mut(&self) -> Result<&mut CallerImpl<'a, StoreData>, Error> { unsafe { &mut *self.caller.get() } .as_mut() .ok_or_else(|| error!("Caller outlived its Func execution")) } pub fn get(&self) -> Result<&CallerImpl<'a, StoreData>, Error> { unsafe { (*self.caller.get()).as_ref() } .ok_or_else(|| error!("Caller outlived its Func execution")) } pub fn expire(&self) { unsafe { *self.caller.get() = None } } } /// @yard /// @rename Wasmtime::Caller /// Represents the Caller's context within a Func execution. An instance of /// Caller is sent as the first parameter to Func's implementation (the /// block argument in {Func.new}). /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Caller.html Wasmtime's Rust doc #[derive(Debug)] #[magnus::wrap(class = "Wasmtime::Caller", free_immediately, unsafe_generics)] pub struct Caller<'a> { handle: CallerHandle<'a>, } impl<'a> Caller<'a> { pub fn new(caller: CallerImpl<'a, StoreData>) -> Self { Self { handle: CallerHandle::new(caller), } } /// @yard /// Returns the store's data. Akin to {Store#data}. /// @return [Object] The store's data (the object passed to {Store.new}). pub fn store_data(&self) -> Result<Value, Error> { self.context().map(|ctx| ctx.data().user_data()) } /// @yard /// @def export(name) /// @see Instance#export pub fn export( ruby: &Ruby, rb_self: Obj<Caller<'a>>, name: RString, ) -> Result<Option<Extern<'a>>, Error> { let inner = rb_self.handle.get_mut()?; if let Some(export) = inner.get_export(unsafe { name.as_str() }?) { export.wrap_wasmtime_type(ruby, rb_self.into()).map(Some) } else { Ok(None) } } /// @yard /// (see Store#get_fuel) /// @def get_fuel pub fn get_fuel(&self) -> Result<u64, Error> { self.handle .get() .map(|c| c.get_fuel())? .map_err(|e| error!("{}", e)) } /// @yard /// (see Store#set_fuel) /// @def set_fuel(fuel) pub fn set_fuel(&self, fuel: u64) -> Result<(), Error> { self.handle .get_mut() .and_then(|c| c.set_fuel(fuel).map_err(|e| error!("{}", e)))?; Ok(()) } pub fn context(&self) -> Result<StoreContext<'_, StoreData>, Error> { self.handle.get().map(|c| c.as_context()) } pub fn context_mut(&self) -> Result<StoreContextMut<'_, StoreData>, Error> { self.handle.get_mut().map(|c| c.as_context_mut()) } pub fn expire(&self) { self.handle.expire(); } } unsafe impl Send for Caller<'_> {} pub fn init(ruby: &Ruby) -> Result<(), Error> { let klass = root().define_class("Caller", ruby.class_object())?; klass.define_method("store_data", method!(Caller::store_data, 0))?; klass.define_method("export", method!(Caller::export, 1))?; klass.define_method("get_fuel", method!(Caller::get_fuel, 0))?; klass.define_method("set_fuel", method!(Caller::set_fuel, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/module.rs
ext/src/ruby_api/module.rs
use std::{ mem::{transmute, MaybeUninit}, ops::Deref, os::raw::c_void, }; use super::{ convert::{WrapWasmtimeExternType, WrapWasmtimeType}, engine::Engine, root, }; use crate::{ error, helpers::{nogvl, Tmplock}, }; use magnus::{ class, function, method, rb_sys::AsRawValue, typed_data::Obj, Error, Module as _, Object, RArray, RHash, RString, Ruby, }; use rb_sys::{ rb_str_locktmp, rb_str_unlocktmp, tracking_allocator::ManuallyTracked, RSTRING_LEN, RSTRING_PTR, }; use wasmtime::{ImportType, Module as ModuleImpl}; /// @yard /// Represents a WebAssembly module. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Module.html Wasmtime's Rust doc #[derive(Clone)] #[magnus::wrap(class = "Wasmtime::Module", size, free_immediately, frozen_shareable)] pub struct Module { inner: ModuleImpl, _track_memory_usage: ManuallyTracked<()>, } // Needed for ManuallyTracked unsafe impl Send for Module {} impl Module { /// @yard /// @def new(engine, wat_or_wasm) /// @param engine [Wasmtime::Engine] /// @param wat_or_wasm [String] The String of WAT or Wasm. /// @return [Wasmtime::Module] pub fn new(engine: &Engine, wat_or_wasm: RString) -> Result<Self, Error> { let eng = engine.get(); let (locked_slice, _locked_slice_guard) = wat_or_wasm.as_locked_slice()?; let module = nogvl(|| ModuleImpl::new(eng, locked_slice)) .map_err(|e| error!("Could not build module: {}", e))?; Ok(module.into()) } /// @yard /// @def from_file(engine, path) /// @param engine [Wasmtime::Engine] /// @param path [String] /// @return [Wasmtime::Module] pub fn from_file(engine: &Engine, path: RString) -> Result<Self, Error> { let eng = engine.get(); let (path, _locked_str_guard) = path.as_locked_str()?; // SAFETY: this string is immediately copied and never moved off the stack let module = nogvl(|| ModuleImpl::from_file(eng, path)) .map_err(|e| error!("Could not build module from file: {}", e))?; Ok(module.into()) } /// @yard /// Instantiates a serialized module coming from either {#serialize} or {Wasmtime::Engine#precompile_module}. /// /// The engine serializing and the engine deserializing must: /// * have the same configuration /// * be of the same gem version /// /// @def deserialize(engine, compiled) /// @param engine [Wasmtime::Engine] /// @param compiled [String] String obtained with either {Wasmtime::Engine#precompile_module} or {#serialize}. /// @return [Wasmtime::Module] pub fn deserialize(engine: &Engine, compiled: RString) -> Result<Self, Error> { // SAFETY: this string is immediately copied and never moved off the stack unsafe { ModuleImpl::deserialize(engine.get(), compiled.as_slice()) } .map(Into::into) .map_err(|e| error!("Could not deserialize module: {}", e)) } /// @yard /// Instantiates a serialized module from a file. /// /// @def deserialize_file(engine, path) /// @param engine [Wasmtime::Engine] /// @param path [String] /// @return [Wasmtime::Module] /// @see .deserialize pub fn deserialize_file(engine: &Engine, path: RString) -> Result<Self, Error> { unsafe { ModuleImpl::deserialize_file(engine.get(), path.as_str()?) } .map(Into::into) .map_err(|e| error!("Could not deserialize module from file: {}", e)) } /// @yard /// Serialize the module. /// @return [String] /// @see .deserialize pub fn serialize(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RString, Error> { let module = rb_self.get(); let bytes = module.serialize(); bytes .map(|bytes| ruby.str_from_slice(&bytes)) .map_err(|e| error!("{:?}", e)) } pub fn get(&self) -> &ModuleImpl { &self.inner } /// @yard /// Returns the list of imports that this Module has and must be satisfied. /// @return [Array<Hash>] An array of hashes containing import information pub fn imports(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RArray, Error> { let module = rb_self.get(); let imports = module.imports(); let result = ruby.ary_new_capa(imports.len()); for import in imports { let hash = ruby.hash_new(); hash.aset("module", import.module())?; hash.aset("name", import.name())?; hash.aset("type", import.ty().wrap_wasmtime_type(ruby)?)?; result.push(hash)?; } Ok(result) } } impl From<ModuleImpl> for Module { fn from(inner: ModuleImpl) -> Self { let range = inner.image_range(); let start = range.start; let end = range.end; let size = if end > start { unsafe { end.offset_from(start) } } else { // This is mostly a safety mechanism; this should never happen if // things are correctly configured. 0 }; Self { inner, _track_memory_usage: ManuallyTracked::new(size as usize), } } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("Module", ruby.class_object())?; class.define_singleton_method("new", function!(Module::new, 2))?; class.define_singleton_method("from_file", function!(Module::from_file, 2))?; class.define_singleton_method("deserialize", function!(Module::deserialize, 2))?; class.define_singleton_method("deserialize_file", function!(Module::deserialize_file, 2))?; class.define_method("serialize", method!(Module::serialize, 0))?; class.define_method("imports", method!(Module::imports, 0))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/params.rs
ext/src/ruby_api/params.rs
use super::{convert::ToWasmVal, errors::ExceptionMessage, store::StoreContextValue}; use magnus::{error::ErrorType, Error, Ruby, Value}; use static_assertions::assert_eq_size; use wasmtime::{FuncType, ValType}; #[derive(Debug, Clone)] #[repr(C)] struct Param { val: Value, index: u32, ty: ValType, } impl Param { pub fn new(index: u32, ty: ValType, val: Value) -> Self { Self { index, ty, val } } fn to_wasmtime_val(&self, store: &StoreContextValue) -> Result<wasmtime::Val, Error> { self.val .to_wasm_val(store, self.ty.clone()) .map_err(|error| error.append(format!(" (param at index {})", self.index))) } } pub struct Params<'a>(&'a FuncType, &'a [Value]); impl<'a> Params<'a> { pub fn new(ruby: &Ruby, ty: &'a FuncType, params_slice: &'a [Value]) -> Result<Self, Error> { if ty.params().len() != params_slice.len() { return Err(Error::new( ruby.exception_arg_error(), format!( "wrong number of arguments (given {}, expected {})", params_slice.len(), ty.params().len() ), )); } Ok(Self(ty, params_slice)) } pub fn to_vec( &self, ruby: &Ruby, store: &StoreContextValue, ) -> Result<Vec<wasmtime::Val>, Error> { let mut vals = Vec::with_capacity(self.0.params().len()); for (i, (param, value)) in self.0.params().zip(self.1.iter()).enumerate() { let i: u32 = i .try_into() .map_err(|_| Error::new(ruby.exception_arg_error(), "too many params"))?; let param = Param::new(i, param, *value); vals.push(param.to_wasmtime_val(store)?); } Ok(vals) } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/externals.rs
ext/src/ruby_api/externals.rs
use super::{ convert::{WrapWasmtimeExternType, WrapWasmtimeType}, func::{Func, FuncType}, global::{Global, GlobalType}, memory::{Memory, MemoryType}, root, store::StoreContextValue, table::{Table, TableType}, }; use crate::{conversion_err, not_implemented}; use magnus::{ class, gc::Marker, method, prelude::*, rb_sys::AsRawValue, typed_data::Obj, DataTypeFunctions, Error, Module, RClass, Ruby, TypedData, Value, }; #[derive(TypedData)] #[magnus( class = "Wasmtime::ExternType", size, mark, free_immediately, unsafe_generics )] pub enum ExternType { Func(Obj<FuncType>), Global(Obj<GlobalType>), Memory(Obj<MemoryType>), Table(Obj<TableType>), } impl DataTypeFunctions for ExternType { fn mark(&self, marker: &Marker) { match self { ExternType::Func(f) => marker.mark(*f), ExternType::Global(g) => marker.mark(*g), ExternType::Memory(m) => marker.mark(*m), ExternType::Table(t) => marker.mark(*t), } } } unsafe impl Send for ExternType {} impl ExternType { /// @yard /// Returns the exported function's FuncType or raises a `{ConversionError}` when the export is not a /// function. /// @return [FuncType] The exported function's type. pub fn to_func_type(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { ExternType::Func(f) => Ok(f.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Func::class(ruby)), } } /// @yard /// Returns the exported global's GlobalType or raises a `{ConversionError}` when the export is not a global. /// @return [GlobalType] The exported global's type. pub fn to_global_type(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { ExternType::Global(g) => Ok(g.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Global::class(ruby)), } } /// @yard /// Returns the exported memory's MemoryType or raises a `{ConversionError}` when the export is not a /// memory. /// @return [MemoryType] The exported memory's type. pub fn to_memory_type(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { ExternType::Memory(m) => Ok(m.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Memory::class(ruby)), } } /// @yard /// Returns the exported table's TableType or raises a `{ConversionError}` when the export is not a table. /// @return [TableType] The exported table's type. pub fn to_table_type(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { ExternType::Table(t) => Ok(t.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Table::class(ruby)), } } fn inner_class(rb_self: Obj<Self>) -> RClass { match *rb_self { ExternType::Func(f) => f.class(), ExternType::Global(g) => g.class(), ExternType::Memory(m) => m.class(), ExternType::Table(t) => t.class(), } } } /// @yard /// @rename Wasmtime::Extern /// An external item to a WebAssembly module, or a list of what can possibly be exported from a Wasm module. /// @see https://docs.rs/wasmtime/latest/wasmtime/enum.Extern.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus( class = "Wasmtime::Extern", size, mark, free_immediately, unsafe_generics )] pub enum Extern<'a> { Func(Obj<Func<'a>>), Global(Obj<Global<'a>>), Memory(Obj<Memory<'a>>), Table(Obj<Table<'a>>), } impl DataTypeFunctions for Extern<'_> { fn mark(&self, marker: &Marker) { match self { Extern::Func(f) => marker.mark(*f), Extern::Global(g) => marker.mark(*g), Extern::Memory(m) => marker.mark(*m), Extern::Table(t) => marker.mark(*t), } } } unsafe impl Send for Extern<'_> {} impl Extern<'_> { /// @yard /// Returns the exported function or raises a `{ConversionError}` when the export is not a /// function. /// @return [Func] The exported function. pub fn to_func(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { Extern::Func(f) => Ok(f.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Func::class(ruby)), } } /// @yard /// Returns the exported global or raises a `{ConversionError}` when the export is not a global. /// @return [Global] The exported global. pub fn to_global(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { Extern::Global(g) => Ok(g.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Global::class(ruby)), } } /// @yard /// Returns the exported memory or raises a `{ConversionError}` when the export is not a /// memory. /// @return [Memory] The exported memory. pub fn to_memory(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { Extern::Memory(m) => Ok(m.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Memory::class(ruby)), } } /// @yard /// Returns the exported table or raises a `{ConversionError}` when the export is not a table. /// @return [Table] The exported table. pub fn to_table(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { match *rb_self { Extern::Table(t) => Ok(t.as_value()), _ => conversion_err!(Self::inner_class(rb_self), Table::class(ruby)), } } pub fn inspect(rb_self: Obj<Self>) -> Result<String, Error> { let inner_string: String = match *rb_self { Extern::Func(f) => f.inspect(), Extern::Global(g) => g.inspect(), Extern::Memory(m) => m.inspect(), Extern::Table(t) => t.inspect(), }; Ok(format!( "#<Wasmtime::Extern:0x{:016x} @value={}>", rb_self.as_raw(), inner_string )) } fn inner_class(rb_self: Obj<Self>) -> RClass { match *rb_self { Extern::Func(f) => f.class(), Extern::Global(g) => g.class(), Extern::Memory(m) => m.class(), Extern::Table(t) => t.class(), } } } impl<'a> WrapWasmtimeType<'a, Extern<'a>> for wasmtime::Extern { fn wrap_wasmtime_type( &self, ruby: &Ruby, store: StoreContextValue<'a>, ) -> Result<Extern<'a>, Error> { match self { wasmtime::Extern::Func(func) => { Ok(Extern::Func(ruby.obj_wrap(Func::from_inner(store, *func)))) } wasmtime::Extern::Global(global) => Ok(Extern::Global( ruby.obj_wrap(Global::from_inner(store, *global)), )), wasmtime::Extern::Memory(mem) => Ok(Extern::Memory( ruby.obj_wrap(Memory::from_inner(store, *mem)?), )), wasmtime::Extern::Table(table) => Ok(Extern::Table( ruby.obj_wrap(Table::from_inner(store, *table)), )), wasmtime::Extern::SharedMemory(_) => { not_implemented!(ruby, "shared memory not supported") } wasmtime::Extern::Tag(_) => { not_implemented!(ruby, "exception handling not yet implemented") } } } } impl WrapWasmtimeExternType<ExternType> for wasmtime::ExternType { fn wrap_wasmtime_type(&self, ruby: &Ruby) -> Result<ExternType, Error> { match self { wasmtime::ExternType::Func(ft) => Ok(ExternType::Func( ruby.obj_wrap(FuncType::from_inner(ft.clone())), )), wasmtime::ExternType::Global(gt) => Ok(ExternType::Global( ruby.obj_wrap(GlobalType::from_inner(gt.clone())), )), wasmtime::ExternType::Memory(mt) => Ok(ExternType::Memory( ruby.obj_wrap(MemoryType::from_inner(mt.clone())), )), wasmtime::ExternType::Table(tt) => Ok(ExternType::Table( ruby.obj_wrap(TableType::from_inner(tt.clone())), )), wasmtime::ExternType::Tag(_) => { not_implemented!(ruby, "exception handling not yet implemented") } } } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let extern_type = root().define_class("ExternType", ruby.class_object())?; extern_type.define_method("to_func_type", method!(ExternType::to_func_type, 0))?; extern_type.define_method("to_global_type", method!(ExternType::to_global_type, 0))?; extern_type.define_method("to_memory_type", method!(ExternType::to_memory_type, 0))?; extern_type.define_method("to_table_type", method!(ExternType::to_table_type, 0))?; let class = root().define_class("Extern", ruby.class_object())?; class.define_method("to_func", method!(Extern::to_func, 0))?; class.define_method("to_global", method!(Extern::to_global, 0))?; class.define_method("to_memory", method!(Extern::to_memory, 0))?; class.define_method("to_table", method!(Extern::to_table, 0))?; class.define_method("inspect", method!(Extern::inspect, 0))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/memory.rs
ext/src/ruby_api/memory.rs
mod unsafe_slice; use self::unsafe_slice::UnsafeSlice; use super::{ root, store::{Store, StoreContextValue}, }; use crate::{define_rb_intern, error}; use magnus::{ class, function, gc::Marker, method, r_string::RString, scan_args, typed_data::Obj, DataTypeFunctions, Error, Module as _, Object, Ruby, TypedData, Value, }; use rb_sys::tracking_allocator::ManuallyTracked; use wasmtime::{Extern, Memory as MemoryImpl}; const WASM_PAGE_SIZE: u32 = wasmtime_environ::Memory::DEFAULT_PAGE_SIZE; define_rb_intern!( MIN_SIZE => "min_size", MAX_SIZE => "max_size", ); #[derive(TypedData)] #[magnus( class = "Wasmtime::MemoryType", free_immediately, mark, unsafe_generics )] pub struct MemoryType { inner: wasmtime::MemoryType, } impl DataTypeFunctions for MemoryType { fn mark(&self, _marker: &Marker) {} } impl MemoryType { pub fn from_inner(inner: wasmtime::MemoryType) -> Self { Self { inner } } /// @yard /// @return [Integer] The minimum number of memory pages. pub fn min_size(&self) -> u64 { self.inner.minimum() } /// @yard /// @return [Integer, nil] The maximum number of memory pages. pub fn max_size(&self) -> Option<u64> { self.inner.maximum() } } impl From<&MemoryType> for wasmtime::ExternType { fn from(memory_type: &MemoryType) -> Self { Self::Memory(memory_type.inner.clone()) } } /// @yard /// @rename Wasmtime::Memory /// Represents a WebAssembly memory. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Memory.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus(class = "Wasmtime::Memory", free_immediately, mark, unsafe_generics)] pub struct Memory<'a> { store: StoreContextValue<'a>, inner: ManuallyTracked<MemoryImpl>, } impl DataTypeFunctions for Memory<'_> { fn mark(&self, marker: &Marker) { self.store.mark(marker) } } unsafe impl Send for Memory<'_> {} impl<'a> Memory<'a> { /// @yard /// @def new(store, min_size:, max_size: nil) /// @param store [Store] /// @param min_size [Integer] The minimum memory pages. /// @param max_size [Integer, nil] The maximum memory pages. pub fn new(args: &[Value]) -> Result<Self, Error> { let args = scan_args::scan_args::<(Obj<Store>,), (), (), (), _, ()>(args)?; let kw = scan_args::get_kwargs::<_, (u32,), (Option<u32>,), ()>( args.keywords, &[*MIN_SIZE], &[*MAX_SIZE], )?; let (store,) = args.required; let (min,) = kw.required; let (max,) = kw.optional; let memtype = wasmtime::MemoryType::new(min, max); let inner = MemoryImpl::new(store.context_mut(), memtype).map_err(|e| error!("{}", e))?; let memsize = inner.data_size(store.context_mut()); Ok(Self { store: store.into(), inner: ManuallyTracked::wrap(inner, memsize), }) } pub fn from_inner(store: StoreContextValue<'a>, inner: MemoryImpl) -> Result<Self, Error> { let memsize = inner.data_size(store.context()?); Ok(Self { store, inner: ManuallyTracked::wrap(inner, memsize), }) } /// @yard /// @return [Integer] The minimum number of memory pages. pub fn min_size(&self) -> Result<u64, Error> { Ok(self .get_wasmtime_memory() .ty(self.store.context()?) .minimum()) } /// @yard /// @return [Integer, nil] The maximum number of memory pages. pub fn max_size(&self) -> Result<Option<u64>, Error> { Ok(self .get_wasmtime_memory() .ty(self.store.context()?) .maximum()) } /// @yard /// Read +size+ bytes starting at +offset+. Result is a ASCII-8BIT encoded string. /// /// @def read(offset, size) /// @param offset [Integer] /// @param size [Integer] /// @return [String] Binary +String+ of the memory. pub fn read( ruby: &Ruby, rb_self: Obj<Self>, offset: usize, size: usize, ) -> Result<RString, Error> { rb_self .get_wasmtime_memory() .data(rb_self.store.context()?) .get(offset..) .and_then(|s| s.get(..size)) .map(|s| ruby.str_from_slice(s)) .ok_or_else(|| error!("out of bounds memory access")) } /// @yard /// Read +size+ bytes starting at +offset+. Result is a UTF-8 encoded string. /// /// @def read_utf8(offset, size) /// @param offset [Integer] /// @param size [Integer] /// @return [String] UTF-8 +String+ of the memory. pub fn read_utf8( ruby: &Ruby, rb_self: Obj<Self>, offset: usize, size: usize, ) -> Result<RString, Error> { rb_self .get_wasmtime_memory() .data(rb_self.store.context()?) .get(offset..) .and_then(|s| s.get(..size)) .ok_or_else(|| error!("out of bounds memory access")) .and_then(|s| std::str::from_utf8(s).map_err(|e| error!("{}", e))) .map(|s| ruby.str_new(s)) } /// @yard /// Read +size+ bytes starting at +offset+ into an {UnsafeSlice}. This /// provides a way to read a slice of memory without copying the underlying /// data. /// /// The returned {UnsafeSlice} lazily reads the underlying memory, meaning that /// the actual pointer to the string buffer is not materialzed until /// {UnsafeSlice#to_str} is called. /// /// SAFETY: Resizing the memory (as with {Wasmtime::Memory#grow}) will /// invalidate the {UnsafeSlice}, and future attempts to read the slice will raise /// an error. However, it is not possible to invalidate the Ruby +String+ /// object after calling {Memory::UnsafeSlice#to_str}. As such, the caller must ensure /// that the Wasmtime {Memory} is not resized while holding the Ruby string. /// Failing to do so could result in the +String+ buffer pointing to invalid /// memory. /// /// In general, you should prefer using {Memory#read} or {Memory#read_utf8} /// over this method unless you know what you're doing. /// /// @def read_unsafe_slice(offset, size) /// @param offset [Integer] /// @param size [Integer] /// @return [Wasmtime::Memory::UnsafeSlice] Slice of the memory. pub fn read_unsafe_slice( ruby: &Ruby, rb_self: Obj<Self>, offset: usize, size: usize, ) -> Result<Obj<UnsafeSlice<'a>>, Error> { Ok(ruby.obj_wrap(UnsafeSlice::new(rb_self, offset..(offset + size))?)) } /// @yard /// Write +value+ starting at +offset+. /// /// @def write(offset, value) /// @param offset [Integer] /// @param value [String] /// @return [void] pub fn write(&self, offset: usize, value: RString) -> Result<(), Error> { let slice = unsafe { value.as_slice() }; self.get_wasmtime_memory() .write(self.store.context_mut()?, offset, slice) .map_err(|e| error!("{}", e)) } /// @yard /// Grows a memory by +delta+ pages. /// Raises if the memory grows beyond its limit. /// /// @def grow(delta) /// @param delta [Integer] The number of pages to grow by. /// @return [Integer] The number of pages the memory had before being resized. pub fn grow(&self, delta: usize) -> Result<u64, Error> { let ret = self .get_wasmtime_memory() .grow(self.store.context_mut()?, delta as _) .map_err(|e| error!("{}", e)); self.inner .increase_memory_usage(delta * (WASM_PAGE_SIZE as usize)); ret } /// @yard /// @return [Integer] The number of pages of the memory. pub fn size(&self) -> Result<u64, Error> { Ok(self.get_wasmtime_memory().size(self.store.context()?)) } /// @yard /// @return [Integer] The number of bytes of the memory. pub fn data_size(&self) -> Result<usize, Error> { Ok(self.get_wasmtime_memory().data_size(self.store.context()?)) } pub fn get_wasmtime_memory(&self) -> &MemoryImpl { self.inner.get() } fn data(&self) -> Result<&[u8], Error> { Ok(self.get_wasmtime_memory().data(self.store.context()?)) } } impl From<&Memory<'_>> for Extern { fn from(memory: &Memory) -> Self { Self::Memory(*memory.get_wasmtime_memory()) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let type_class = root().define_class("MemoryType", ruby.class_object())?; type_class.define_method("min_size", method!(MemoryType::min_size, 0))?; type_class.define_method("max_size", method!(MemoryType::max_size, 0))?; let class = root().define_class("Memory", ruby.class_object())?; class.define_singleton_method("new", function!(Memory::new, -1))?; class.define_method("min_size", method!(Memory::min_size, 0))?; class.define_method("max_size", method!(Memory::max_size, 0))?; class.define_method("read", method!(Memory::read, 2))?; class.define_method("read_utf8", method!(Memory::read_utf8, 2))?; class.define_method("write", method!(Memory::write, 2))?; class.define_method("grow", method!(Memory::grow, 1))?; class.define_method("size", method!(Memory::size, 0))?; class.define_method("data_size", method!(Memory::data_size, 0))?; class.define_method("read_unsafe_slice", method!(Memory::read_unsafe_slice, 2))?; unsafe_slice::init(ruby)?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/table.rs
ext/src/ruby_api/table.rs
use super::{ convert::{ToRubyValue, ToSym, ToValType, ToWasmVal}, root, store::{Store, StoreContextValue}, }; use crate::{define_rb_intern, error}; use magnus::{ class, function, gc::Marker, method, prelude::*, scan_args, typed_data::Obj, DataTypeFunctions, Error, IntoValue, Object, Ruby, Symbol, TypedData, Value, }; use wasmtime::{Extern, Table as TableImpl, Val}; define_rb_intern!( MIN_SIZE => "min_size", MAX_SIZE => "max_size", ); #[derive(TypedData)] #[magnus(class = "Wasmtime::TableType", free_immediately, mark, unsafe_generics)] pub struct TableType { inner: wasmtime::TableType, } impl DataTypeFunctions for TableType { fn mark(&self, _marker: &Marker) {} } impl TableType { pub fn from_inner(inner: wasmtime::TableType) -> Self { Self { inner } } /// @yard /// @def type /// @return [Symbol] The Wasm type of the elements of this table. pub fn type_(&self) -> Result<Symbol, Error> { self.inner.element().to_sym() } /// @yard /// @return [Integer] The minimum size of this table. pub fn min_size(&self) -> u64 { self.inner.minimum() } /// @yard /// @return [Integer, nil] The maximum size of this table. pub fn max_size(&self) -> Option<u64> { self.inner.maximum() } } impl From<&TableType> for wasmtime::ExternType { fn from(table_type: &TableType) -> Self { Self::Table(table_type.inner.clone()) } } /// @yard /// @rename Wasmtime::Table /// Represents a WebAssembly table. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Table.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus(class = "Wasmtime::Table", free_immediately, mark, unsafe_generics)] pub struct Table<'a> { store: StoreContextValue<'a>, inner: TableImpl, } impl DataTypeFunctions for Table<'_> { fn mark(&self, marker: &Marker) { self.store.mark(marker) } } impl<'a> Table<'a> { /// @yard /// @def new(store, type, initial, min_size:, max_size: nil) /// @param store [Store] /// @param type [Symbol] The WebAssembly type of the value held by this table. /// @param initial [Value] The initial value of values in the table. /// @param min_size [Integer] The minimum number of elements in the table. /// @param max_size [Integer, nil] The maximum number of elements in the table. pub fn new(args: &[Value]) -> Result<Self, Error> { let args = scan_args::scan_args::<(Obj<Store>, Symbol, Value), (), (), (), _, ()>(args)?; let kw = scan_args::get_kwargs::<_, (u32,), (Option<u32>,), ()>( args.keywords, &[*MIN_SIZE], &[*MAX_SIZE], )?; let (store, value_type, default) = args.required; let (min,) = kw.required; let (max,) = kw.optional; let wasm_type = value_type.to_val_type()?; let wasm_default = default.to_wasm_val(&store.into(), wasm_type.clone())?; let ref_ = wasm_default .ref_() .ok_or_else(|| error!("Expected Ref for table value"))?; let table_type = wasm_type .as_ref() .ok_or_else(|| error!("Expected RefType"))? .clone(); let inner = TableImpl::new( store.context_mut(), wasmtime::TableType::new(table_type, min, max), ref_, ) .map_err(|e| error!("{}", e))?; let table = Self { store: store.into(), inner, }; table.retain_non_nil_extern_ref(default)?; Ok(table) } pub fn from_inner(store: StoreContextValue<'a>, inner: TableImpl) -> Self { Self { store, inner } } /// @yard /// @def type /// @return [Symbol] The Wasm type of the elements of this table. pub fn type_(&self) -> Result<Symbol, Error> { self.ty()?.element().to_sym() } /// @yard /// @return [Integer] The minimum size of this table. pub fn min_size(&self) -> Result<u64, Error> { self.ty().map(|ty| ty.minimum()) } /// @yard /// @return [Integer, nil] The maximum size of this table. pub fn max_size(&self) -> Result<Option<u64>, Error> { self.ty().map(|ty| ty.maximum()) } /// @yard /// Returns the table element value at +index+, or +nil+ if index is out of bound. /// /// @def get(index) /// @param index [Integer] /// @return [Object, nil] pub fn get(ruby: &Ruby, rb_self: Obj<Self>, index: u64) -> Result<Value, Error> { match rb_self.inner.get(rb_self.store.context_mut()?, index) { Some(wasm_val) => Val::from(wasm_val).to_ruby_value(ruby, &rb_self.store), None => Ok(().into_value_with(ruby)), } } /// @yard /// Sets the table entry at +index+ to +value+. /// /// @def set(index, value) /// @param index [Integer] /// @param value [Object] /// @return [void] pub fn set(&self, index: u64, value: Value) -> Result<(), Error> { self.inner .set( self.store.context_mut()?, index, value .to_wasm_val(&self.store, wasmtime::ValType::from(self.value_type()?))? .ref_() .ok_or_else(|| error!("Expected Ref"))?, ) .map_err(|e| error!("{}", e)) .and_then(|result| { self.retain_non_nil_extern_ref(value)?; Ok(result) }) } /// @yard /// Grows the size of this table by +delta+. /// Raises if the table grows beyond its limit. /// /// @def grow(delta, initial) /// @param delta [Integer] The number of elements to add to the table. /// @param initial [Object] The initial value for newly added table slots. /// @return [void] pub fn grow(&self, delta: u64, initial: Value) -> Result<u64, Error> { self.inner .grow( self.store.context_mut()?, delta, initial .to_wasm_val(&self.store, wasmtime::ValType::from(self.value_type()?))? .ref_() .ok_or_else(|| error!("Expected Ref"))?, ) .map_err(|e| error!("{}", e)) .and_then(|result| { self.retain_non_nil_extern_ref(initial)?; Ok(result) }) } /// @yard /// @return [Integer] The size of the table. pub fn size(&self) -> Result<u64, Error> { Ok(self.inner.size(self.store.context()?)) } fn ty(&self) -> Result<wasmtime::TableType, Error> { Ok(self.inner.ty(self.store.context()?)) } fn value_type(&self) -> Result<wasmtime::RefType, Error> { let table_type = self.inner.ty(self.store.context()?); let el = table_type.element(); Ok(el.clone()) } fn retain_non_nil_extern_ref(&self, value: Value) -> Result<(), Error> { if !value.is_nil() && self.value_type()?.matches(&wasmtime::RefType::EXTERNREF) { self.store.retain(value)?; } Ok(()) } pub fn inner(&self) -> TableImpl { self.inner } } impl From<&Table<'_>> for Extern { fn from(table: &Table) -> Self { Self::Table(table.inner()) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let type_class = root().define_class("TableType", ruby.class_object())?; type_class.define_method("type", method!(TableType::type_, 0))?; type_class.define_method("min_size", method!(TableType::min_size, 0))?; type_class.define_method("max_size", method!(TableType::max_size, 0))?; let class = root().define_class("Table", ruby.class_object())?; class.define_singleton_method("new", function!(Table::new, -1))?; class.define_method("type", method!(Table::type_, 0))?; class.define_method("min_size", method!(Table::min_size, 0))?; class.define_method("max_size", method!(Table::max_size, 0))?; class.define_method("get", method!(Table::get, 1))?; class.define_method("set", method!(Table::set, 2))?; class.define_method("grow", method!(Table::grow, 2))?; class.define_method("size", method!(Table::size, 0))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/trap.rs
ext/src/ruby_api/trap.rs
use std::convert::TryFrom; use crate::ruby_api::{errors::base_error, root}; use magnus::Error; use magnus::{ method, prelude::*, rb_sys::AsRawValue, typed_data::Obj, value::Lazy, DataTypeFunctions, ExceptionClass, IntoValue, Ruby, Symbol, TypedData, }; pub fn trap_error() -> ExceptionClass { static ERR: Lazy<ExceptionClass> = Lazy::new(|_| root().define_error("Trap", base_error()).unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ERR) } macro_rules! trap_const { ($trap:ident) => { trap_error().const_get(stringify!($trap)).map(Some) }; } #[derive(TypedData, Debug)] #[magnus(class = "Wasmtime::Trap", size, free_immediately)] /// @yard pub struct Trap { trap: wasmtime::Trap, wasm_backtrace: Option<wasmtime::WasmBacktrace>, } impl DataTypeFunctions for Trap {} impl Trap { pub fn new(trap: wasmtime::Trap, wasm_backtrace: Option<wasmtime::WasmBacktrace>) -> Self { Self { trap, wasm_backtrace, } } /// @yard /// Returns a textual description of the trap error, for example: /// wasm trap: wasm `unreachable` instruction executed /// @return [String] pub fn message(&self) -> String { self.trap.to_string() } /// @yard /// Returns a textual representation of the Wasm backtrce, if it exists. /// For example: /// error while executing at wasm backtrace: /// 0: 0x1a - <unknown>!<wasm function 0> /// @return [String, nil] pub fn wasm_backtrace_message(&self) -> Option<String> { self.wasm_backtrace.as_ref().map(|bt| format!("{bt}")) } /// @yard /// Returns the trap code as a Symbol, possibly nil if the trap did not /// origin from Wasm code. All possible trap codes are defined as constants on {Trap}. /// @return [Symbol, nil] pub fn code(&self) -> Result<Option<Symbol>, Error> { match self.trap { wasmtime::Trap::StackOverflow => trap_const!(STACK_OVERFLOW), wasmtime::Trap::MemoryOutOfBounds => trap_const!(MEMORY_OUT_OF_BOUNDS), wasmtime::Trap::HeapMisaligned => trap_const!(HEAP_MISALIGNED), wasmtime::Trap::TableOutOfBounds => trap_const!(TABLE_OUT_OF_BOUNDS), wasmtime::Trap::IndirectCallToNull => trap_const!(INDIRECT_CALL_TO_NULL), wasmtime::Trap::BadSignature => trap_const!(BAD_SIGNATURE), wasmtime::Trap::IntegerOverflow => trap_const!(INTEGER_OVERFLOW), wasmtime::Trap::IntegerDivisionByZero => trap_const!(INTEGER_DIVISION_BY_ZERO), wasmtime::Trap::BadConversionToInteger => trap_const!(BAD_CONVERSION_TO_INTEGER), wasmtime::Trap::UnreachableCodeReached => trap_const!(UNREACHABLE_CODE_REACHED), wasmtime::Trap::Interrupt => trap_const!(INTERRUPT), wasmtime::Trap::AlwaysTrapAdapter => trap_const!(ALWAYS_TRAP_ADAPTER), wasmtime::Trap::OutOfFuel => trap_const!(OUT_OF_FUEL), // When adding a trap code here, define a matching constant on Wasmtime::Trap (in Ruby) _ => trap_const!(UNKNOWN), } } pub fn inspect(ruby: &Ruby, rb_self: Obj<Self>) -> Result<String, Error> { Ok(format!( "#<Wasmtime::Trap:0x{:016x} @trap_code={}>", rb_self.as_raw(), rb_self.code()?.into_value_with(ruby).inspect() )) } pub fn into_error(self, ruby: &Ruby) -> Error { magnus::Exception::from_value(ruby.obj_wrap(self).as_value()) .unwrap() // Can't fail: Wasmtime::Trap is an Exception .into() } } impl TryFrom<wasmtime::Error> for Trap { type Error = wasmtime::Error; fn try_from(value: wasmtime::Error) -> Result<Self, Self::Error> { match value.downcast_ref::<wasmtime::Trap>() { Some(trap) => { let trap = trap.to_owned(); let bt = value.downcast::<wasmtime::WasmBacktrace>(); Ok(Trap::new(trap, bt.map(Some).unwrap_or(None))) } None => Err(value), } } } pub fn init() -> Result<(), Error> { let class = trap_error(); class.define_method("message", method!(Trap::message, 0))?; class.define_method( "wasm_backtrace_message", method!(Trap::wasm_backtrace_message, 0), )?; class.define_method("code", method!(Trap::code, 0))?; class.define_method("inspect", method!(Trap::inspect, 0))?; class.define_alias("to_s", "message")?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/mod.rs
ext/src/ruby_api/mod.rs
#![allow(rustdoc::broken_intra_doc_links)] #![allow(rustdoc::invalid_html_tags)] #![allow(rustdoc::bare_urls)] #![allow(rustdoc::invalid_rust_codeblocks)] // The `pub use` imports below need to be publicly exposed when the ruby_api // feature is enabled, else they must be publicly exposed to the crate only // (`pub(crate) use`). Allowing unused imports is easier and less repetitive. // Also the feature is already correctly gated in lib.rs. #![allow(unused_imports)] use magnus::{function, value::Lazy, Error, RModule, RString, Ruby}; mod caller; mod component; mod config; mod convert; mod engine; mod errors; mod externals; mod func; mod global; mod instance; mod linker; mod memory; mod module; mod params; mod pooling_allocation_config; mod store; mod table; mod trap; mod wasi; mod wasi_config; pub use caller::Caller; pub use engine::Engine; pub use func::Func; pub use instance::Instance; pub use linker::Linker; pub use memory::Memory; pub use module::Module; pub use params::Params; pub use pooling_allocation_config::PoolingAllocationConfig; pub use store::Store; pub use trap::Trap; pub use wasi_config::WasiConfig; /// The "Wasmtime" Ruby module. pub fn root() -> RModule { static ROOT: Lazy<RModule> = Lazy::new(|ruby| ruby.define_module("Wasmtime").unwrap()); let ruby = Ruby::get().unwrap(); ruby.get_inner(&ROOT) } // This Struct is a placeholder for documentation, so that we can hang methods // to it and have yard-rustdoc discover them. /// @yard /// @module pub struct Wasmtime; impl Wasmtime { /// @yard /// Converts a WAT +String+ into Wasm. /// @param wat [String] /// @def wat2wasm(wat) /// @return [String] The Wasm represented as a binary +String+. pub fn wat2wasm(ruby: &Ruby, wat: RString) -> Result<RString, Error> { wat::parse_str(unsafe { wat.as_str()? }) .map(|bytes| ruby.str_from_slice(bytes.as_slice())) .map_err(|e| crate::error!("{}", e)) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let wasmtime = root(); wasmtime.define_module_function("wat2wasm", function!(Wasmtime::wat2wasm, 1))?; errors::init()?; trap::init()?; engine::init(ruby)?; module::init(ruby)?; store::init(ruby)?; instance::init(ruby)?; func::init(ruby)?; caller::init(ruby)?; memory::init(ruby)?; linker::init(ruby)?; externals::init(ruby)?; wasi::init(ruby)?; wasi_config::init(ruby)?; table::init(ruby)?; global::init(ruby)?; pooling_allocation_config::init(ruby)?; component::init(ruby)?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/linker.rs
ext/src/ruby_api/linker.rs
use super::{ convert::WrapWasmtimeType, convert::{ToExtern, ToValTypeVec}, engine::Engine, externals::Extern, func::{self, Func}, instance::Instance, module::Module, root, store::{Store, StoreContextValue, StoreData}, }; use crate::{err, error, ruby_api::errors}; use magnus::{ block::Proc, class, function, gc::Marker, method, prelude::*, scan_args, scan_args::scan_args, typed_data::Obj, DataTypeFunctions, Error, Object, RArray, RHash, RString, Ruby, TypedData, Value, }; use std::cell::RefCell; use wasmtime::Linker as LinkerImpl; /// @yard /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Linker.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus(class = "Wasmtime::Linker", size, mark, free_immediately)] pub struct Linker { inner: RefCell<LinkerImpl<StoreData>>, refs: RefCell<Vec<Value>>, has_wasi: RefCell<bool>, } unsafe impl Send for Linker {} impl DataTypeFunctions for Linker { fn mark(&self, marker: &Marker) { marker.mark_slice(self.refs.borrow().as_slice()); } } impl Linker { /// @yard /// @def new(engine) /// @param engine [Engine] /// @return [Linker] pub fn new(engine: &Engine) -> Result<Self, Error> { let inner: LinkerImpl<StoreData> = LinkerImpl::new(engine.get()); Ok(Self { inner: RefCell::new(inner), refs: Default::default(), has_wasi: RefCell::new(false), }) } /// @yard /// Allow shadowing. /// @def allow_shadowing=(val) /// @param val [Boolean] pub fn set_allow_shadowing(&self, val: bool) { self.inner.borrow_mut().allow_shadowing(val); } /// @yard /// Allow unknown exports. /// @def allow_unknown_exports=(val) /// @param val [Boolean] pub fn set_allow_unknown_exports(&self, val: bool) { self.inner.borrow_mut().allow_unknown_exports(val); } /// @yard /// Define unknown (unresolved) imports as functions which trap. /// @def define_unknown_imports_as_traps(mod) /// @param mod [Module] /// @return [void] pub fn define_unknown_imports_as_traps(&self, module: &Module) -> Result<(), Error> { self.inner .borrow_mut() .define_unknown_imports_as_traps(module.get()) .map_err(|e| error!("{}", e)) } /// @yard /// Define an item in this linker. /// @def define(store, mod, name, item) /// @param store [Store] /// @param mod [String] Module name /// @param name [String] Import name /// @param item [Func, Memory] The item to define. /// @return [void] pub fn define( ruby: &Ruby, rb_self: &Self, store: &Store, module: RString, name: RString, item: Value, ) -> Result<(), Error> { let item = item.to_extern(ruby)?; rb_self .inner .borrow_mut() .define( store.context(), unsafe { module.as_str()? }, unsafe { name.as_str()? }, item, ) .map(|_| ()) .map_err(|e| error!("{}", e)) } /// @yard /// Define a function in this linker. /// /// @see Wasmtime::Func.new /// /// @def func_new(mod, name, params, results, &block) /// @param mod [String] Module name /// @param name [String] Import name /// @param params [Array<Symbol>] The function's parameters. /// @param results [Array<Symbol>] The function's results. /// @param block [Block] See {Func.new} for block argument details. /// @return [void] /// @see Func.new pub fn func_new(&self, args: &[Value]) -> Result<(), Error> { let args = scan_args::<(RString, RString, RArray, RArray), (), (), (), RHash, Proc>(args)?; let (module, name, params, results) = args.required; let callable = args.block; let mut inner_mut = self.inner.borrow_mut(); let engine = inner_mut.engine(); let ty = wasmtime::FuncType::new( engine, params.to_val_type_vec()?, results.to_val_type_vec()?, ); let func_closure = func::make_func_closure(&ty, callable.into()); self.refs.borrow_mut().push(callable.as_value()); inner_mut .func_new( unsafe { module.as_str() }?, unsafe { name.as_str() }?, ty, func_closure, ) .map_err(|e| error!("{}", e)) .map(|_| ()) } /// @yard /// Looks up a previously defined item in this linker. /// /// @def get(store, mod, name) /// @param store [Store] /// @param mod [String] Module name /// @param name [String] Import name /// @return [Extern, nil] The item if it exists, nil otherwise. pub fn get( &self, store: Obj<Store>, module: RString, name: RString, ) -> Result<Option<Extern<'_>>, Error> { let ext = self.inner .borrow() .get(store.context_mut(), unsafe { module.as_str() }?, unsafe { name.as_str()? }); let ruby = Ruby::get_with(store); match ext { None => Ok(None), Some(ext) => ext.wrap_wasmtime_type(&ruby, store.into()).map(Some), } } /// @yard /// Defines an entire {Instance} in this linker. /// /// @def instance(store, mod, instance) /// @param store [Store] /// @param mod [String] Module name /// @param instance [Instance] /// @return [void] pub fn instance( &self, store: &Store, module: RString, instance: &Instance, ) -> Result<(), Error> { self.inner .borrow_mut() .instance( store.context_mut(), unsafe { module.as_str() }?, instance.get(), ) .map_err(|e| error!("{}", e)) .map(|_| ()) } /// @yard /// Defines automatic instantiation of a {Module} in this linker. /// /// @def module(store, name, mod) /// @param store [Store] /// @param name [String] Module name /// @param mod [Module] /// @return [void] pub fn module(&self, store: &Store, name: RString, module: &Module) -> Result<(), Error> { self.inner .borrow_mut() .module(store.context_mut(), unsafe { name.as_str()? }, module.get()) .map(|_| ()) .map_err(|e| error!("{}", e)) } /// @yard /// Aliases one item’s name as another. /// /// @def alias(mod, name, as_mod, as_name) /// @param mod [String] The source module name. /// @param name [String] The source item name. /// @param as_mod [String] The destination module name. /// @param as_name [String] The destination item name. /// @return [void] pub fn alias( &self, module: RString, name: RString, as_module: RString, as_name: RString, ) -> Result<(), Error> { self.inner .borrow_mut() .alias( unsafe { module.as_str() }?, unsafe { name.as_str() }?, unsafe { as_module.as_str() }?, unsafe { as_name.as_str() }?, ) .map_err(|e| error!("{}", e)) .map(|_| ()) } /// @yard /// Aliases one module’s name as another. /// /// @def alias(mod, as_mod) /// @param mod [String] Source module name /// @param as_mod [String] Destination module name /// @return [void] pub fn alias_module(&self, module: RString, as_module: RString) -> Result<(), Error> { self.inner .borrow_mut() .alias_module(unsafe { module.as_str() }?, unsafe { as_module.as_str() }?) .map_err(|e| error!("{}", e)) .map(|_| ()) } /// @yard /// Instantiates a {Module} in a {Store} using the defined imports in the linker. /// @def instantiate(store, mod) /// @param store [Store] /// @param mod [Module] /// @return [Instance] pub fn instantiate( ruby: &Ruby, rb_self: Obj<Self>, store: Obj<Store>, module: &Module, ) -> Result<Instance, Error> { if *rb_self.has_wasi.borrow() && !store.context().data().has_wasi_p1_ctx() { return err!("{}", errors::missing_wasi_p1_ctx_error()); } rb_self .inner .borrow_mut() .instantiate(store.context_mut(), module.get()) .map_err(|e| StoreContextValue::from(store).handle_wasm_error(ruby, e)) .map(|instance| { rb_self .refs .borrow() .iter() .for_each(|val| store.retain(*val)); Instance::from_inner(store, instance) }) } /// @yard /// Returns the “default export” of a module. /// @def get_default(store, mod) /// @param store [Store] /// @param mod [String] Module name /// @return [Func] pub fn get_default(&self, store: Obj<Store>, module: RString) -> Result<Func<'_>, Error> { self.inner .borrow() .get_default(store.context_mut(), unsafe { module.as_str() }?) .map(|func| Func::from_inner(store.into(), func)) .map_err(|e| error!("{}", e)) } /// @yard /// Replaces the `poll_oneoff` and `sched_yield` function implementations /// with deterministic ones. /// @return [void] pub fn use_deterministic_scheduling_functions(&self) -> Result<(), Error> { let mut inner = self.inner.borrow_mut(); deterministic_wasi_ctx::replace_scheduling_functions(&mut inner).map_err(|e| error!("{e}")) } pub(crate) fn add_wasi_p1(&self) -> Result<(), Error> { *self.has_wasi.borrow_mut() = true; let mut inner = self.inner.borrow_mut(); wasmtime_wasi::p1::add_to_linker_sync(&mut inner, |s| s.wasi_p1_ctx_mut()) .map_err(|e| error!("{e}")) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("Linker", ruby.class_object())?; class.define_singleton_method("new", function!(Linker::new, 1))?; class.define_method("allow_shadowing=", method!(Linker::set_allow_shadowing, 1))?; class.define_method( "allow_unknown_exports=", method!(Linker::set_allow_unknown_exports, 1), )?; class.define_method( "define_unknown_imports_as_traps", method!(Linker::define_unknown_imports_as_traps, 1), )?; class.define_method("define", method!(Linker::define, 4))?; class.define_method("func_new", method!(Linker::func_new, -1))?; class.define_method("get", method!(Linker::get, 3))?; class.define_method("instance", method!(Linker::instance, 3))?; class.define_method("module", method!(Linker::module, 3))?; class.define_method("alias", method!(Linker::alias, 4))?; class.define_method("alias_module", method!(Linker::alias_module, 2))?; class.define_method("instantiate", method!(Linker::instantiate, 2))?; class.define_method("get_default", method!(Linker::get_default, 2))?; class.define_method( "use_deterministic_scheduling_functions", method!(Linker::use_deterministic_scheduling_functions, 0), )?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/wasi_config.rs
ext/src/ruby_api/wasi_config.rs
use super::root; use crate::error; use crate::helpers::OutputLimitedBuffer; use crate::ruby_api::convert::ToValType; use crate::{define_rb_intern, helpers::SymbolEnum}; use lazy_static::lazy_static; use magnus::{ class, function, gc::Marker, method, typed_data::Obj, value::Opaque, DataTypeFunctions, Error, IntoValue, Module, Object, RArray, RHash, RString, Ruby, Symbol, TryConvert, TypedData, Value, }; use rb_sys::ruby_rarray_flags::RARRAY_EMBED_FLAG; use std::cell::RefCell; use std::convert::TryFrom; use std::fs; use std::path::Path; use std::{fs::File, path::PathBuf}; use wasmtime_wasi::cli::{InputFile, OutputFile}; use wasmtime_wasi::p1::WasiP1Ctx; use wasmtime_wasi::p2::pipe::MemoryInputPipe; use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder}; define_rb_intern!( READ => "read", WRITE => "write", MUTATE => "mutate", ALL => "all", ); lazy_static! { static ref FILE_PERMS_MAPPING: SymbolEnum<'static, FilePerms> = { let mapping = vec![ (*READ, FilePerms::READ), (*WRITE, FilePerms::WRITE), (*ALL, FilePerms::all()), ]; SymbolEnum::new(":file_perms", mapping) }; static ref DIR_PERMS_MAPPING: SymbolEnum<'static, DirPerms> = { let mapping = vec![ (*READ, DirPerms::READ), (*MUTATE, DirPerms::MUTATE), (*ALL, DirPerms::all()), ]; SymbolEnum::new(":dir_perms", mapping) }; } enum ReadStream { Inherit, Path(Opaque<RString>), String(Opaque<RString>), } impl ReadStream { pub fn mark(&self, marker: &Marker) { match self { Self::Inherit => (), Self::Path(s) => marker.mark(*s), Self::String(s) => marker.mark(*s), } } } enum WriteStream { Inherit, Path(Opaque<RString>), Buffer(Opaque<RString>, usize), } impl WriteStream { pub fn mark(&self, marker: &Marker) { match self { Self::Inherit => (), Self::Path(v) => marker.mark(*v), Self::Buffer(v, _) => marker.mark(*v), } } } struct PermsSymbolEnum(Symbol); #[derive(Clone)] struct MappedDirectory { host_path: Opaque<RString>, guest_path: Opaque<RString>, dir_perms: Opaque<Symbol>, file_perms: Opaque<Symbol>, } impl MappedDirectory { pub fn mark(&self, marker: &Marker) { marker.mark(self.host_path); marker.mark(self.guest_path); marker.mark(self.dir_perms); marker.mark(self.file_perms); } } #[derive(Default)] struct WasiConfigInner { stdin: Option<ReadStream>, stdout: Option<WriteStream>, stderr: Option<WriteStream>, env: Option<Opaque<RHash>>, args: Option<Opaque<RArray>>, deterministic: bool, mapped_directories: Vec<MappedDirectory>, } impl WasiConfigInner { pub fn mark(&self, marker: &Marker) { if let Some(v) = self.stdin.as_ref() { v.mark(marker); } if let Some(v) = self.stdout.as_ref() { v.mark(marker); } if let Some(v) = self.stderr.as_ref() { v.mark(marker); } if let Some(v) = self.env.as_ref() { marker.mark(*v); } if let Some(v) = self.args.as_ref() { marker.mark(*v); } for v in &self.mapped_directories { v.mark(marker); } } } impl TryFrom<PermsSymbolEnum> for DirPerms { type Error = magnus::Error; fn try_from(value: PermsSymbolEnum) -> Result<Self, Error> { let ruby = Ruby::get_with(value.0); DIR_PERMS_MAPPING.get(value.0.into_value_with(&ruby)) } } impl TryFrom<PermsSymbolEnum> for FilePerms { type Error = magnus::Error; fn try_from(value: PermsSymbolEnum) -> Result<Self, Error> { let ruby = Ruby::get_with(value.0); FILE_PERMS_MAPPING.get(value.0.into_value_with(&ruby)) } } /// @yard /// WASI config to be sent as {Store#new}’s +wasi_config+ keyword argument. /// /// Instance methods mutate the current object and return +self+. /// // #[derive(Debug)] #[derive(Default, TypedData)] #[magnus(class = "Wasmtime::WasiConfig", size, mark, free_immediately)] pub struct WasiConfig { inner: RefCell<WasiConfigInner>, } impl DataTypeFunctions for WasiConfig { fn mark(&self, marker: &Marker) { self.inner.borrow().mark(marker); } } type RbSelf = Obj<WasiConfig>; impl WasiConfig { /// @yard /// Create a new {WasiConfig}. By default, it has nothing: no stdin/out/err, /// no env, no argv, no file access. /// @return [WasiConfig] pub fn new() -> Self { Self::default() } /// @yard /// Use deterministic implementations for clocks and random methods. /// @return [WasiConfig] +self+ pub fn add_determinism(rb_self: RbSelf) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.deterministic = true; rb_self } /// @yard /// Inherit stdin from the current Ruby process. /// @return [WasiConfig] +self+ pub fn inherit_stdin(rb_self: RbSelf) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdin = Some(ReadStream::Inherit); rb_self } /// @yard /// Set stdin to read from the specified file. /// @param path [String] The path of the file to read from. /// @def set_stdin_file(path) /// @return [WasiConfig] +self+ pub fn set_stdin_file(rb_self: RbSelf, path: RString) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdin = Some(ReadStream::Path(path.into())); rb_self } /// @yard /// Set stdin to the specified String. /// @param content [String] /// @def set_stdin_string(content) /// @return [WasiConfig] +self+ pub fn set_stdin_string(rb_self: RbSelf, content: RString) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdin = Some(ReadStream::String(content.into())); rb_self } /// @yard /// Inherit stdout from the current Ruby process. /// @return [WasiConfig] +self+ pub fn inherit_stdout(rb_self: RbSelf) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdout = Some(WriteStream::Inherit); rb_self } /// @yard /// Set stdout to write to a file. Will truncate the file if it exists, /// otherwise try to create it. /// @param path [String] The path of the file to write to. /// @def set_stdout_file(path) /// @return [WasiConfig] +self+ pub fn set_stdout_file(rb_self: RbSelf, path: RString) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdout = Some(WriteStream::Path(path.into())); rb_self } /// @yard /// Set stdout to write to a string buffer. /// If the string buffer is frozen, Wasm execution will raise a Wasmtime::Error error. /// No encoding checks are done on the resulting string, it is the caller's responsibility to ensure the string contains a valid encoding /// @param buffer [String] The string buffer to write to. /// @param capacity [Integer] The maximum number of bytes that can be written to the output buffer. /// @def set_stdout_buffer(buffer, capacity) /// @return [WasiConfig] +self+ pub fn set_stdout_buffer(rb_self: RbSelf, buffer: RString, capacity: usize) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stdout = Some(WriteStream::Buffer(buffer.into(), capacity)); rb_self } /// @yard /// Inherit stderr from the current Ruby process. /// @return [WasiConfig] +self+ pub fn inherit_stderr(rb_self: RbSelf) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stderr = Some(WriteStream::Inherit); rb_self } /// @yard /// Set stderr to write to a file. Will truncate the file if it exists, /// otherwise try to create it. /// @param path [String] The path of the file to write to. /// @def set_stderr_file(path) /// @return [WasiConfig] +self+ pub fn set_stderr_file(rb_self: RbSelf, path: RString) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stderr = Some(WriteStream::Path(path.into())); rb_self } /// @yard /// Set stderr to write to a string buffer. /// If the string buffer is frozen, Wasm execution will raise a Wasmtime::Error error. /// No encoding checks are done on the resulting string, it is the caller's responsibility to ensure the string contains a valid encoding /// @param buffer [String] The string buffer to write to. /// @param capacity [Integer] The maximum number of bytes that can be written to the output buffer. /// @def set_stderr_buffer(buffer, capacity) /// @return [WasiConfig] +self+ pub fn set_stderr_buffer(rb_self: RbSelf, buffer: RString, capacity: usize) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.stderr = Some(WriteStream::Buffer(buffer.into(), capacity)); rb_self } /// @yard /// Set env to the specified +Hash+. /// @param env [Hash<String, String>] /// @def set_env(env) /// @return [WasiConfig] +self+ pub fn set_env(rb_self: RbSelf, env: RHash) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.env = Some(env.into()); rb_self } /// @yard /// Set the arguments (argv) to the specified +Array+. /// @param args [Array<String>] /// @def set_argv(args) /// @return [WasiConfig] +self+ pub fn set_argv(rb_self: RbSelf, argv: RArray) -> RbSelf { let mut inner = rb_self.inner.borrow_mut(); inner.args = Some(argv.into()); rb_self } /// @yard /// Set mapped directory for host path and guest path. /// @param host_path [String] /// @param guest_path [String] /// @param dir_perms [Symbol] Directory permissions, one of :read, :mutate, or :all /// @param file_perms [Symbol] File permissions, one of :read, :write, or :all /// @def set_mapped_directory(host_path, guest_path, dir_perms, file_perms) /// @return [WasiConfig] +self+ pub fn set_mapped_directory( rb_self: RbSelf, host_path: RString, guest_path: RString, dir_perms: Symbol, file_perms: Symbol, ) -> RbSelf { let mapped_dir = MappedDirectory { host_path: host_path.into(), guest_path: guest_path.into(), dir_perms: dir_perms.into(), file_perms: file_perms.into(), }; let mut inner = rb_self.inner.borrow_mut(); inner.mapped_directories.push(mapped_dir); rb_self } pub fn build_p1(&self, ruby: &Ruby) -> Result<WasiP1Ctx, Error> { let mut builder = self.build_impl(ruby)?; let ctx = builder.build_p1(); Ok(ctx) } pub fn build(&self, ruby: &Ruby) -> Result<WasiCtx, Error> { let mut builder = self.build_impl(ruby)?; let ctx = builder.build(); Ok(ctx) } fn build_impl(&self, ruby: &Ruby) -> Result<WasiCtxBuilder, Error> { let mut builder = WasiCtxBuilder::new(); let inner = self.inner.borrow(); if let Some(stdin) = inner.stdin.as_ref() { match stdin { ReadStream::Inherit => builder.inherit_stdin(), ReadStream::Path(path) => { builder.stdin(file_r(ruby.get_inner(*path)).map(InputFile::new)?) } ReadStream::String(input) => { // SAFETY: &[u8] copied before calling in to Ruby, no GC can happen before. let inner = ruby.get_inner(*input); builder.stdin(MemoryInputPipe::new(unsafe { inner.as_slice() }.to_vec())) } }; } if let Some(stdout) = inner.stdout.as_ref() { match stdout { WriteStream::Inherit => builder.inherit_stdout(), WriteStream::Path(path) => { builder.stdout(file_w(ruby.get_inner(*path)).map(OutputFile::new)?) } WriteStream::Buffer(buffer, capacity) => { builder.stdout(OutputLimitedBuffer::new(*buffer, *capacity)) } }; } if let Some(stderr) = inner.stderr.as_ref() { match stderr { WriteStream::Inherit => builder.inherit_stderr(), WriteStream::Path(path) => { builder.stderr(file_w(ruby.get_inner(*path)).map(OutputFile::new)?) } WriteStream::Buffer(buffer, capacity) => { builder.stderr(OutputLimitedBuffer::new(*buffer, *capacity)) } }; } if let Some(args) = inner.args.as_ref() { // SAFETY: no gc can happen nor do we write to `args`. for item in unsafe { ruby.get_inner(*args).as_slice() } { let arg = RString::try_convert(*item)?; // SAFETY: &str copied before calling in to Ruby, no GC can happen before. let arg = unsafe { arg.as_str() }?; builder.arg(arg); } } if let Some(env_hash) = inner.env.as_ref() { let env_vec: Vec<(String, String)> = ruby.get_inner(*env_hash).to_vec()?; builder.envs(&env_vec); } if inner.deterministic { deterministic_wasi_ctx::add_determinism_to_wasi_ctx_builder(&mut builder); } for mapped_dir in &inner.mapped_directories { let host_path = ruby.get_inner(mapped_dir.host_path).to_string()?; let guest_path = ruby.get_inner(mapped_dir.guest_path).to_string()?; let dir_perms = ruby.get_inner(mapped_dir.dir_perms); let file_perms = ruby.get_inner(mapped_dir.file_perms); builder .preopened_dir( Path::new(&host_path), &guest_path, PermsSymbolEnum(dir_perms).try_into()?, PermsSymbolEnum(file_perms).try_into()?, ) .map_err(|e| error!("{}", e))?; } Ok(builder) } } pub fn file_r(path: RString) -> Result<File, Error> { // SAFETY: &str copied before calling in to Ruby, no GC can happen before. File::open(unsafe { path.as_str()? }).map_err(|e| error!("Failed to open file {}\n{}", path, e)) } pub fn file_w(path: RString) -> Result<File, Error> { // SAFETY: &str copied before calling in to Ruby, no GC can happen before. File::create(unsafe { path.as_str()? }) .map_err(|e| error!("Failed to write to file {}\n{}", path, e)) } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("WasiConfig", ruby.class_object())?; class.define_singleton_method("new", function!(WasiConfig::new, 0))?; class.define_method("add_determinism", method!(WasiConfig::add_determinism, 0))?; class.define_method("inherit_stdin", method!(WasiConfig::inherit_stdin, 0))?; class.define_method("set_stdin_file", method!(WasiConfig::set_stdin_file, 1))?; class.define_method("set_stdin_string", method!(WasiConfig::set_stdin_string, 1))?; class.define_method("inherit_stdout", method!(WasiConfig::inherit_stdout, 0))?; class.define_method("set_stdout_file", method!(WasiConfig::set_stdout_file, 1))?; class.define_method( "set_stdout_buffer", method!(WasiConfig::set_stdout_buffer, 2), )?; class.define_method("inherit_stderr", method!(WasiConfig::inherit_stderr, 0))?; class.define_method("set_stderr_file", method!(WasiConfig::set_stderr_file, 1))?; class.define_method( "set_stderr_buffer", method!(WasiConfig::set_stderr_buffer, 2), )?; class.define_method("set_env", method!(WasiConfig::set_env, 1))?; class.define_method("set_argv", method!(WasiConfig::set_argv, 1))?; class.define_method( "set_mapped_directory", method!(WasiConfig::set_mapped_directory, 4), )?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/pooling_allocation_config.rs
ext/src/ruby_api/pooling_allocation_config.rs
use lazy_static::lazy_static; use std::cell::RefCell; use magnus::{ class, function, method, rb_sys::AsRawValue, typed_data::Obj, value::ReprValue, Error, Module, Object as _, Ruby, Value, }; use rb_sys::{ruby_special_consts::RUBY_Qtrue, VALUE}; use wasmtime::{Enabled, PoolingAllocationConfig as PoolingAllocationConfigImpl}; use crate::{define_rb_intern, err, helpers::SymbolEnum, root}; /// @yard /// Configuration options used with an engines `allocation_strategy` to change /// the behavior of the pooling instance allocator. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.PoolingAllocationConfig.html Wasmtime's Rust doc #[derive(Clone)] #[magnus::wrap(class = "Wasmtime::PoolingAllocationConfig", size, free_immediately)] pub struct PoolingAllocationConfig { inner: RefCell<PoolingAllocationConfigImpl>, } impl PoolingAllocationConfig { /// @yard /// @def new /// @return [Wasmtime::PoolingAllocationConfig] pub fn new(ruby: &Ruby) -> Result<Obj<Self>, Error> { let obj = ruby.obj_wrap(Self::from(PoolingAllocationConfigImpl::default())); if ruby.block_given() { let _: Value = ruby.block_proc()?.call((obj,))?; } Ok(obj) } /// @yard /// @def total_memories=(total_memories) /// @param total_memories [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_total_memories(rb_self: Obj<Self>, total_memories: u32) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.total_memories(total_memories); Ok(rb_self) } /// @yard /// @def total_tables=(total_tables) /// @param total_tables [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_total_tables(rb_self: Obj<Self>, total_tables: u32) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.total_tables(total_tables); Ok(rb_self) } /// @yard /// @def max_memories_per_module=(max_memories) /// @param max_memories [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_memories_per_module( rb_self: Obj<Self>, max_memories: u32, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_memories_per_module(max_memories); Ok(rb_self) } /// @yard /// @def max_tables_per_module=(max_tables) /// @param max_tables [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_tables_per_component( rb_self: Obj<Self>, max_tables: u32, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_tables_per_component(max_tables); Ok(rb_self) } /// @yard /// @def memory_protection_keys_available? /// @return [Boolean] pub fn are_memory_protection_keys_available() -> Result<bool, Error> { Ok(wasmtime::PoolingAllocationConfig::are_memory_protection_keys_available()) } /// @yard /// @def async_stack_keep_resident=(amount) /// @param amount [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_async_stack_keep_resident( rb_self: Obj<Self>, amt: usize, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.async_stack_keep_resident(amt); Ok(rb_self) } /// @def linear_memory_keep_resident= /// @param size [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_linear_memory_keep_resident( rb_self: Obj<Self>, size: usize, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.linear_memory_keep_resident(size); Ok(rb_self) } /// @def max_component_instance_size= /// @param size [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_component_instance_size( rb_self: Obj<Self>, size: usize, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_component_instance_size(size); Ok(rb_self) } /// @def max_core_instance_size= /// @param size [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_core_instance_size(rb_self: Obj<Self>, size: usize) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_core_instance_size(size); Ok(rb_self) } /// @def max_memories_per_component= /// @param max_memories [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_memories_per_component( rb_self: Obj<Self>, max_memories: u32, ) -> Result<Obj<Self>, Error> { rb_self .borrow_mut()? .max_memories_per_component(max_memories); Ok(rb_self) } /// @def max_memory_protection_keys= /// @param max_keys [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_memory_protection_keys( rb_self: Obj<Self>, max_keys: usize, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_memory_protection_keys(max_keys); Ok(rb_self) } /// @def max_unused_warm_slots= /// @param max_slots [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_unused_warm_slots( rb_self: Obj<Self>, max_slots: u32, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_unused_warm_slots(max_slots); Ok(rb_self) } /// @def max_memory_size= /// @param bytes [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_max_memory_size(rb_self: Obj<Self>, bytes: usize) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.max_memory_size(bytes); Ok(rb_self) } /// @def memory_protection_keys= /// @param keys [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_memory_protection_keys( rb_self: Obj<Self>, strategy: Value, ) -> Result<Obj<Self>, Error> { let val = MPK_MAPPING.get(strategy)?; rb_self.borrow_mut()?.memory_protection_keys(val); Ok(rb_self) } /// @def table_elements= /// @param elements [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_table_elements(rb_self: Obj<Self>, elements: usize) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.table_elements(elements); Ok(rb_self) } /// @def table_keep_resident= /// @param size [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_table_keep_resident(rb_self: Obj<Self>, size: usize) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.table_keep_resident(size); Ok(rb_self) } /// @def total_component_instances= /// @param instances [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_total_component_instances( rb_self: Obj<Self>, instances: u32, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.total_component_instances(instances); Ok(rb_self) } /// @def total_core_instances= /// @param instances [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_total_core_instances( rb_self: Obj<Self>, instances: u32, ) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.total_core_instances(instances); Ok(rb_self) } /// @def total_stacks= /// @param stacks [Integer] /// @return [Wasmtime::PoolingAllocationConfig] pub fn set_total_stacks(rb_self: Obj<Self>, stacks: u32) -> Result<Obj<Self>, Error> { rb_self.borrow_mut()?.total_stacks(stacks); Ok(rb_self) } pub fn inspect(rb_self: Obj<Self>) -> Result<String, Error> { let inner = format!("{:?}", rb_self.borrow_mut()?); Ok(format!( "#<Wasmtime::PoolingAllocationConfig inner={inner}>" )) } fn borrow_mut(&self) -> Result<std::cell::RefMut<'_, PoolingAllocationConfigImpl>, Error> { if let Ok(inner) = self.inner.try_borrow_mut() { Ok(inner) } else { err!("already mutably borrowed") } } pub fn to_inner(&self) -> Result<PoolingAllocationConfigImpl, Error> { if let Ok(inner) = self.inner.try_borrow() { Ok(inner.clone()) } else { err!("already borrowed") } } } impl From<PoolingAllocationConfigImpl> for PoolingAllocationConfig { fn from(inner: PoolingAllocationConfigImpl) -> Self { Self { inner: RefCell::new(inner), } } } define_rb_intern!( AUTO => "auto", YES => "yes", NO => "no", ); lazy_static! { pub static ref MPK_MAPPING: SymbolEnum<'static, Enabled> = { let mapping = vec![ (*AUTO, Enabled::Auto), (*YES, Enabled::Yes), (*NO, Enabled::No), ]; SymbolEnum::new("Memory protection keys strategy", mapping) }; } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("PoolingAllocationConfig", ruby.class_object())?; class.define_singleton_method("new", function!(PoolingAllocationConfig::new, 0))?; class.define_singleton_method( "memory_protection_keys_available?", function!( PoolingAllocationConfig::are_memory_protection_keys_available, 0 ), )?; class.define_method( "total_memories=", method!(PoolingAllocationConfig::set_total_memories, 1), )?; class.define_method( "total_tables=", method!(PoolingAllocationConfig::set_total_tables, 1), )?; class.define_method( "max_memories_per_module=", method!(PoolingAllocationConfig::set_max_memories_per_module, 1), )?; class.define_method( "max_tables_per_module=", method!(PoolingAllocationConfig::set_max_tables_per_component, 1), )?; class.define_method( "async_stack_keep_resident=", method!(PoolingAllocationConfig::set_async_stack_keep_resident, 1), )?; class.define_method( "linear_memory_keep_resident=", method!(PoolingAllocationConfig::set_linear_memory_keep_resident, 1), )?; class.define_method( "max_component_instance_size=", method!(PoolingAllocationConfig::set_max_component_instance_size, 1), )?; class.define_method( "max_core_instance_size=", method!(PoolingAllocationConfig::set_max_core_instance_size, 1), )?; class.define_method( "max_memories_per_component=", method!(PoolingAllocationConfig::set_max_memories_per_component, 1), )?; class.define_method( "max_memory_protection_keys=", method!(PoolingAllocationConfig::set_max_memory_protection_keys, 1), )?; class.define_method( "max_tables_per_component=", method!(PoolingAllocationConfig::set_max_tables_per_component, 1), )?; class.define_method( "max_unused_warm_slots=", method!(PoolingAllocationConfig::set_max_unused_warm_slots, 1), )?; class.define_method( "max_memory_size=", method!(PoolingAllocationConfig::set_max_memory_size, 1), )?; class.define_method( "memory_protection_keys=", method!(PoolingAllocationConfig::set_memory_protection_keys, 1), )?; class.define_method( "table_elements=", method!(PoolingAllocationConfig::set_table_elements, 1), )?; class.define_method( "table_keep_resident=", method!(PoolingAllocationConfig::set_table_keep_resident, 1), )?; class.define_method( "total_component_instances=", method!(PoolingAllocationConfig::set_total_component_instances, 1), )?; class.define_method( "total_core_instances=", method!(PoolingAllocationConfig::set_total_core_instances, 1), )?; class.define_method( "total_stacks=", method!(PoolingAllocationConfig::set_total_stacks, 1), )?; class.define_method("inspect", method!(PoolingAllocationConfig::inspect, 0))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/instance.rs
ext/src/ruby_api/instance.rs
use super::{ convert::{ToExtern, WrapWasmtimeType}, func::Func, module::Module, root, store::{Store, StoreContextValue, StoreData}, }; use crate::err; use magnus::{ class, function, gc::Marker, method, prelude::*, scan_args, typed_data::Obj, DataTypeFunctions, Error, Object, RArray, RHash, RString, Ruby, TryConvert, TypedData, Value, }; use wasmtime::{Extern, Instance as InstanceImpl, StoreContextMut}; /// @yard /// Represents a WebAssembly instance. /// @see https://docs.rs/wasmtime/latest/wasmtime/struct.Instance.html Wasmtime's Rust doc #[derive(Clone, Debug, TypedData)] #[magnus(class = "Wasmtime::Instance", mark, free_immediately)] pub struct Instance { inner: InstanceImpl, store: Obj<Store>, } unsafe impl Send for Instance {} impl DataTypeFunctions for Instance { fn mark(&self, marker: &Marker) { marker.mark(self.store) } } impl Instance { /// @yard /// @def new(store, mod, imports = []) /// @param store [Store] The store to instantiate the module in. /// @param mod [Module] The module to instantiate. /// @param imports [Array<Func, Memory>] /// The module's import, in orders that that they show up in the module. /// @return [Instance] pub fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> { let args = scan_args::scan_args::<(Obj<Store>, &Module), (Option<Value>,), (), (), (), ()>(args)?; let (wrapped_store, module) = args.required; let mut context = wrapped_store.context_mut(); let imports = args .optional .0 .and_then(|v| if v.is_nil() { None } else { Some(v) }); let imports: Vec<Extern> = match imports { Some(arr) => { let arr = RArray::try_convert(arr)?; let mut imports = Vec::with_capacity(arr.len()); // SAFETY: arr won't get gc'd (it's on the stack) and we don't mutate it. for import in unsafe { arr.as_slice() } { context.data_mut().retain(*import); imports.push(import.to_extern(ruby)?); } imports } None => vec![], }; let module = module.get(); let inner = InstanceImpl::new(context, module, &imports) .map_err(|e| StoreContextValue::from(wrapped_store).handle_wasm_error(ruby, e))?; Ok(Self { inner, store: wrapped_store, }) } pub fn get(&self) -> InstanceImpl { self.inner } pub fn from_inner(store: Obj<Store>, inner: InstanceImpl) -> Self { Self { inner, store } } /// @yard /// Returns a +Hash+ of exports where keys are export names as +String+s /// and values are {Extern}s. /// /// @def exports /// @return [Hash{String => Extern}] pub fn exports(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RHash, Error> { let mut ctx = rb_self.store.context_mut(); let hash = ruby.hash_new(); for export in rb_self.inner.exports(&mut ctx) { let export_name = ruby.str_new(export.name()); let wrapped_store = rb_self.store; let wrapped_export = export .into_extern() .wrap_wasmtime_type(ruby, wrapped_store.into())?; hash.aset(export_name, wrapped_export)?; } Ok(hash) } /// @yard /// Get an export by name. /// /// @def export(name) /// @param name [String] /// @return [Extern, nil] The export if it exists, nil otherwise. pub fn export(&self, str: RString) -> Result<Option<super::externals::Extern<'_>>, Error> { let export = self .inner .get_export(self.store.context_mut(), unsafe { str.as_str()? }); let ruby = Ruby::get_with(str); match export { Some(export) => export .wrap_wasmtime_type(&ruby, self.store.into()) .map(Some), None => Ok(None), } } /// @yard /// Retrieves a Wasm function from the instance and calls it. /// Essentially a shortcut for +instance.export(name).call(...)+. /// /// @def invoke(name, *args) /// @param name [String] The name of function to run. /// @param (see Func#call) /// @return (see Func#call) /// @see Func#call pub fn invoke(ruby: &Ruby, rb_self: Obj<Self>, args: &[Value]) -> Result<Value, Error> { let name = RString::try_convert(*args.first().ok_or_else(|| { Error::new( ruby.exception_type_error(), "wrong number of arguments (given 0, expected 1+)", ) })?)?; let func = rb_self.get_func(rb_self.store.context_mut(), unsafe { name.as_str()? })?; Func::invoke(ruby, &rb_self.store.into(), &func, &args[1..]) } fn get_func( &self, context: StoreContextMut<'_, StoreData>, name: &str, ) -> Result<wasmtime::Func, Error> { let instance = self.inner; if let Some(func) = instance.get_func(context, name) { Ok(func) } else { err!("function \"{}\" not found", name) } } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let class = root().define_class("Instance", ruby.class_object())?; class.define_singleton_method("new", function!(Instance::new, -1))?; class.define_method("invoke", method!(Instance::invoke, -1))?; class.define_method("exports", method!(Instance::exports, 0))?; class.define_method("export", method!(Instance::export, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component.rs
ext/src/ruby_api/component.rs
mod convert; mod func; mod instance; mod linker; mod wasi_command; use super::root; use magnus::{ class::{self, RClass}, function, method, prelude::*, r_string::RString, typed_data::Obj, value::Lazy, Error, Module, Object, RModule, Ruby, }; use rb_sys::tracking_allocator::ManuallyTracked; use wasmtime::component::Component as ComponentImpl; pub use func::Func; pub use instance::Instance; pub use linker::Linker; pub use wasi_command::WasiCommand; pub fn component_namespace(ruby: &Ruby) -> RModule { static COMPONENT_NAMESPACE: Lazy<RModule> = Lazy::new(|_| root().define_module("Component").unwrap()); ruby.get_inner(&COMPONENT_NAMESPACE) } use crate::{ error, helpers::{nogvl, Tmplock}, Engine, }; /// @yard /// @rename Wasmtime::Component::Component /// Represents a WebAssembly component. /// @see https://docs.rs/wasmtime/latest/wasmtime/component/struct.Component.html Wasmtime's Rust doc #[magnus::wrap( class = "Wasmtime::Component::Component", size, free_immediately, frozen_shareable )] pub struct Component { inner: ComponentImpl, _track_memory_usage: ManuallyTracked<()>, } // Needed for ManuallyTracked unsafe impl Send for Component {} impl Component { /// @yard /// Creates a new component from the given binary data. /// @def new(engine, wat_or_wasm) /// @param engine [Wasmtime::Engine] /// @param wat_or_wasm [String] The String of WAT or Wasm. /// @return [Wasmtime::Component::Component] pub fn new(engine: &Engine, wat_or_wasm: RString) -> Result<Self, Error> { let eng = engine.get(); let (locked_slice, _locked_slice_guard) = wat_or_wasm.as_locked_slice()?; let component = nogvl(|| ComponentImpl::new(eng, locked_slice)) .map_err(|e| error!("Could not build component: {}", e))?; Ok(component.into()) } /// @yard /// @def from_file(engine, path) /// @param engine [Wasmtime::Engine] /// @param path [String] /// @return [Wasmtime::Component::Component] pub fn from_file(engine: &Engine, path: RString) -> Result<Self, Error> { let eng = engine.get(); let (path, _locked_str_guard) = path.as_locked_str()?; // SAFETY: this string is immediately copied and never moved off the stack let component = nogvl(|| ComponentImpl::from_file(eng, path)) .map_err(|e| error!("Could not build component from file: {}", e))?; Ok(component.into()) } /// @yard /// Instantiates a serialized component coming from either {#serialize} or {Wasmtime::Engine#precompile_component}. /// /// The engine serializing and the engine deserializing must: /// * have the same configuration /// * be of the same gem version /// /// @def deserialize(engine, compiled) /// @param engine [Wasmtime::Engine] /// @param compiled [String] String obtained with either {Wasmtime::Engine#precompile_component} or {#serialize}. /// @return [Wasmtime::Component::Component] pub fn deserialize(engine: &Engine, compiled: RString) -> Result<Self, Error> { // SAFETY: this string is immediately copied and never moved off the stack unsafe { ComponentImpl::deserialize(engine.get(), compiled.as_slice()) } .map(Into::into) .map_err(|e| error!("Could not deserialize component: {}", e)) } /// @yard /// Instantiates a serialized component from a file. /// /// @def deserialize_file(engine, path) /// @param engine [Wasmtime::Engine] /// @param path [String] /// @return [Wasmtime::Component::Component] /// @see .deserialize pub fn deserialize_file(engine: &Engine, path: RString) -> Result<Self, Error> { unsafe { ComponentImpl::deserialize_file(engine.get(), path.as_str()?) } .map(Into::into) .map_err(|e| error!("Could not deserialize component from file: {}", e)) } /// @yard /// Serialize the component. /// @return [String] /// @see .deserialize pub fn serialize(ruby: &Ruby, rb_self: Obj<Self>) -> Result<RString, Error> { let bytes = rb_self.get().serialize(); bytes .map(|bytes| ruby.str_from_slice(&bytes)) .map_err(|e| error!("{:?}", e)) } pub fn get(&self) -> &ComponentImpl { &self.inner } } impl From<ComponentImpl> for Component { fn from(inner: ComponentImpl) -> Self { let range = inner.image_range(); let start = range.start; let end = range.end; assert!(end > start); let size = unsafe { end.offset_from(start) }; Self { inner, _track_memory_usage: ManuallyTracked::new(size as usize), } } } mod bundled { include!(concat!(env!("OUT_DIR"), "/bundled/component.rs")); } pub fn init(ruby: &Ruby) -> Result<(), Error> { bundled::init()?; let namespace = component_namespace(ruby); let class = namespace.define_class("Component", ruby.class_object())?; class.define_singleton_method("new", function!(Component::new, 2))?; class.define_singleton_method("from_file", function!(Component::from_file, 2))?; class.define_singleton_method("deserialize", function!(Component::deserialize, 2))?; class.define_singleton_method( "deserialize_file", function!(Component::deserialize_file, 2), )?; class.define_method("serialize", method!(Component::serialize, 0))?; linker::init(ruby, &namespace)?; instance::init(ruby, &namespace)?; func::init(ruby, &namespace)?; convert::init(ruby)?; wasi_command::init(ruby, &namespace)?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/memory/unsafe_slice.rs
ext/src/ruby_api/memory/unsafe_slice.rs
use crate::{define_rb_intern, error, root, Memory}; use magnus::{ class, gc::Marker, method, rb_sys::{AsRawId, AsRawValue, FromRawValue}, typed_data::Obj, value::{IntoId, Lazy, Opaque}, Class, DataTypeFunctions, Error, Module as _, Ruby, TryConvert, TypedData, Value, }; #[cfg(ruby_gte_3_0)] use magnus::{RClass, RModule}; use rb_sys::{rb_ivar_set, rb_obj_freeze, rb_str_new_static}; #[cfg(ruby_gte_3_0)] use rb_sys::{ rb_memory_view_entry_t, rb_memory_view_init_as_byte_array, rb_memory_view_register, rb_memory_view_t, VALUE, }; use std::ops::Range; /// @yard /// @rename Wasmtime::Memory::UnsafeSlice /// Represents a slice of a WebAssembly memory. This is useful for creating Ruby /// strings from Wasm memory without any extra memory allocations. /// /// The returned {UnsafeSlice} lazily reads the underlying memory, meaning that /// the actual pointer to the string buffer is not materialzed until /// {UnsafeSlice#to_str} is called. #[derive(TypedData)] #[magnus( class = "Wasmtime::Memory::UnsafeSlice", free_immediately, mark, unsafe_generics )] pub struct UnsafeSlice<'a> { memory: MemoryGuard<'a>, range: Range<usize>, } define_rb_intern!(IVAR_NAME => "__slice__",); impl DataTypeFunctions for UnsafeSlice<'_> { fn mark(&self, marker: &Marker) { self.memory.mark(marker) } } #[cfg(ruby_gte_3_0)] fn fiddle_memory_view_class(ruby: &Ruby) -> Option<RClass> { let fiddle = ruby.class_object().const_get::<_, RModule>("Fiddle").ok()?; fiddle.const_get("MemoryView").ok() } impl<'a> UnsafeSlice<'a> { pub fn new(memory: Obj<Memory<'a>>, range: Range<usize>) -> Result<Self, Error> { let memory = MemoryGuard::new(memory)?; let slice = Self { memory, range }; let _ = slice.get_raw_slice()?; // Check that the slice is valid. Ok(slice) } /// @yard /// Get this slice as a Fiddle memory view, which can be cheaply read by /// other Ruby extensions. /// /// @def to_memory_view /// @return [Fiddle::MemoryView] Memory view of the slice. #[cfg(ruby_gte_3_0)] pub fn to_memory_view(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { static CLASS: Lazy<RClass> = Lazy::new(|_| { let ruby = Ruby::get().unwrap(); fiddle_memory_view_class(&ruby).unwrap() }); ruby.get_inner(&CLASS).new_instance((rb_self,)) } /// @yard /// Gets the memory slice as a Ruby string without copying the underlying buffer. /// /// @def to_str /// @return [String] Binary +String+ of the memory. pub fn to_str(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Value, Error> { let raw_slice = rb_self.get_raw_slice()?; let id = IVAR_NAME.into_id_with(ruby); let rstring = unsafe { let val = rb_str_new_static(raw_slice.as_ptr() as _, raw_slice.len() as _); rb_ivar_set(val, id.as_raw(), rb_self.as_raw()); rb_obj_freeze(val) }; Ok(unsafe { Value::from_raw(rstring) }) } fn get_raw_slice(&self) -> Result<&[u8], Error> { let mem = self.memory.get()?; mem.data()? .get(self.range.clone()) .ok_or_else(|| error!("out of bounds memory access")) } #[cfg(ruby_gte_3_0)] fn register_memory_view(ruby: &Ruby) -> Result<(), Error> { let class = Self::class(ruby); static ENTRY: rb_memory_view_entry_t = rb_memory_view_entry_t { get_func: Some(UnsafeSlice::initialize_memory_view), release_func: None, available_p_func: Some(UnsafeSlice::is_memory_view_available), }; if unsafe { rb_memory_view_register(class.as_raw(), &ENTRY) } { Ok(()) } else { Err(error!("failed to register memory view")) } } #[cfg(ruby_gte_3_0)] extern "C" fn initialize_memory_view( value: VALUE, view: *mut rb_memory_view_t, _flags: i32, ) -> bool { let obj = unsafe { Value::from_raw(value) }; let Ok(memory) = <Obj<UnsafeSlice>>::try_convert(obj) else { return false; }; let Ok(raw_slice) = memory.get_raw_slice() else { return false; }; let (ptr, size) = (raw_slice.as_ptr(), raw_slice.len()); unsafe { rb_memory_view_init_as_byte_array(view, value, ptr as _, size as _, true) } } #[cfg(ruby_gte_3_0)] extern "C" fn is_memory_view_available(value: VALUE) -> bool { let obj = unsafe { Value::from_raw(value) }; let Ok(memory) = <Obj<UnsafeSlice>>::try_convert(obj) else { return false; }; memory.get_raw_slice().is_ok() } } /// A guard that ensures that a memory slice is not invalidated by resizing pub struct MemoryGuard<'a> { memory: Opaque<Obj<Memory<'a>>>, original_size: u64, } impl<'a> MemoryGuard<'a> { pub fn new(memory: Obj<Memory<'a>>) -> Result<Self, Error> { let original_size = memory.size()?; Ok(Self { memory: memory.into(), original_size, }) } pub fn get(&self) -> Result<&Memory<'a>, Error> { let ruby = Ruby::get().unwrap(); let mem = ruby.get_inner_ref(&self.memory); if mem.size()? != self.original_size { Err(error!("memory slice was invalidated by resize")) } else { Ok(mem) } } pub fn mark(&self, marker: &Marker) { marker.mark(self.memory) } } pub fn init(ruby: &Ruby) -> Result<(), Error> { let parent = root().define_class("Memory", ruby.class_object())?; let class = parent.define_class("UnsafeSlice", ruby.class_object())?; class.define_method("to_str", method!(UnsafeSlice::to_str, 0))?; #[cfg(ruby_gte_3_0)] if ruby.require("fiddle").is_ok() && fiddle_memory_view_class(ruby).is_some() { UnsafeSlice::register_memory_view(ruby)?; class.define_method("to_memory_view", method!(UnsafeSlice::to_memory_view, 0))?; } Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component/func.rs
ext/src/ruby_api/component/func.rs
use crate::ruby_api::{ component::{ convert::{component_val_to_rb, rb_to_component_val}, Instance, }, errors::ExceptionMessage, store::{Store, StoreContextValue}, }; use magnus::{ class, gc::Marker, method, prelude::*, typed_data::Obj, value, DataTypeFunctions, Error, IntoValue, RArray, RModule, Ruby, TypedData, Value, }; use wasmtime::component::{Func as FuncImpl, Type, Val}; /// @yard /// @rename Wasmtime::Component::Func /// Represents a WebAssembly component Function /// @see https://docs.wasmtime.dev/api/wasmtime/component/struct.Func.html Wasmtime's Rust doc /// /// == Component model types conversion /// /// Here's how component model types map to Ruby objects: /// /// bool:: /// Ruby +true+ or +false+, no automatic conversion happens. /// s8, u8, s16, u16, etc.:: /// Ruby +Integer+. Overflows raise. /// f32, f64:: /// Ruby +Float+. /// string:: /// Ruby +String+. Exception will be raised if the string is not valid UTF-8. /// list<T>:: /// Ruby +Array+. /// tuple:: /// Ruby +Array+ of the same size of tuple. Example: +tuple<T, U>+ would be converted to +[T, U]+. /// record:: /// Ruby +Hash+ where field names are +String+s /// (for performance, see {this benchmark}[https://github.com/bytecodealliance/wasmtime-rb/issues/400#issuecomment-2496097993]). /// result<O, E>:: /// {Result} instance. When converting a result branch of the none /// type, the {Result}’s value MUST be +nil+. /// /// Examples of none type in a result: unparametrized +result+, +result<O>+, +result<_, E>+. /// option<T>:: /// +nil+ is mapped to +None+, anything else is mapped to +Some(T)+. /// flags:: /// Ruby +Array+ of +String+s. /// enum:: /// Ruby +String+. Exception will be raised of the +String+ is not a valid enum value. /// variant:: /// {Variant} instance wrapping the variant's name and optionally its value. /// Exception will be raised for: /// - invalid {Variant#name}, /// - unparametrized variant and not nil {Variant#value}. /// resource (own<T> or borrow<T>):: /// Not yet supported. #[derive(TypedData)] #[magnus(class = "Wasmtime::Component::Func", size, mark, free_immediately)] pub struct Func { store: Obj<Store>, instance: Obj<Instance>, inner: FuncImpl, } unsafe impl Send for Func {} impl DataTypeFunctions for Func { fn mark(&self, marker: &Marker) { marker.mark(self.store); marker.mark(self.instance); } } impl Func { /// @yard /// Calls a Wasm component model function. /// @def call(*args) /// @param args [Array<Object>] the function's arguments as per its Wasm definition /// @return [Object] the function's return value as per its Wasm definition /// @see Func Func class-level documentation for type conversion logic pub fn call(&self, args: &[Value]) -> Result<Value, Error> { let ruby = Ruby::get().unwrap(); Func::invoke(&ruby, self.store, &self.inner, args) } pub fn from_inner(inner: FuncImpl, instance: Obj<Instance>, store: Obj<Store>) -> Self { Self { store, instance, inner, } } pub fn invoke( ruby: &Ruby, store: Obj<Store>, func: &FuncImpl, args: &[Value], ) -> Result<Value, Error> { let store_context_value = StoreContextValue::from(store); let func_ty = func.ty(store.context_mut()); let results_ty = func_ty.results(); let mut results = vec![wasmtime::component::Val::Bool(false); results_ty.len()]; let params = convert_params(ruby, &store_context_value, func_ty.params(), args)?; func.call(store.context_mut(), &params, &mut results) .map_err(|e| store_context_value.handle_wasm_error(ruby, e))?; let result = match results_ty.len() { 0 => Ok(ruby.qnil().as_value()), 1 => component_val_to_rb( ruby, results.into_iter().next().unwrap(), &store_context_value, ), _ => { let ary = ruby.ary_new_capa(results_ty.len()); for result in results { let val = component_val_to_rb(ruby, result, &store_context_value)?; ary.push(val)?; } Ok(ary.into_value_with(ruby)) } }; func.post_return(store.context_mut()) .map_err(|e| store_context_value.handle_wasm_error(ruby, e))?; result } } fn convert_params<'a>( ruby: &Ruby, store: &StoreContextValue, ty: impl ExactSizeIterator<Item = (&'a str, Type)>, params_slice: &[Value], ) -> Result<Vec<Val>, Error> { if ty.len() != params_slice.len() { return Err(Error::new( ruby.exception_arg_error(), format!( "wrong number of arguments (given {}, expected {})", params_slice.len(), ty.len() ), )); } let mut params = Vec::with_capacity(ty.len()); for (i, (ty, value)) in ty.zip(params_slice.iter()).enumerate() { let i: u32 = i .try_into() .map_err(|_| Error::new(ruby.exception_arg_error(), "too many params"))?; let component_val = rb_to_component_val(*value, store, &ty.1) .map_err(|error| error.append(format!(" (param at index {i})")))?; params.push(component_val); } Ok(params) } pub fn init(ruby: &Ruby, namespace: &RModule) -> Result<(), Error> { let func = namespace.define_class("Func", ruby.class_object())?; func.define_method("call", method!(Func::call, -1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component/convert.rs
ext/src/ruby_api/component/convert.rs
use crate::ruby_api::component::component_namespace; use crate::ruby_api::errors::ExceptionMessage; use crate::ruby_api::store::StoreContextValue; use crate::{define_rb_intern, err, error, not_implemented}; use magnus::rb_sys::AsRawValue; use magnus::value::{IntoId, Lazy, ReprValue}; use magnus::{ prelude::*, try_convert, value, Error, IntoValue, RArray, RClass, RHash, RString, Ruby, Value, }; use wasmtime::component::{Type, Val}; define_rb_intern!( // For Component::Result OK => "ok", ERROR => "error", IS_ERROR => "error?", IS_OK => "ok?", // For Component::Variant NEW => "new", NAME => "name", VALUE => "value", ); pub(crate) fn component_val_to_rb( ruby: &Ruby, val: Val, _store: &StoreContextValue, ) -> Result<Value, Error> { match val { Val::Bool(bool) => Ok(bool.into_value_with(ruby)), Val::S8(n) => Ok(n.into_value_with(ruby)), Val::U8(n) => Ok(n.into_value_with(ruby)), Val::S16(n) => Ok(n.into_value_with(ruby)), Val::U16(n) => Ok(n.into_value_with(ruby)), Val::S32(n) => Ok(n.into_value_with(ruby)), Val::U32(n) => Ok(n.into_value_with(ruby)), Val::S64(n) => Ok(n.into_value_with(ruby)), Val::U64(n) => Ok(n.into_value_with(ruby)), Val::Float32(n) => Ok(n.into_value_with(ruby)), Val::Float64(n) => Ok(n.into_value_with(ruby)), Val::Char(c) => Ok(c.into_value_with(ruby)), Val::String(s) => Ok(s.as_str().into_value_with(ruby)), Val::List(vec) => { let array = ruby.ary_new_capa(vec.len()); for val in vec { array.push(component_val_to_rb(ruby, val, _store)?)?; } Ok(array.into_value_with(ruby)) } Val::Record(fields) => { let hash = ruby.hash_new(); for (name, val) in fields { let rb_value = component_val_to_rb(ruby, val, _store) .map_err(|e| e.append(format!(" (struct field \"{name}\")")))?; hash.aset(name.as_str(), rb_value)? } Ok(hash.into_value_with(ruby)) } Val::Tuple(vec) => { let array = ruby.ary_new_capa(vec.len()); for val in vec { array.push(component_val_to_rb(ruby, val, _store)?)?; } Ok(array.into_value_with(ruby)) } Val::Variant(kind, val) => { let payload = match val { Some(val) => component_val_to_rb(ruby, *val, _store)?, None => ruby.qnil().into_value_with(ruby), }; variant_class(ruby).funcall( NEW.into_id_with(ruby), (kind.into_value_with(ruby), payload), ) } Val::Enum(kind) => Ok(kind.as_str().into_value_with(ruby)), Val::Option(val) => match val { Some(val) => Ok(component_val_to_rb(ruby, *val, _store)?), None => Ok(ruby.qnil().as_value()), }, Val::Result(val) => { let (ruby_method, val) = match val { Ok(val) => (OK.into_id_with(ruby), val), Err(val) => (ERROR.into_id_with(ruby), val), }; let ruby_argument = match val { Some(val) => component_val_to_rb(ruby, *val, _store)?, None => ruby.qnil().as_value(), }; result_class(ruby).funcall(ruby_method, (ruby_argument,)) } Val::Flags(vec) => Ok(vec.into_value_with(ruby)), Val::Resource(_resource_any) => not_implemented!(ruby, "Resource not implemented"), Val::Future(_) => not_implemented!(ruby, "Future not implemented"), Val::ErrorContext(_) => not_implemented!(ruby, "ErrorContext not implemented"), Val::Stream(_) => not_implemented!(ruby, "Stream not implemented"), } } pub(crate) fn rb_to_component_val( value: Value, _store: &StoreContextValue, ty: &Type, ) -> Result<Val, Error> { let ruby = Ruby::get_with(value); match ty { Type::Bool => { if value.as_raw() == ruby.qtrue().as_raw() { Ok(Val::Bool(true)) } else if value.as_raw() == ruby.qfalse().as_raw() { Ok(Val::Bool(false)) } else { Err(Error::new( ruby.exception_type_error(), // SAFETY: format will copy classname directly, before we call back in to Ruby format!("no implicit conversion of {} into boolean", unsafe { value.classname() }), )) } } Type::S8 => Ok(Val::S8(i8::try_convert(value)?)), Type::U8 => Ok(Val::U8(u8::try_convert(value)?)), Type::S16 => Ok(Val::S16(i16::try_convert(value)?)), Type::U16 => Ok(Val::U16(u16::try_convert(value)?)), Type::S32 => Ok(Val::S32(i32::try_convert(value)?)), Type::U32 => Ok(Val::U32(u32::try_convert(value)?)), Type::S64 => Ok(Val::S64(i64::try_convert(value)?)), Type::U64 => Ok(Val::U64(u64::try_convert(value)?)), Type::Float32 => Ok(Val::Float32(f32::try_convert(value)?)), Type::Float64 => Ok(Val::Float64(f64::try_convert(value)?)), Type::Char => Ok(Val::Char(value.to_r_string()?.to_char()?)), Type::String => Ok(Val::String(RString::try_convert(value)?.to_string()?)), Type::List(list) => { let ty = list.ty(); let rarray = RArray::try_convert(value)?; let mut vals: Vec<Val> = Vec::with_capacity(rarray.len()); // SAFETY: we don't mutate the RArray and we don't call into // user code so user code can't mutate it either. for (i, value) in unsafe { rarray.as_slice() }.iter().enumerate() { let component_val = rb_to_component_val(*value, _store, &ty) .map_err(|e| e.append(format!(" (list item at index {i})")))?; vals.push(component_val); } Ok(Val::List(vals)) } Type::Record(record) => { let hash = RHash::try_convert(value)?; let mut kv = Vec::with_capacity(record.fields().len()); for field in record.fields() { let value = hash .get(field.name) .ok_or_else(|| error!("struct field missing: {}", field.name)) .and_then(|v| { rb_to_component_val(v, _store, &field.ty) .map_err(|e| e.append(format!(" (struct field \"{}\")", field.name))) })?; kv.push((field.name.to_string(), value)) } Ok(Val::Record(kv)) } Type::Tuple(tuple) => { let types = tuple.types(); let rarray = RArray::try_convert(value)?; if types.len() != rarray.len() { return Err(Error::new( ruby.exception_type_error(), format!( "invalid array length for tuple (given {}, expected {})", rarray.len(), types.len() ), )); } let mut vals: Vec<Val> = Vec::with_capacity(rarray.len()); for (i, (ty, value)) in types.zip(unsafe { rarray.as_slice() }.iter()).enumerate() { let component_val = rb_to_component_val(*value, _store, &ty) .map_err(|error| error.append(format!(" (tuple value at index {i})")))?; vals.push(component_val); } Ok(Val::Tuple(vals)) } Type::Variant(variant) => { let name: RString = value.funcall(NAME.into_id_with(&ruby), ())?; let name = name.to_string()?; let case = variant .cases() .find(|case| case.name == name.as_str()) .ok_or_else(|| { error!( "invalid variant case \"{}\", valid cases: [{}]", name, variant .cases() .map(|c| format!("\"{}\"", c.name)) .collect::<Vec<_>>() .join(", ") ) })?; let payload_rb: Value = value.funcall(VALUE.into_id_with(&ruby), ())?; let payload_val = match (&case.ty, payload_rb.is_nil()) { (Some(ty), _) => rb_to_component_val(payload_rb, _store, ty) .map(|val| Some(Box::new(val))) .map_err(|e| e.append(format!(" (variant value for \"{}\")", &name))), // case doesn't have payload and Variant#value *is nil* (None, true) => Ok(None), // case doesn't have payload and Variant#value *is not nil* (None, false) => err!( "expected no value for variant case \"{}\", got {}", &name, payload_rb.inspect() ), }?; Ok(Val::Variant(name, payload_val)) } Type::Enum(_) => { let rstring = RString::try_convert(value)?; rstring.to_string().map(Val::Enum) } Type::Option(option_type) => { if value.is_nil() { Ok(Val::Option(None)) } else { Ok(Val::Option(Some(Box::new(rb_to_component_val( value, _store, &option_type.ty(), )?)))) } } Type::Result(result_type) => { // Expect value to conform to `Wasmtime::Component::Value`'s interface let is_ok = value.funcall::<_, (), bool>(IS_OK.into_id_with(&ruby), ())?; if is_ok { let ok_value = value.funcall::<_, (), Value>(OK.into_id_with(&ruby), ())?; match result_type.ok() { Some(ty) => rb_to_component_val(ok_value, _store, &ty) .map(|val| Val::Result(Result::Ok(Some(Box::new(val))))), None => { if ok_value.is_nil() { Ok(Val::Result(Ok(None))) } else { err!( "expected nil for result<_, E> ok branch, got {}", ok_value.inspect() ) } } } } else { let err_value = value.funcall::<_, (), Value>(ERROR.into_id_with(&ruby), ())?; match result_type.err() { Some(ty) => rb_to_component_val(err_value, _store, &ty) .map(|val| Val::Result(Result::Err(Some(Box::new(val))))), None => { if err_value.is_nil() { Ok(Val::Result(Err(None))) } else { err!( "expected nil for result<O, _> error branch, got {}", err_value.inspect() ) } } } } } Type::Flags(_) => Vec::<String>::try_convert(value).map(Val::Flags), Type::Own(_resource_type) => not_implemented!(ruby, "Resource not implemented"), Type::Borrow(_resource_type) => not_implemented!(ruby, "Resource not implemented"), Type::Future(_) => not_implemented!(ruby, "Future not implemented"), Type::Stream(_) => not_implemented!(ruby, "Stream not implemented"), Type::ErrorContext => not_implemented!(ruby, "ErrorContext not implemented"), } } fn result_class(ruby: &Ruby) -> RClass { static RESULT_CLASS: Lazy<RClass> = Lazy::new(|ruby| component_namespace(ruby).const_get("Result").unwrap()); ruby.get_inner(&RESULT_CLASS) } fn variant_class(ruby: &Ruby) -> RClass { static VARIANT_CLASS: Lazy<RClass> = Lazy::new(|ruby| component_namespace(ruby).const_get("Variant").unwrap()); ruby.get_inner(&VARIANT_CLASS) } pub fn init(ruby: &Ruby) -> Result<(), Error> { // Warm up let _ = result_class(ruby); let _ = OK; let _ = ERROR; let _ = IS_ERROR; let _ = IS_OK; let _ = result_class(ruby); let _ = NEW; let _ = NAME; let _ = VALUE; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component/wasi_command.rs
ext/src/ruby_api/component/wasi_command.rs
use magnus::{ class, function, method, module::Module, typed_data::Obj, DataTypeFunctions, Error, Object, RModule, Ruby, }; use wasmtime_wasi::p2::bindings::sync::Command; use crate::{ err, error, ruby_api::{ component::{linker::Linker, Component}, errors, }, Store, }; #[magnus::wrap(class = "Wasmtime::Component::WasiCommand", size, free_immediately)] pub struct WasiCommand { command: Command, } impl WasiCommand { /// @yard /// @def new(store, component, linker) /// @param store [Store] /// @param component [Component] /// @param linker [Linker] /// @return [WasiCommand] pub fn new(store: &Store, component: &Component, linker: &Linker) -> Result<Self, Error> { if linker.has_wasi() && !store.context().data().has_wasi_ctx() { return err!("{}", errors::missing_wasi_ctx_error("WasiCommand.new")); } let command = Command::instantiate(store.context_mut(), component.get(), &linker.inner_mut()) .map_err(|e| error!("{e}"))?; Ok(Self { command }) } /// @yard /// @def call_run(store) /// @param store [Store] /// @return [nil] pub fn call_run(_ruby: &Ruby, rb_self: Obj<Self>, store: &Store) -> Result<(), Error> { rb_self .command .wasi_cli_run() .call_run(store.context_mut()) .map_err(|err| error!("{err}"))? .map_err(|_| error!("Error running `run`")) } } pub fn init(ruby: &Ruby, namespace: &RModule) -> Result<(), Error> { let linker = namespace.define_class("WasiCommand", ruby.class_object())?; linker.define_singleton_method("new", function!(WasiCommand::new, 3))?; linker.define_method("call_run", method!(WasiCommand::call_run, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component/linker.rs
ext/src/ruby_api/component/linker.rs
use super::{Component, Instance}; use crate::{ err, ruby_api::{ errors, store::{StoreContextValue, StoreData}, Engine, Module, Store, }, }; use std::{ borrow::BorrowMut, cell::{RefCell, RefMut}, }; use crate::error; use magnus::{ class, function, gc::Marker, method, r_string::RString, scan_args, typed_data::Obj, DataTypeFunctions, Error, Module as _, Object, RModule, Ruby, TryConvert, TypedData, Value, }; use wasmtime::component::{Linker as LinkerImpl, LinkerInstance as LinkerInstanceImpl}; use wasmtime_wasi::{ResourceTable, WasiCtx}; /// @yard /// @rename Wasmtime::Component::Linker /// @see https://docs.rs/wasmtime/latest/wasmtime/component/struct.Linker.html Wasmtime's Rust doc #[derive(TypedData)] #[magnus(class = "Wasmtime::Component::Linker", size, mark, free_immediately)] pub struct Linker { inner: RefCell<LinkerImpl<StoreData>>, refs: RefCell<Vec<Value>>, has_wasi: RefCell<bool>, } unsafe impl Send for Linker {} impl DataTypeFunctions for Linker { fn mark(&self, marker: &magnus::gc::Marker) { marker.mark_slice(self.refs.borrow().as_slice()); } } impl Linker { /// @yard /// @def new(engine) /// @param engine [Engine] /// @return [Linker] pub fn new(engine: &Engine) -> Result<Self, Error> { let linker: LinkerImpl<StoreData> = LinkerImpl::new(engine.get()); Ok(Linker { inner: RefCell::new(linker), refs: RefCell::new(Vec::new()), has_wasi: RefCell::new(false), }) } pub(crate) fn inner_mut(&self) -> RefMut<'_, LinkerImpl<StoreData>> { self.inner.borrow_mut() } pub(crate) fn has_wasi(&self) -> bool { *self.has_wasi.borrow() } /// @yard /// @def root /// Define items in the root of this {Linker}. /// @yield [instance] The block allows configuring the {LinkerInstance}; /// outside of this scope the instance becomes unusable. /// @yieldparam instance [LinkerInstance] /// @return [Linker] +self+ pub fn root(ruby: &Ruby, rb_self: Obj<Self>) -> Result<Obj<Self>, Error> { let Ok(mut inner) = rb_self.inner.try_borrow_mut() else { return err!("Linker is not reentrant"); }; let instance = ruby.obj_wrap(LinkerInstance::from_inner(inner.root())); let block_result: Result<Value, _> = ruby.yield_value(instance); instance.take_inner(); match block_result { Ok(_) => Ok(rb_self), Err(e) => Err(e), } } /// @yard /// @def instance(name) /// Define items at the provided namespace in this {Linker}. /// @param name [String] /// @yield [instance] The block allows configuring the {LinkerInstance}; /// outside of this scope the instance becomes unusable. /// @yieldparam instance [LinkerInstance] /// @return [Linker] +self+ pub fn instance(ruby: &Ruby, rb_self: Obj<Self>, name: RString) -> Result<Obj<Self>, Error> { let mut inner = rb_self.inner.borrow_mut(); let instance = inner .instance(unsafe { name.as_str() }?) .map_err(|e| error!("{}", e))?; let instance = ruby.obj_wrap(LinkerInstance::from_inner(instance)); let block_result: Result<Value, _> = ruby.yield_value(instance); instance.take_inner(); match block_result { Ok(_) => Ok(rb_self), Err(e) => Err(e), } } /// @yard /// Instantiates a {Component} in a {Store} using the defined imports in the linker. /// @def instantiate(store, component) /// @param store [Store] /// @param component [Component] /// @return [Instance] fn instantiate( _ruby: &Ruby, rb_self: Obj<Self>, store: Obj<Store>, component: &Component, ) -> Result<Instance, Error> { if *rb_self.has_wasi.borrow() && !store.context().data().has_wasi_ctx() { return err!("{}", errors::missing_wasi_ctx_error("linker.instantiate")); } let inner = rb_self.inner.borrow(); inner .instantiate(store.context_mut(), component.get()) .map(|instance| { rb_self .refs .borrow() .iter() .for_each(|value| store.retain(*value)); Instance::from_inner(store, instance) }) .map_err(|e| error!("{}", e)) } pub(crate) fn add_wasi_p2(&self) -> Result<(), Error> { *self.has_wasi.borrow_mut() = true; let mut inner = self.inner.borrow_mut(); wasmtime_wasi::p2::add_to_linker_sync(&mut inner).map_err(|e| error!("{e}")) } } /// @yard /// @rename Wasmtime::Component::LinkerInstance /// @see https://docs.rs/wasmtime/latest/wasmtime/component/struct.LinkerInstance.html Wasmtime's Rust doc /// {LinkerInstance}s are builder-style, ephemeral objects that can only be used /// within the block to which they get yielded. Calling methods outside of the /// block will raise. #[derive(TypedData)] #[magnus( class = "Wasmtime::Component::LinkerInstance", size, mark, free_immediately, unsafe_generics )] pub struct LinkerInstance<'a> { inner: RefCell<MaybeInstanceImpl<'a>>, refs: RefCell<Vec<Value>>, } unsafe impl Send for LinkerInstance<'_> {} impl DataTypeFunctions for LinkerInstance<'_> { fn mark(&self, marker: &Marker) { marker.mark_slice(self.refs.borrow().as_slice()); } } struct MaybeInstanceImpl<'a>(Option<LinkerInstanceImpl<'a, StoreData>>); impl<'a> MaybeInstanceImpl<'a> { pub fn new(instance: LinkerInstanceImpl<'a, StoreData>) -> Self { Self(Some(instance)) } pub fn get_mut(&mut self) -> Result<&mut LinkerInstanceImpl<'a, StoreData>, Error> { match &mut self.0 { Some(instance) => Ok(instance), None => err!("LinkerInstance went out of scope"), } } pub fn expire(&mut self) -> Option<LinkerInstanceImpl<'a, StoreData>> { self.0.take() } } impl<'a> LinkerInstance<'a> { fn from_inner(inner: LinkerInstanceImpl<'a, StoreData>) -> Self { Self { inner: RefCell::new(MaybeInstanceImpl::new(inner)), refs: RefCell::new(Vec::new()), } } /// @yard /// @def module(name, mod) /// @param name [String] /// @param mod [Module] fn module(rb_self: Obj<Self>, name: RString, module: &Module) -> Result<Obj<Self>, Error> { let Ok(mut maybe_instance) = rb_self.inner.try_borrow_mut() else { return err!("LinkerInstance is not reentrant"); }; let inner = maybe_instance.get_mut()?; inner .module(unsafe { name.as_str()? }, module.get()) .map_err(|e| error!("{}", e))?; Ok(rb_self) } /// @yard /// Defines a nested instance within the instance. /// @def instance(name) /// @param name [String] /// @yield [instance] The block allows configuring the {LinkerInstance}; /// outside of this scope the instance becomes unusable. /// @yieldparam instance [LinkerInstance] /// @return [LinkerInstance] +self+ fn instance(ruby: &Ruby, rb_self: Obj<Self>, name: RString) -> Result<Obj<Self>, Error> { let Ok(mut maybe_instance) = rb_self.inner.try_borrow_mut() else { return err!("LinkerInstance is not reentrant"); }; let inner = maybe_instance.get_mut()?; let nested_inner = inner .instance(unsafe { name.as_str()? }) .map_err(|e| error!("{}", e))?; let nested_instance = ruby.obj_wrap(LinkerInstance::from_inner(nested_inner)); let block_result: Result<Value, _> = ruby.yield_value(nested_instance); nested_instance.take_inner(); match block_result { Ok(_) => Ok(rb_self), Err(e) => Err(e), } } fn take_inner(&self) { let Ok(mut maybe_instance) = self.inner.try_borrow_mut() else { panic!("Linker instance is already borrowed, can't expire.") }; maybe_instance.expire(); } } pub fn init(ruby: &Ruby, namespace: &RModule) -> Result<(), Error> { let linker = namespace.define_class("Linker", ruby.class_object())?; linker.define_singleton_method("new", function!(Linker::new, 1))?; linker.define_method("root", method!(Linker::root, 0))?; linker.define_method("instance", method!(Linker::instance, 1))?; linker.define_method("instantiate", method!(Linker::instantiate, 2))?; let linker_instance = namespace.define_class("LinkerInstance", ruby.class_object())?; linker_instance.define_method("module", method!(LinkerInstance::module, 2))?; linker_instance.define_method("instance", method!(LinkerInstance::instance, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/ruby_api/component/instance.rs
ext/src/ruby_api/component/instance.rs
use crate::ruby_api::{component::Func, Store}; use std::{borrow::BorrowMut, cell::RefCell}; use crate::error; use magnus::{ class, error::ErrorType, function, gc::Marker, method, prelude::*, r_string::RString, scan_args, typed_data::Obj, value::{self, ReprValue}, DataTypeFunctions, Error, RArray, Ruby, TryConvert, TypedData, Value, }; use magnus::{IntoValue, RModule}; use wasmtime::component::{ComponentExportIndex, Instance as InstanceImpl, Type, Val}; /// @yard /// Represents a WebAssembly component instance. /// @see https://docs.rs/wasmtime/latest/wasmtime/component/struct.Instance.html Wasmtime's Rust doc #[derive(Clone, TypedData)] #[magnus(class = "Wasmtime::Component::Instance", mark, free_immediately)] pub struct Instance { inner: InstanceImpl, store: Obj<Store>, } unsafe impl Send for Instance {} impl DataTypeFunctions for Instance { fn mark(&self, marker: &Marker) { marker.mark(self.store) } } impl Instance { pub fn from_inner(store: Obj<Store>, inner: InstanceImpl) -> Self { Self { inner, store } } /// @yard /// Retrieves a Wasm function from the component instance. /// /// @def get_func(handle) /// @param handle [String, Array<String>] The path of the function to retrieve /// @return [Func, nil] The function if it exists, nil otherwise /// /// @example Retrieve a top-level +add+ export: /// instance.get_func("add") /// /// @example Retrieve an +add+ export nested under an +adder+ instance top-level export: /// instance.get_func(["adder", "add"]) pub fn get_func(rb_self: Obj<Self>, handle: Value) -> Result<Option<Func>, Error> { let func = rb_self .export_index(handle)? .and_then(|index| rb_self.inner.get_func(rb_self.store.context_mut(), index)) .map(|inner| Func::from_inner(inner, rb_self, rb_self.store)); Ok(func) } fn export_index(&self, handle: Value) -> Result<Option<ComponentExportIndex>, Error> { let ruby = Ruby::get_with(handle); let invalid_arg = || { Error::new( ruby.exception_type_error(), format!( "invalid argument for component index, expected String | Array<String>, got {}", handle.inspect() ), ) }; let index = if let Some(name) = RString::from_value(handle) { self.inner .get_export(self.store.context_mut(), None, unsafe { name.as_str()? }) .map(|(_, index)| index) } else if let Some(names) = RArray::from_value(handle) { unsafe { names.as_slice() } .iter() .try_fold::<_, _, Result<_, Error>>(None, |index, name| { let name = RString::from_value(*name).ok_or_else(invalid_arg)?; Ok(self .inner .get_export(self.store.context_mut(), index.as_ref(), unsafe { name.as_str()? }) .map(|(_, index)| index)) })? } else { return Err(invalid_arg()); }; Ok(index) } } pub fn init(ruby: &Ruby, namespace: &RModule) -> Result<(), Error> { let instance = namespace.define_class("Instance", ruby.class_object())?; instance.define_method("get_func", method!(Instance::get_func, 1))?; Ok(()) }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/symbol_enum.rs
ext/src/helpers/symbol_enum.rs
use super::static_id::StaticId; use magnus::{prelude::*, Error, Ruby, Symbol, TryConvert, Value}; use std::fmt::Display; /// Represents an enum as a set of Symbols (using `StaticId`). /// Each symbol maps to a value of the enum's type. pub struct SymbolEnum<'a, T: Clone> { what: &'a str, mapping: Mapping<T>, } impl<'a, T: Clone> SymbolEnum<'a, T> { pub fn new(what: &'a str, mapping: Vec<(StaticId, T)>) -> Self { Self { what, mapping: Mapping(mapping), } } /// Map a Magnus `Value` to the entry in the enum. /// Returns an `ArgumentError` with a message enumerating all valid symbols /// when `needle` isn't a valid symbol. pub fn get(&self, needle: Value) -> Result<T, magnus::Error> { let needle = Symbol::try_convert(needle).map_err(|_| self.error(needle))?; let id = magnus::value::Id::from(needle); self.mapping .0 .iter() .find(|(haystack, _)| *haystack == id) .map(|found| found.1.clone()) .ok_or_else(|| self.error(needle.as_value())) } pub fn error(&self, value: Value) -> Error { let ruby = Ruby::get_with(value); Error::new( ruby.exception_arg_error(), format!( "invalid {}, expected one of {}, got {:?}", self.what, self.mapping, value ), ) } } struct Mapping<T: Clone>(Vec<(StaticId, T)>); /// Mimicks `Array#inpsect`'s output with all valid symbols. /// E.g.: `[:s1, :s2, :s3]` impl<T: Clone> Display for Mapping<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "[")?; if let Some(((last, _), elems)) = self.0.split_last() { for (id, _) in elems.iter() { write!(f, ":{}, ", Symbol::from(*id).name().unwrap())?; } write!(f, ":{}", Symbol::from(*last).name().unwrap())?; } write!(f, "]")?; Ok(()) } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/output_limited_buffer.rs
ext/src/helpers/output_limited_buffer.rs
use bytes::Bytes; use magnus::{ value::{InnerValue, Opaque, ReprValue}, RString, Ruby, }; use std::io::Write; use std::sync::{Arc, Mutex}; use tokio::io::AsyncWrite; use wasmtime_wasi::cli::{IsTerminal, StdoutStream}; use wasmtime_wasi::p2::{OutputStream, Pollable, StreamError, StreamResult}; /// A buffer that limits the number of bytes that can be written to it. /// If the buffer is full, it will truncate the data. /// Is used in the buffer implementations of stdout and stderr in `WasiP1Ctx` and `WasiCtxBuilder`. pub struct OutputLimitedBuffer { inner: Arc<Mutex<OutputLimitedBufferInner>>, } // No support for WASI P3, yet. impl AsyncWrite for OutputLimitedBuffer { fn poll_write( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, _buf: &[u8], ) -> std::task::Poll<Result<usize, std::io::Error>> { std::task::Poll::Ready(Ok(0)) } fn poll_flush( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { std::task::Poll::Ready(Ok(())) } fn poll_shutdown( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { std::task::Poll::Ready(Ok(())) } } impl OutputLimitedBuffer { /// Creates a new [OutputLimitedBuffer] with the given underlying buffer /// and capacity. pub fn new(buffer: Opaque<RString>, capacity: usize) -> Self { Self { inner: Arc::new(Mutex::new(OutputLimitedBufferInner::new(buffer, capacity))), } } } impl Clone for OutputLimitedBuffer { fn clone(&self) -> Self { Self { inner: Arc::clone(&self.inner), } } } impl StdoutStream for OutputLimitedBuffer { fn p2_stream(&self) -> Box<dyn OutputStream> { let cloned = self.clone(); Box::new(cloned) } fn async_stream(&self) -> Box<dyn AsyncWrite + Send + Sync> { let cloned = self.clone(); Box::new(cloned) } } impl IsTerminal for OutputLimitedBuffer { fn is_terminal(&self) -> bool { false } } #[async_trait::async_trait] impl Pollable for OutputLimitedBuffer { async fn ready(&mut self) {} } impl OutputStream for OutputLimitedBuffer { fn write(&mut self, bytes: Bytes) -> StreamResult<()> { let mut stream = self.inner.lock().expect("Should be only writer"); stream.write(&bytes) } fn flush(&mut self) -> StreamResult<()> { Ok(()) } fn check_write(&mut self) -> StreamResult<usize> { let mut stream = self.inner.lock().expect("Should be only writer"); stream.check_write() } } struct OutputLimitedBufferInner { buffer: Opaque<RString>, /// The maximum number of bytes that can be written to the output stream buffer. capacity: usize, } impl OutputLimitedBufferInner { #[must_use] pub fn new(buffer: Opaque<RString>, capacity: usize) -> Self { Self { buffer, capacity } } } impl OutputLimitedBufferInner { fn check_write(&mut self) -> StreamResult<usize> { Ok(usize::MAX) } fn write(&mut self, buf: &[u8]) -> StreamResult<()> { // Append a buffer to the string and truncate when hitting the capacity. // We return the input buffer size regardless of whether we truncated or not to avoid a panic. let ruby = Ruby::get().unwrap(); let mut inner_buffer = self.buffer.get_inner_with(&ruby); // Handling frozen case here is necessary because magnus does not check if a string is frozen before writing to it. let is_frozen = inner_buffer.as_value().is_frozen(); if is_frozen { return Err(StreamError::trap("Cannot write to a frozen buffer.")); } if buf.is_empty() { return Ok(()); } if inner_buffer .len() .checked_add(buf.len()) .is_some_and(|val| val < self.capacity) { inner_buffer .write(buf) .map_err(|e| StreamError::trap(&e.to_string()))?; } else { let portion = self.capacity - inner_buffer.len(); inner_buffer .write(&buf[0..portion]) .map_err(|e| StreamError::trap(&e.to_string()))?; }; Ok(()) } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/tmplock.rs
ext/src/helpers/tmplock.rs
use magnus::{ rb_sys::{protect, AsRawValue}, RString, }; pub trait Tmplock { fn as_locked_slice(&self) -> Result<(&[u8], TmplockGuard), magnus::Error>; fn as_locked_str(&self) -> Result<(&str, TmplockGuard), magnus::Error>; } #[derive(Debug)] #[repr(transparent)] pub struct TmplockGuard { raw: rb_sys::VALUE, } impl Drop for TmplockGuard { fn drop(&mut self) { let result = unsafe { protect(|| rb_sys::rb_str_unlocktmp(self.raw)) }; debug_assert!( result.is_ok(), "failed to unlock tmplock for unknown reason" ); } } impl Tmplock for RString { fn as_locked_slice(&self) -> Result<(&[u8], TmplockGuard), magnus::Error> { let raw = self.as_raw(); let slice = unsafe { self.as_slice() }; let raw = protect(|| unsafe { rb_sys::rb_str_locktmp(raw) })?; let guard = TmplockGuard { raw }; Ok((slice, guard)) } fn as_locked_str(&self) -> Result<(&str, TmplockGuard), magnus::Error> { let str_result = unsafe { self.as_str()? }; let raw = self.as_raw(); let raw = protect(|| unsafe { rb_sys::rb_str_locktmp(raw) })?; let guard = TmplockGuard { raw }; Ok((str_result, guard)) } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/macros.rs
ext/src/helpers/macros.rs
/// A macro to define a new `Id` const for a given string. #[macro_export] macro_rules! define_rb_intern { ($($name:ident => $id:expr,)*) => { $( lazy_static::lazy_static! { /// Define a Ruby internal `Id`. Equivalent to `rb_intern("$name")` pub static ref $name: $crate::helpers::StaticId = $crate::helpers::StaticId::intern_str($id); } )* }; }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/mod.rs
ext/src/helpers/mod.rs
mod macros; mod nogvl; mod output_limited_buffer; mod static_id; mod symbol_enum; mod tmplock; pub use nogvl::nogvl; pub use output_limited_buffer::OutputLimitedBuffer; pub use static_id::StaticId; pub use symbol_enum::SymbolEnum; pub use tmplock::Tmplock;
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/static_id.rs
ext/src/helpers/static_id.rs
use magnus::rb_sys::{AsRawId, FromRawId}; use magnus::{ value::{Id, IntoId}, Ruby, Symbol, }; use std::convert::TryInto; use std::num::NonZeroUsize; /// A static `Id` that can be used to refer to a Ruby ID. /// /// Use `define_rb_intern!` to define it so that it will be cached in a global variable. /// /// Magnus' `Id` can't be used for this purpose since it is not `Sync`, so cannot /// be used as a global variable with `lazy_static` in `define_rb_intern!`. /// See [this commit on the Magnus repo][commit]. /// /// [commit]: https://github.com/matsadler/magnus/commit/1a1c1ee874e15b0b222f7aae68bb9b5360072e57 #[derive(Clone, Copy)] #[repr(transparent)] pub struct StaticId(NonZeroUsize); impl StaticId { // Use `define_rb_intern!` instead, which uses this function. pub fn intern_str(id: &'static str) -> Self { let ruby = Ruby::get().unwrap(); let id: Id = ruby.sym_new(id).into(); // SAFETY: Ruby will never return a `0` ID. StaticId(unsafe { NonZeroUsize::new_unchecked(id.as_raw() as _) }) } } impl IntoId for StaticId { fn into_id_with(self, _: &Ruby) -> Id { // SAFEFY: This is safe because we know that the `Id` is something // returned from ruby. unsafe { Id::from_raw(self.0.get().try_into().expect("ID to be a usize")) } } } impl From<StaticId> for Symbol { fn from(static_id: StaticId) -> Self { let ruby = Ruby::get().unwrap(); let id: Id = static_id.into_id_with(&ruby); id.into() } } impl std::cmp::PartialEq<Id> for StaticId { fn eq(&self, other: &Id) -> bool { other.as_raw() as usize == self.0.get() } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/ext/src/helpers/nogvl.rs
ext/src/helpers/nogvl.rs
use std::{ffi::c_void, mem::MaybeUninit, ptr::null_mut}; use rb_sys::rb_thread_call_without_gvl; unsafe extern "C" fn call_without_gvl<F, R>(arg: *mut c_void) -> *mut c_void where F: FnMut() -> R, R: Sized, { let arg = arg as *mut (&mut F, &mut MaybeUninit<R>); let (func, result) = unsafe { &mut *arg }; result.write(func()); null_mut() } pub fn nogvl<F, R>(mut func: F) -> R where F: FnMut() -> R, R: Sized, { let result = MaybeUninit::uninit(); let arg_ptr = &(&mut func, &result) as *const _ as *mut c_void; unsafe { rb_thread_call_without_gvl(Some(call_without_gvl::<F, R>), arg_ptr, None, null_mut()); result.assume_init() } }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/spec/fixtures/wasi-fs/src/main.rs
spec/fixtures/wasi-fs/src/main.rs
use std::io::{Write, Read}; use std::fs::File; fn main() { let args: Vec<String> = std::env::args().collect(); let counter_file = File::open(&args[1]).expect("failed to open counter file"); let mut counter_str = String::new(); counter_file.take(100).read_to_string(&mut counter_str) .expect("failed to read counter file"); let mut counter: u32 = counter_str.trim().parse().expect("failed to parse counter"); counter += 1; let mut counter_file = File::create(&args[1]).expect("failed to create counter file"); write!(counter_file, "{}", counter).expect("failed to write counter file"); }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/spec/fixtures/component-types/src/lib.rs
spec/fixtures/component-types/src/lib.rs
#[allow(warnings)] mod bindings; use bindings::exports::resource; use bindings::Guest; use paste::paste; macro_rules! id_function { ($wasm_ty:ident, $rust_ty:ty) => { paste! { fn [<id_ $wasm_ty>](v: $rust_ty) -> $rust_ty { v } } }; } struct WrappedString(String); impl resource::GuestWrappedString for WrappedString { fn new(v: String) -> Self { Self(v) } fn to_string(&self) -> String { self.0.clone() } } struct Component; impl resource::Guest for Component { type WrappedString = WrappedString; fn resource_owned(_: resource::WrappedString) {} } impl Guest for Component { id_function!(bool, bool); id_function!(s8, i8); id_function!(u8, u8); id_function!(s16, i16); id_function!(u16, u16); id_function!(s32, i32); id_function!(u32, u32); id_function!(s64, i64); id_function!(u64, u64); id_function!(f32, f32); id_function!(f64, f64); id_function!(char, char); id_function!(string, String); id_function!(list, Vec<u32>); id_function!(record, bindings::Point); id_function!(tuple, (u32, String)); id_function!(variant, bindings::Filter); id_function!(enum, bindings::Size); id_function!(option, Option<u32>); id_function!(result, Result<u32, u32>); id_function!(flags, bindings::Permission); id_function!(result_unit, Result<(), ()>); } bindings::export!(Component with_types_in bindings);
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/spec/fixtures/wasi-debug/src/main.rs
spec/fixtures/wasi-debug/src/main.rs
use miniserde::{json, Serialize}; use std::io::{Write, Read}; #[derive(Serialize)] struct Wasi { args: Vec<String>, env: Vec<(String, String)>, pwd: String, stdin: String, } #[derive(Serialize)] struct Log<'a> { name: &'static str, wasi: &'a Wasi, } fn main() { let args: Vec<String> = std::env::args().collect(); let env: Vec<(String, String)> = std::env::vars().collect(); let pwd : String = std::env::current_dir() .expect("current working directory") .to_string_lossy() .into(); let mut stdin = String::new(); std::io::stdin().read_to_string(&mut stdin) .expect("failed to read stdin"); let wasi = Wasi {args, env, pwd, stdin }; let stdout = Log { name: "stdout", wasi: &wasi }; let stderr = Log { name: "stderr", wasi: &wasi }; std::io::stdout().write_all(json::to_string(&stdout).as_bytes()) .expect("failed to write to stdout"); std::io::stderr().write_all(json::to_string(&stderr).as_bytes()) .expect("failed to write to stderr"); }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
bytecodealliance/wasmtime-rb
https://github.com/bytecodealliance/wasmtime-rb/blob/4bd163735452f44ee6e7066516ce63595df1e29b/spec/fixtures/wasi-deterministic/src/main.rs
spec/fixtures/wasi-deterministic/src/main.rs
// In a determinisitc build, the output of this program should be the same // for every execution. // // This program generates random numbers, sleeps for 2 seconds, // and prints to stdout and stderr. // // Expected Output: // // stdout: json string with the following keys: // - Random numbers: rang1, rang2, rang3 // - UTC time before sleep: utc1 // - UTC time after sleep: utc2 // - System time before sleep: system_time1 // - System time after sleep: system_time2 // - Elapsed time: system_time1_elapsed // // stderr: "Error: This is an error message" // Import rust's io and filesystem module use chrono::{DateTime, Utc}; use rand::Rng; use serde_json; use std::collections::HashMap; use std::thread::sleep; use std::time::{Duration, SystemTime}; // Entry point to our WASI applications fn main() { // Define a dict to store our output let mut dict = HashMap::new(); // Define random numbers let mut rng = rand::thread_rng(); let n1: u32 = rng.gen(); let n2: u32 = rng.gen(); let n3: u32 = rng.gen(); dict.insert("rang1".to_string(), n1.to_string()); dict.insert("rang2".to_string(), n2.to_string()); dict.insert("rang3".to_string(), n3.to_string()); let utc1 = Utc::now(); let utc1_str = utc1.format("%+").to_string(); dict.insert("utc1".to_string(), utc1_str); // Define system time, elaspsed time let system_time1 = SystemTime::now(); let date_time1: DateTime<Utc> = system_time1.into(); let system_time_str = date_time1.format("%+"); dict.insert("system_time1".to_string(), system_time_str.to_string()); // we sleep for 2 seconds sleep(Duration::new(2, 0)); match system_time1.elapsed() { Ok(elapsed) => { // it prints '2' println!("{}", elapsed.as_secs()); dict.insert( "system_time1_elapsed".to_string(), elapsed.as_secs().to_string(), ); } Err(e) => { // an error occurred! println!("Error: {e:?}"); } } // Declare a new UTC after the pause let utc2 = Utc::now(); let utc2_str = utc2.format("%+").to_string(); dict.insert("utc2".to_string(), utc2_str); let json = serde_json::to_string(&dict).unwrap(); // write to stdout println!("{}", json); // write to stderr eprintln!("Error: {}", "This is an error message"); }
rust
Apache-2.0
4bd163735452f44ee6e7066516ce63595df1e29b
2026-01-04T20:22:01.008503Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/seismic-reth/src/main.rs
bin/seismic-reth/src/main.rs
#![allow(missing_docs)] use std::net::SocketAddr; use clap::Parser; use jsonrpsee_http_client::HttpClientBuilder; use reth::cli::Cli; use reth_cli_commands::node::NoArgs; use reth_node_core::node_config::NodeConfig; use reth_seismic_cli::chainspec::SeismicChainSpecParser; use reth_seismic_node::node::SeismicNode; use reth_seismic_rpc::ext::{EthApiExt, EthApiOverrideServer, SeismicApi, SeismicApiServer}; use reth_tracing::tracing::*; use seismic_enclave::{ api::TdxQuoteRpcClient as _, mock::start_mock_server, GetPurposeKeysResponse, }; /// Boot the enclave (or mock server) and fetch purpose keys. /// This must be called before building the node components. /// Panics if the enclave cannot be booted or purpose keys cannot be fetched. async fn boot_enclave_and_fetch_keys<ChainSpec>( config: &NodeConfig<ChainSpec>, ) -> GetPurposeKeysResponse { // Boot enclave or start mock server if config.enclave.mock_server { info!(target: "reth::cli", "Starting mock enclave server"); let addr = config.enclave.enclave_server_addr; let port = config.enclave.enclave_server_port; tokio::spawn(async move { start_mock_server(SocketAddr::new(addr, port)) .await .expect("Failed to start mock enclave server"); }); // Give the mock server time to start tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; } let enclave_client = HttpClientBuilder::default() .build(format!( "http://{}:{}", config.enclave.enclave_server_addr, config.enclave.enclave_server_port )) .expect("Failed to build enclave client"); // Fetch purpose keys from enclave - this must succeed or we panic info!(target: "reth::cli", "Fetching purpose keys from enclave"); let mut failures = 0; while failures <= config.enclave.retries { match enclave_client.get_purpose_keys(0).await { Ok(purpose_keys) => { info!(target: "reth::cli", "Successfully fetched purpose keys from enclave"); return purpose_keys; } Err(e) => { warn!(target: "reth::cli", "Failure to fetch purpose keys {}/{}: {}", failures, config.enclave.retries, e); tokio::time::sleep(tokio::time::Duration::from_secs( config.enclave.retry_seconds.into(), )) .await; failures += 1; } } } panic!("FATAL: Failed to fetch purpose keys from enclave on boot after {} failures", failures); } fn main() { // Enable backtraces unless we explicitly set RUST_BACKTRACE if std::env::var_os("RUST_BACKTRACE").is_none() { std::env::set_var("RUST_BACKTRACE", "1"); } reth_cli_util::sigsegv_handler::install(); if let Err(err) = Cli::<SeismicChainSpecParser, NoArgs>::parse().run(|builder, _| async move { // Boot enclave and fetch purpose keys BEFORE building node components let purpose_keys = boot_enclave_and_fetch_keys(builder.config()).await; // Store purpose keys in global static storage before building the node reth_seismic_node::purpose_keys::init_purpose_keys(purpose_keys.clone()); // building additional endpoints seismic api let seismic_api = SeismicApi::new(purpose_keys.clone()); let node = builder .node(SeismicNode::default()) .extend_rpc_modules(move |ctx| { // replace eth_ namespace ctx.modules.replace_configured( EthApiExt::new(ctx.registry.eth_api().clone(), purpose_keys.clone()).into_rpc(), )?; // add seismic_ namespace ctx.modules.merge_configured(seismic_api.into_rpc())?; info!(target: "reth::cli", "seismic api configured"); Ok(()) }) .launch_with_debug_capabilities() .await?; node.node_exit_future.await }) { eprintln!("Error: {err:?}"); std::process::exit(1); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/reth/src/lib.rs
bin/reth/src/lib.rs
//! Rust Ethereum (reth) binary executable. //! //! ## Feature Flags //! //! - `jemalloc`: Uses [jemallocator](https://github.com/tikv/jemallocator) as the global allocator. //! This is **not recommended on Windows**. See [here](https://rust-lang.github.io/rfcs/1974-global-allocators.html#jemalloc) //! for more info. //! - `jemalloc-prof`: Enables [jemallocator's](https://github.com/tikv/jemallocator) heap profiling //! and leak detection functionality. See [jemalloc's opt.prof](https://jemalloc.net/jemalloc.3.html#opt.prof) //! documentation for usage details. This is **not recommended on Windows**. See [here](https://rust-lang.github.io/rfcs/1974-global-allocators.html#jemalloc) //! for more info. //! - `asm-keccak`: replaces the default, pure-Rust implementation of Keccak256 with one implemented //! in assembly; see [the `keccak-asm` crate](https://github.com/DaniPopes/keccak-asm) for more //! details and supported targets //! - `min-error-logs`: Disables all logs below `error` level. //! - `min-warn-logs`: Disables all logs below `warn` level. //! - `min-info-logs`: Disables all logs below `info` level. This can speed up the node, since fewer //! calls to the logging component are made. //! - `min-debug-logs`: Disables all logs below `debug` level. //! - `min-trace-logs`: Disables all logs below `trace` level. #![doc( // TODO: seismic html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] pub mod cli; /// Re-exported utils. pub mod utils { pub use reth_db::open_db_read_only; /// Re-exported from `reth_node_core`, also to prevent a breaking change. See the comment /// on the `reth_node_core::args` re-export for more details. pub use reth_node_core::utils::*; } /// Re-exported payload related types pub mod payload { pub use reth_ethereum_payload_builder::EthereumExecutionPayloadValidator; pub use reth_payload_builder::*; pub use reth_payload_primitives::*; } /// Re-exported from `reth_node_api`. pub mod api { pub use reth_node_api::*; } /// Re-exported from `reth_node_core`. pub mod core { pub use reth_node_core::*; } /// Re-exported from `reth_node_metrics`. pub mod prometheus_exporter { pub use reth_node_metrics::recorder::*; } /// Re-export of the `reth_node_core` types specifically in the `args` module. /// /// This is re-exported because the types in `reth_node_core::args` originally existed in /// `reth::args` but were moved to the `reth_node_core` crate. This re-export avoids a breaking /// change. pub mod args { pub use reth_node_core::args::*; } /// Re-exported from `reth_node_core`, also to prevent a breaking change. See the comment on /// the `reth_node_core::args` re-export for more details. pub mod version { pub use reth_node_core::version::*; } /// Re-exported from `reth_node_builder` pub mod builder { pub use reth_node_builder::*; } /// Re-exported from `reth_node_core`, also to prevent a breaking change. See the comment on /// the `reth_node_core::args` re-export for more details. pub mod dirs { pub use reth_node_core::dirs::*; } /// Re-exported from `reth_chainspec` pub mod chainspec { pub use reth_chainspec::*; pub use reth_ethereum_cli::chainspec::*; } /// Re-exported from `reth_provider`. pub mod providers { pub use reth_provider::*; } /// Re-exported from `reth_primitives`. pub mod primitives { pub use reth_primitives::*; } /// Re-exported from `reth_ethereum_consensus`. pub mod beacon_consensus { pub use reth_node_ethereum::consensus::*; } /// Re-exported from `reth_consensus`. pub mod consensus { pub use reth_consensus::*; } /// Re-exported from `reth_consensus_common`. pub mod consensus_common { pub use reth_consensus_common::*; } /// Re-exported from `reth_revm`. pub mod revm { pub use reth_revm::*; } /// Re-exported from `reth_tasks`. pub mod tasks { pub use reth_tasks::*; } /// Re-exported from `reth_network`. pub mod network { pub use reth_network::*; pub use reth_network_api::{ noop, test_utils::PeersHandleProvider, NetworkInfo, Peers, PeersInfo, }; } /// Re-exported from `reth_transaction_pool`. pub mod transaction_pool { pub use reth_transaction_pool::*; } /// Re-export of `reth_rpc_*` crates. pub mod rpc { /// Re-exported from `reth_rpc_builder`. pub mod builder { pub use reth_rpc_builder::*; } /// Re-exported from `alloy_rpc_types`. pub mod types { pub use alloy_rpc_types::*; } /// Re-exported from `reth_rpc_server_types`. pub mod server_types { pub use reth_rpc_server_types::*; /// Re-exported from `reth_rpc_eth_types`. pub mod eth { pub use reth_rpc_eth_types::*; } } /// Re-exported from `reth_rpc_api`. pub mod api { pub use reth_rpc_api::*; } /// Re-exported from `reth_rpc::eth`. pub mod eth { pub use reth_rpc::eth::*; } /// Re-exported from `reth_rpc::rpc`. pub mod result { pub use reth_rpc_server_types::result::*; } /// Re-exported from `reth_rpc_convert`. pub mod compat { pub use reth_rpc_convert::*; } } /// Ress subprotocol installation. pub mod ress; // re-export for convenience #[doc(inline)] pub use reth_cli_runner::{tokio_runtime, CliContext, CliRunner}; // for rendering diagrams use aquamarine as _; // used in main use clap as _; use reth_cli_util as _;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/reth/src/ress.rs
bin/reth/src/ress.rs
use reth_ethereum_primitives::EthPrimitives; use reth_evm::ConfigureEvm; use reth_network::{protocol::IntoRlpxSubProtocol, NetworkProtocols}; use reth_network_api::FullNetwork; use reth_node_api::ConsensusEngineEvent; use reth_node_core::args::RessArgs; use reth_provider::providers::{BlockchainProvider, ProviderNodeTypes}; use reth_ress_protocol::{NodeType, ProtocolState, RessProtocolHandler}; use reth_ress_provider::{maintain_pending_state, PendingState, RethRessProtocolProvider}; use reth_tasks::TaskExecutor; use reth_tokio_util::EventStream; use tokio::sync::mpsc; use tracing::*; /// Install `ress` subprotocol if it's enabled. pub fn install_ress_subprotocol<P, E, N>( args: RessArgs, provider: BlockchainProvider<P>, evm_config: E, network: N, task_executor: TaskExecutor, engine_events: EventStream<ConsensusEngineEvent<EthPrimitives>>, ) -> eyre::Result<()> where P: ProviderNodeTypes<Primitives = EthPrimitives>, E: ConfigureEvm<Primitives = EthPrimitives> + Clone + 'static, N: FullNetwork + NetworkProtocols, { info!(target: "reth::cli", "Installing ress subprotocol"); let pending_state = PendingState::default(); // Spawn maintenance task for pending state. task_executor.spawn(maintain_pending_state( engine_events, provider.clone(), pending_state.clone(), )); let (tx, mut rx) = mpsc::unbounded_channel(); let provider = RethRessProtocolProvider::new( provider, evm_config, Box::new(task_executor.clone()), args.max_witness_window, args.witness_max_parallel, args.witness_cache_size, pending_state, )?; network.add_rlpx_sub_protocol( RessProtocolHandler { provider, node_type: NodeType::Stateful, peers_handle: network.peers_handle().clone(), max_active_connections: args.max_active_connections, state: ProtocolState::new(tx), } .into_rlpx_sub_protocol(), ); info!(target: "reth::cli", "Ress subprotocol support enabled"); task_executor.spawn(async move { while let Some(event) = rx.recv().await { trace!(target: "reth::ress", ?event, "Received ress event"); } }); Ok(()) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/reth/src/main.rs
bin/reth/src/main.rs
#![allow(missing_docs)] #[global_allocator] static ALLOC: reth_cli_util::allocator::Allocator = reth_cli_util::allocator::new_allocator(); use clap::Parser; use reth::{args::RessArgs, cli::Cli, ress::install_ress_subprotocol}; use reth_ethereum_cli::chainspec::EthereumChainSpecParser; use reth_node_builder::NodeHandle; use reth_node_ethereum::EthereumNode; use tracing::info; fn main() { reth_cli_util::sigsegv_handler::install(); // Enable backtraces unless a RUST_BACKTRACE value has already been explicitly provided. if std::env::var_os("RUST_BACKTRACE").is_none() { unsafe { std::env::set_var("RUST_BACKTRACE", "1") }; } if let Err(err) = Cli::<EthereumChainSpecParser, RessArgs>::parse().run(async move |builder, ress_args| { info!(target: "reth::cli", "Launching node"); let NodeHandle { node, node_exit_future } = builder.node(EthereumNode::default()).launch_with_debug_capabilities().await?; // Install ress subprotocol. if ress_args.enabled { install_ress_subprotocol( ress_args, node.provider, node.evm_config, node.network, node.task_executor, node.add_ons_handle.engine_events.new_listener(), )?; } node_exit_future.await }) { eprintln!("Error: {err:?}"); std::process::exit(1); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/reth/src/cli/mod.rs
bin/reth/src/cli/mod.rs
//! CLI definition and entrypoint to executable /// Re-export of the [`reth_node_core`] types specifically in the `cli` module. /// /// This is re-exported because the types in `reth_node_core::cli` originally existed in /// `reth::cli` but were moved to the [`reth_node_core`] crate. This re-export avoids a /// breaking change. pub use crate::core::cli::*; /// Re-export of the [`reth_ethereum_cli`] types specifically in the `interface` module. /// /// This is re-exported because the types in [`reth_ethereum_cli::interface`] originally /// existed in `reth::cli` but were moved to the [`reth_ethereum_cli`] crate. This re-export /// avoids a breaking change. pub use reth_ethereum_cli::interface::*;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/bin/reth-bench/src/valid_payload.rs
bin/reth-bench/src/valid_payload.rs
//! This is an extension trait for any provider that implements the engine API, to wait for a VALID //! response. This is useful for benchmarking, as it allows us to wait for a payload to be valid //! before sending additional calls. use alloy_eips::eip7685::Requests; use alloy_provider::{ext::EngineApi, network::AnyRpcBlock, Network, Provider}; use alloy_rpc_types_engine::{ ExecutionPayload, ExecutionPayloadInputV2, ForkchoiceState, ForkchoiceUpdated, PayloadAttributes, PayloadStatus, }; use alloy_transport::TransportResult; use op_alloy_rpc_types_engine::OpExecutionPayloadV4; use reth_node_api::EngineApiMessageVersion; use tracing::error; /// An extension trait for providers that implement the engine API, to wait for a VALID response. #[async_trait::async_trait] pub trait EngineApiValidWaitExt<N>: Send + Sync { /// Calls `engine_forkChoiceUpdatedV1` with the given [`ForkchoiceState`] and optional /// [`PayloadAttributes`], and waits until the response is VALID. async fn fork_choice_updated_v1_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated>; /// Calls `engine_forkChoiceUpdatedV2` with the given [`ForkchoiceState`] and optional /// [`PayloadAttributes`], and waits until the response is VALID. async fn fork_choice_updated_v2_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated>; /// Calls `engine_forkChoiceUpdatedV3` with the given [`ForkchoiceState`] and optional /// [`PayloadAttributes`], and waits until the response is VALID. async fn fork_choice_updated_v3_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated>; } #[async_trait::async_trait] impl<N, P> EngineApiValidWaitExt<N> for P where N: Network, P: Provider<N> + EngineApi<N>, { async fn fork_choice_updated_v1_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated> { let mut status = self.fork_choice_updated_v1(fork_choice_state, payload_attributes.clone()).await?; while !status.is_valid() { if status.is_invalid() { error!( ?status, ?fork_choice_state, ?payload_attributes, "Invalid forkchoiceUpdatedV1 message", ); panic!("Invalid forkchoiceUpdatedV1: {status:?}"); } if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", )) } status = self.fork_choice_updated_v1(fork_choice_state, payload_attributes.clone()).await?; } Ok(status) } async fn fork_choice_updated_v2_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated> { let mut status = self.fork_choice_updated_v2(fork_choice_state, payload_attributes.clone()).await?; while !status.is_valid() { if status.is_invalid() { error!( ?status, ?fork_choice_state, ?payload_attributes, "Invalid forkchoiceUpdatedV2 message", ); panic!("Invalid forkchoiceUpdatedV2: {status:?}"); } if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", )) } status = self.fork_choice_updated_v2(fork_choice_state, payload_attributes.clone()).await?; } Ok(status) } async fn fork_choice_updated_v3_wait( &self, fork_choice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated> { let mut status = self.fork_choice_updated_v3(fork_choice_state, payload_attributes.clone()).await?; while !status.is_valid() { if status.is_invalid() { error!( ?status, ?fork_choice_state, ?payload_attributes, "Invalid forkchoiceUpdatedV3 message", ); panic!("Invalid forkchoiceUpdatedV3: {status:?}"); } status = self.fork_choice_updated_v3(fork_choice_state, payload_attributes.clone()).await?; } Ok(status) } } pub(crate) fn block_to_new_payload( block: AnyRpcBlock, is_optimism: bool, ) -> eyre::Result<(EngineApiMessageVersion, serde_json::Value)> { let block = block .into_inner() .map_header(|header| header.map(|h| h.into_header_with_defaults())) .try_map_transactions(|tx| { // try to convert unknowns into op type so that we can also support optimism tx.try_into_either::<op_alloy_consensus::OpTxEnvelope>() })? .into_consensus(); // Convert to execution payload let (payload, sidecar) = ExecutionPayload::from_block_slow(&block); let (version, params) = match payload { ExecutionPayload::V3(payload) => { let cancun = sidecar.cancun().unwrap(); if let Some(prague) = sidecar.prague() { if is_optimism { ( EngineApiMessageVersion::V4, serde_json::to_value(( OpExecutionPayloadV4 { payload_inner: payload, withdrawals_root: block.withdrawals_root.unwrap(), }, cancun.versioned_hashes.clone(), cancun.parent_beacon_block_root, Requests::default(), ))?, ) } else { ( EngineApiMessageVersion::V4, serde_json::to_value(( payload, cancun.versioned_hashes.clone(), cancun.parent_beacon_block_root, prague.requests.requests_hash(), ))?, ) } } else { ( EngineApiMessageVersion::V3, serde_json::to_value(( payload, cancun.versioned_hashes.clone(), cancun.parent_beacon_block_root, ))?, ) } } ExecutionPayload::V2(payload) => { let input = ExecutionPayloadInputV2 { execution_payload: payload.payload_inner, withdrawals: Some(payload.withdrawals), }; (EngineApiMessageVersion::V2, serde_json::to_value((input,))?) } ExecutionPayload::V1(payload) => { (EngineApiMessageVersion::V1, serde_json::to_value((payload,))?) } }; Ok((version, params)) } /// Calls the correct `engine_newPayload` method depending on the given [`ExecutionPayload`] and its /// versioned variant. Returns the [`EngineApiMessageVersion`] depending on the payload's version. /// /// # Panics /// If the given payload is a V3 payload, but a parent beacon block root is provided as `None`. pub(crate) async fn call_new_payload<N: Network, P: Provider<N>>( provider: P, version: EngineApiMessageVersion, params: serde_json::Value, ) -> TransportResult<()> { let method = version.method_name(); let mut status: PayloadStatus = provider.client().request(method, &params).await?; while !status.is_valid() { if status.is_invalid() { error!(?status, ?params, "Invalid {method}",); panic!("Invalid {method}: {status:?}"); } if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", )) } status = provider.client().request(method, &params).await?; } Ok(()) } /// Calls the correct `engine_forkchoiceUpdated` method depending on the given /// `EngineApiMessageVersion`, using the provided forkchoice state and payload attributes for the /// actual engine api message call. pub(crate) async fn call_forkchoice_updated<N, P: EngineApiValidWaitExt<N>>( provider: P, message_version: EngineApiMessageVersion, forkchoice_state: ForkchoiceState, payload_attributes: Option<PayloadAttributes>, ) -> TransportResult<ForkchoiceUpdated> { match message_version { EngineApiMessageVersion::V3 | EngineApiMessageVersion::V4 | EngineApiMessageVersion::V5 => { provider.fork_choice_updated_v3_wait(forkchoice_state, payload_attributes).await } EngineApiMessageVersion::V2 => { provider.fork_choice_updated_v2_wait(forkchoice_state, payload_attributes).await } EngineApiMessageVersion::V1 => { provider.fork_choice_updated_v1_wait(forkchoice_state, payload_attributes).await } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false