Skip to content

Commit

Permalink
twine-demo: update example code
Browse files Browse the repository at this point in the history
Signed-off-by: Ralf Zerres <[email protected]>
  • Loading branch information
rzerres committed Jun 12, 2021
1 parent 037bb85 commit e3901bd
Show file tree
Hide file tree
Showing 7 changed files with 157 additions and 72 deletions.
5 changes: 4 additions & 1 deletion twine-demo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ edition = "2018"
build = "build.rs"

[dependencies]
serde = { version = "^1.0", features = ["derive"] }
serde_json = { version = "^1.0" }
substring = "1.4.5"
tracing = "0.1.25"
tracing-subscriber = "0.2.17"
twine = { version = "^0.3", features = ["serde"] }

[build-dependencies]
twine = "0.3.8"
twine = { version = "^0.3", features = ["serde"] }

[[bin]]
name = "twine-demo"
Expand Down
59 changes: 59 additions & 0 deletions twine-demo/data/demo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"_comment1": "The colour structure is an array of colour elements",
"colour": [
{
"colour_name": "black",
"category": "hue",
"colour_type": "Primary",
"code": {
"rgba": [255,255,255,1],
"hex": "000"
}
},
{
"colour_name": "white",
"category": "value",
"colour_type": "Primary",
"code": {
"rgba": [0,0,0,1],
"hex": "FFF"
}
},
{
"colour_name": "red",
"category": "hue",
"colour_type": "Primary",
"code": {
"rgba": [255,0,0,1],
"hex": "FF0"
}
},
{
"colour_name": "blue",
"category": "hue",
"colour_type": "Primary",
"code": {
"rgba": [0,0,255,1],
"hex": "00F"
}
},
{
"colour_name": "yellow",
"category": "hue",
"colour_type": "Primary",
"code": {
"rgba": [255,255,0,1],
"hex": "FF0"
}
},
{
"colour_name": "green",
"category": "hue",
"colour_type": "Secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "0F0"
}
}
]
}
18 changes: 15 additions & 3 deletions twine-demo/src/i18n/localization.ini
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
[clock_drift]
de = Uhrzeit ist eventuell rückwärts gestellt worden
en = Clock may have gone backwards
[err_lang_not_found]
de = Konnte Sprachkode nicht auslesen
en = Can not read the language code
[err_user_not_found]
de = Benutzer wurde nicht gefunden
en = User not found
[err_import_colours]
de = Import der Farbwert fehlgeschlagen
en = Error importing coulour values
[err_colour_not_found]
de = Farbwert wurde nicht gefunden
en = coulour value not found
[lang_code]
de = Sprachkode
en = language code
Expand All @@ -13,6 +19,12 @@
[main_finished]
de = Programmlogik beendet
en = Program logic finished
[import_colours]
de = Import der Farbwerte
en = import coulour values
[import_not_well_formed]
de = JSON hat nicht die erwartete Struktur
en = JSON was not well-formatted
[import_started]
de = Import aus einer Datei
en = Import from a file
Expand Down
42 changes: 18 additions & 24 deletions twine-demo/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,27 @@
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]

use std::env;
use std::process;
//use substring::Substring;
use std::time::SystemTime;
use tracing::{error, trace, Level};
use tracing::{trace, Level};
use tracing_subscriber::fmt;

// get the macro (t!) accessing the internationalization strings
include!(concat!(env!("OUT_DIR"), "/i18n.rs"));

pub mod services;

use crate::services::imports::twine_import;
use crate::services::imports::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
// initialize the tracing subsystem
let span = tracing::span!(Level::TRACE, "wip_twine");
let _enter = span.enter();
let collector = fmt::Subscriber::builder()
//.with_env_filter("trace")
.with_max_level(tracing::Level::TRACE)
.finish();

// start tracing thread
tracing::subscriber::with_default(collector, || {
// get system environment
//let mut lang = env::var("LANG").unwrap_or_else(|_| "en".to_string());
//let lang_culture = lang.substring(3,4).to_string(); // "de_DE.UTF-8" -> "DE"
//let lang_family = lang.substring(0,2).to_string(); // "de_DE.UTF-8" -> "de"
//lang = format!{"Lang::{}(\"{}\")", &lang_culture, &lang_family};
//println!{"lang: {}", &lang};

// include localization strings
let lang = Lang::De("de");
let mut state = t!(state_started => lang);
Expand All @@ -40,20 +32,22 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
trace!(target: "twine-demo", state = ?state,
res = ? res, time = ?time_start);

let mut import_path = concat!(env!("OUT_DIR"), "/i18n.rs").to_string();
match twine_import::import(&mut import_path, &lang) {
Ok(duration) => {
trace!(target: "twine-demo", import_path = ?import_path,
duration = ?&duration);
}
Err(err) => {
error!("error running import: {}", err);
process::exit(1);
}
};
match json_import::read_colours("data/demo.json") {
Ok(colours) => {
println!("We got {} colour elements", colours.colour.iter().count());
for (pos, e) in colours.colour.iter().enumerate() {
println!("Element {}: colour name={:?}, rgba-value={:?}", pos, e.colour_name, e.code.rgba);
}
},
Err(e) => {
println!("Error: {}!", e);
res = t!(err_import_colours => lang);
println!("Error: {}!", res);
},
}

state = t!(state_finished => lang);
res = t!(err_user_not_found => lang);
res = t!(import_colours => lang);

// localized feedback
let time_end = SystemTime::now();
Expand Down
59 changes: 59 additions & 0 deletions twine-demo/src/services/imports/json_import.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use serde::Deserialize;
use serde_json::Result;
use std::{
fs::File,
io::BufReader,
path::Path,
};

// Valid color types
#[derive(Debug, Deserialize, PartialEq)]
pub enum Type {
/// Primery colour
Primary,
/// Secondary colour
Secondary,
}

impl Default for Type {
fn default() -> Self { Type::Primary }
}

// Color codes structure
#[derive(Debug, Deserialize, PartialEq)]
pub struct Code {
/// Color code as an rgba array
pub rgba: Vec<u8>,
/// Color code as a hex value
pub hex: String,
}

// The colour structure
#[derive(Debug, Deserialize, PartialEq)]
pub struct Colour {
pub colour_name: String,
pub category: String,
pub colour_type: Type,
pub code: Code,
}

// The colours structure
#[derive(Debug, Deserialize, PartialEq)]
pub struct Colours {
pub colour: Vec<Colour>,
}

pub fn read_colours<P>(path: P) -> Result<Colours>
where
P: AsRef<Path>,
{
// Open the file in read-only mode with buffer
let file = File::open(path).unwrap();
let reader = BufReader::new(file);

// Read the JSON contents of the file as an instance of `Colours`.
let colours: Colours = serde_json::from_reader(reader)?;

// Return the `Colours` structure
Ok(colours)
}
4 changes: 2 additions & 2 deletions twine-demo/src/services/imports/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/// test import service
pub mod twine_import;
/// json import service
pub mod json_import;
42 changes: 0 additions & 42 deletions twine-demo/src/services/imports/twine_import.rs

This file was deleted.

0 comments on commit e3901bd

Please sign in to comment.