diff --git a/tsulip/.gitignore b/tsulip/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/tsulip/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/tsulip/LICENSE b/tsulip/LICENSE new file mode 100644 index 0000000..4dc3674 --- /dev/null +++ b/tsulip/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Yoxem + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tsulip/README.md b/tsulip/README.md new file mode 100644 index 0000000..7dbe4dd --- /dev/null +++ b/tsulip/README.md @@ -0,0 +1,6 @@ +# tsulip +a little typesetter. + +**The webpage has been moved to there:** + - [repo](https://git.kianting.info/?p=archivesOfToyLang;a=summary) + - [site](https://kianting.info/wiki/w/Project:ArchivesOfToyLang) diff --git a/tsulip/TODO b/tsulip/TODO new file mode 100644 index 0000000..7bfef18 --- /dev/null +++ b/tsulip/TODO @@ -0,0 +1,2 @@ +1. Token->Parser +2. main.rs 下面的「如何顯示文字於pdf的問題」 \ No newline at end of file diff --git a/tsulip/src/main.rs b/tsulip/src/main.rs new file mode 100644 index 0000000..2a059b0 --- /dev/null +++ b/tsulip/src/main.rs @@ -0,0 +1,213 @@ +extern crate pango; +extern crate cairo; +use std::env; +use regex::Regex; +use std::collections::HashMap; +use std::fs; +use clap::{Arg, App}; + +mod pdf_interface; + +/* +ls = ["(", "3", ")", "1", ")"] + + +def consume(ls): + return ls[1:] + +def parse(): + global ls + if ls[0] == "(": + ls = consume(ls) + a = [] + print(ls) + while ls[0] != ")": + b = parse() + a.append(b) + ls = consume(ls) + return a + else: + + a = ls[0] + ls = consume(ls) + return a +g = parse() +if ls != []: + print("Unexpected right parenthesis ).") +*/ + +/* +mod author; +use author::* */ + +/// DataToken store the tokenized data. +/// - line_no : num of line +/// - col_no : num of col +/// - text : text as string +#[derive(Debug)] +struct DataToken{ + text: String, + line_no: i32, + col_no: i32, +} + +/// DatatokenAST - Storing Data token AST. +/// Node -> for a node +/// Tree -> for a subtree +enum DataTokenAST { + Node(DataToken), + Tree(Vec), + +} + +fn tokenizer(data: String) -> Vec{ + // pattern list. int, float, parenthesis left and right, spaces, identifier, and string + let pattern_list = vec!["\\d+", "\\d+[.]\\d+", "[(]", "[)]", "[ \t\n]", "[^() \t]+", "\"([ \t]|[^\\\\]|\\\\)*\""]; + let joined_string = pattern_list.join("|"); // join the string. + let regex_string = format!(r"({})", joined_string); + let re_pattern = Regex::new(®ex_string).unwrap(); + + let mut token_list : Vec = vec![]; + + let mut line_no = 1; + let mut col_no: i32 = 1; + for cap in re_pattern.captures_iter(&data) { + let text = &cap[0]; + let mut text_length: i32 = (text.chars().count()) as i32; + println!("Month: {}", &cap[0]); + let data_token = DataToken{text : (text.to_string()), line_no: line_no, col_no:col_no}; + token_list.push(data_token); + + if text == "\n"{ + col_no = 1; + line_no += 1; + }else{ + col_no += text_length; + } + + } + + return token_list; +} + +/// parsing the token to let it be a AST. +/// - data_token_list : the list of tokens. +/// return DataTokenAST. +fn token_parser(data_token_list : Vec){ + // remove the spaces + let data_token_list_remove_space = data_token_list + .iter().filter(| x|{ + if (vec!["\n", "\t", " "].contains(&(x.text.as_str()))) + {return false;} + {return true;}}); + println!("{:?}", data_token_list_remove_space); +} + +/// +/// main function. +fn main() { + + // version number of the typesetter. + let version_num = "0.0.1"; + + // input command line + let args_matches = App::new("tsulip") + .version(version_num) + .author("Yoxem ") + .about("A litter typesetter.") + .arg(Arg::with_name("input") + .short("i") + .long("input") + .takes_value(true) + .help("input filepath")) + .arg(Arg::with_name("output") + .short("o") + .long("output") + .takes_value(true) + .help("destination pdf output.")) + .get_matches(); + + + + + let mut input_file_path_raw = args_matches.values_of_lossy("input"); + + let mut input_file_path = "".to_string(); + + match input_file_path_raw { + Some(x) => input_file_path = x[0].clone(), + None => {println!("missing input path."); std::process::exit(1) ;} + } + + let input_file_path_pattern = Regex::new(r"^(.+)[.]tsu$").unwrap(); + + // if file name unmatched, shoew the error: + if !(input_file_path_pattern.is_match(&input_file_path)){ + println!("the file_name {} doesn't match the pattern. It should be \".tsu\".", input_file_path); + std::process::exit(1) ; + } + + let data = fs::read_to_string(input_file_path.clone()).expect((format!("Error: unable to read the file in {}", input_file_path)).as_str()); + + let tokenized = tokenizer(data); + + + + + + + + + // destination of the pdf. + let default_output_pdf_path = format!("{}{}", &input_file_path[0..input_file_path.chars().count()-3], "pdf"); + + let mut output_pdf_path_raw = args_matches.values_of_lossy("output") + .unwrap_or(vec![default_output_pdf_path.to_string()]); + let output_pdf_path = &output_pdf_path_raw[0]; + + let pdf_size = "a4"; + + let mut size_table = HashMap::new(); + + // + // pepersize -> px (w, h) comparison table + size_table.insert("a4", [595.0, 842.0]); + + // setting pdf_size. + let mut pdf_width = 595.0; + let mut pdf_height = 842.0; + if !size_table.contains_key(pdf_size){ + println!("the size {} is unfound. using a4 size.", pdf_size);} + else{ + pdf_width = size_table[pdf_size][0]; + pdf_height = size_table[pdf_size][1]; + } + + println!("{}", pdf_width); + + // create page. + let surface = cairo::PdfSurface::new(110.0, 110.0, "/tmp/a.pdf").expect("Couldn't create surface!"); + let ctx = cairo::Context::new(&surface).expect("running error"); + ctx.scale(110.0, 110.0); // Normalizing the canvas + + ctx.set_source_rgba(0.8, 1.0, 1.0, 0.5); // 設定顏色 + ctx.paint().ok();// 設定背景顏色 + ctx.save(); + + /* + let string = "愛".to_string(); + let x = 100.0; + let y = 100.0; + let font_family = "Noto Sans CJK TC".to_string(); + let font_style = "".to_string(); + let font_weight = "".to_string(); + let color = "#ffffff".to_string(); + */ + // pdf_interface::put_chars(string, x, y , font_family, font_style, font_weight, color, &cxt); + + + + std::process::exit(0) ; +} + + diff --git a/tsulip/src/pdf_interface.rs b/tsulip/src/pdf_interface.rs new file mode 100644 index 0000000..df441d0 --- /dev/null +++ b/tsulip/src/pdf_interface.rs @@ -0,0 +1,75 @@ +extern crate pango; +extern crate cairo; +use pangocairo; + +/// convert font_style string to Style class +/// - font_style : Nommal, Oblique, Italic, or omitted as string. +fn convert_string_to_font_style(font_style_str : String)->pango::Style{ + if font_style_str == "" || font_style_str == "Normal"{ + return pango::Style::Normal; + }else if font_style_str == "Oblique"{ + return pango::Style::Oblique; + }else if font_style_str == "Italic"{ + return pango::Style::Italic; + }else { + println!("the font-style is illegal: {}, set to Normal", font_style_str); + return pango::Style::Normal; + } + +} + +/// convert font_weight string to Weight class +/// - font_style : Thin, Ultralight, Light, Semilight, Book, +/// Normal, Medium, Semibold, Bold, Ultrabold, Heavy, +/// Ultraheavy, or omitted as string. +fn convert_string_to_font_weight(font_weight_str : String)->pango::Weight{ + match font_weight_str.as_str(){ + "" => pango::Weight::Normal, + "Normal" => pango::Weight::Normal, + "Thin" => pango::Weight::Thin, + "Ultralight" => pango::Weight::Ultralight, + "Light" => pango::Weight::Light, + "Semilight" => pango::Weight::Semilight, + "Book" => pango::Weight::Book, + "Medium" => pango::Weight::Medium, + "Semibold" => pango::Weight::Semibold, + "Bold" => pango::Weight::Bold, + "Ultrabold" => pango::Weight::Ultrabold, + "Heavy" => pango::Weight::Heavy, + "Ultraheavy" => pango::Weight::Ultraheavy, + _ => {println!("the font-weight is illegal: {}, set to Normal", font_weight_str); pango::Weight::Normal} + + } + +} + + +/// put chars to the pdf +/// - x = position from left in px +/// - y = position from bottom in px +pub(crate) fn put_chars(text : String, x : f64, y : f64 , font_family : String, + font_style_str : String, font_weight_str : String, color : String, context: &cairo::Context){ + let mut font = pango::FontDescription::new(); + font.set_family(font_family.as_str()); + + let font_style = convert_string_to_font_style(font_style_str); + font.set_style(font_style); + + let weight = convert_string_to_font_weight(font_weight_str); + font.set_weight(weight); + + println!("{:?}", font); + + let fontmap = pangocairo::FontMap::default().unwrap(); + let pango_context = pango::Context::new(); + let pango_layout = pango::Layout::new(&pango_context); + pango_context.set_font_map(&fontmap); + pango_layout.set_font_description(Some(&font)); + pango_layout.set_text(text.as_str()); + + + context.move_to(x, y); + pangocairo::show_layout(&context, &pango_layout); + // context.save(); + +} \ No newline at end of file diff --git a/tsulip/test.pdf b/tsulip/test.pdf new file mode 100644 index 0000000..9a675e2 Binary files /dev/null and b/tsulip/test.pdf differ diff --git a/tsulip/test.tsu b/tsulip/test.tsu new file mode 100644 index 0000000..e55e57d --- /dev/null +++ b/tsulip/test.tsu @@ -0,0 +1,22 @@ +(% 建立網格 ) + +(create-page "a4") + + +(create-frame 1 "main1" 100 100 400 500 "main2") + +(define page-num 0) +(define add-page (lambda () (begin (new-page)(set! page-num (+ page-num 1)) (create-frame page-num 100 100 400 500 (str-append "main" (+ page-num 1)))) + +(define font_color "#ffffff") +(define font_size 10) +(define font_style "Italic") +(define font_family "Noto Sans CJK TC") +(define font_weight "Bold") +(define old_var "") + +(define frame_1_text (string-append "願您們平安。" (void_to_empty_str (set! font_size 12)) "Peace upon you.")) + +(text_to_box) + +(input_boxes (1 "1st") frame_1_text)