Skip to content

Commit

Permalink
Merge pull request #3 from erhanbaris/development
Browse files Browse the repository at this point in the history
Issue #1
  • Loading branch information
erhanbaris authored Feb 18, 2022
2 parents 76910bb + 4b69883 commit bb204ce
Show file tree
Hide file tree
Showing 26 changed files with 207 additions and 215 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ serde = { version = "1.0", default-features = false }
serde_derive = "1.0.123"

log = { version = "0.4.14", default-features = false }
num-format = { version = "0.4", features = ["with-system-locale"] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
hyper = { version = "0.14", features = ["full"] }
Expand Down
6 changes: 3 additions & 3 deletions assets/www/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "smartcalc",
"version": "1.0.0",
"version": "1.0.1",
"description": "",
"main": "main.js",
"devDependencies": {
Expand All @@ -12,8 +12,8 @@
"start": "electron .",
"gen": "electron-packager .",
"pack:osx": "electron-packager . $npm_package_productName --app-version=$npm_package_version --out=dist/osx --platform=darwin --prune=true --arch=x64 --icon=build/icon.icns",
"pack:win32": "electron-packager . $npm_package_productName --out=dist/win --platform=win32 --arch=ia3 --icon=build/icon.png",
"pack:win64": "electron-packager . $npm_package_productName --out=dist/win --platform=win32 --arch=x64 --version=0.36.2 app-version=1.0 --icon=assets/build/win/icon.ico"
"pack:win32": "electron-packager . $npm_package_productName --out=dist/win --platform=win32 --arch=ia3",
"pack:win64": "electron-packager . $npm_package_productName --out=dist/win --platform=win32 --arch=x64 --app-version=$npm_package_version"
},
"author": "",
"license": "GNU GENERAL PUBLIC LICENSE"
Expand Down
29 changes: 27 additions & 2 deletions assets/www/src/js/code.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,35 @@ function makeMarker(msg) {
return marker;
}

function getNumberSeparators() {

// default
var res = {
"decimal": ".",
"thousand": ""
};

// convert a number formatted according to locale
var str = parseFloat(1234.56).toLocaleString();

// if the resulting number does not contain previous number
// (i.e. in some Arabic formats), return defaults
if (!str.match("1"))
return res;

// get decimal and thousand separators
res.decimal = str.replace(/.*4(.*)5.*/, "$1");
res.thousand = str.replace(/.*1(.*)2.*/, "$1");

// return results
return res;
}

await init('./src/js/libsmartcalc_bg.wasm');
const calculator = SmartCalcWeb.default();
const separators = getNumberSeparators();
const calculator = SmartCalcWeb.default(separators.decimal, separators.thousand);

var app = new Vue({
new Vue({
el: '#app',
data: function() {
return {
Expand Down
65 changes: 40 additions & 25 deletions assets/www/src/js/libsmartcalc.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,15 @@ function addBorrowedObject(obj) {
return stack_pointer;
}

function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
function handleError(f) {
return function () {
try {
return f.apply(this, arguments);

} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
};
}
/**
*/
Expand All @@ -217,20 +220,32 @@ export class SmartCalcWeb {
wasm.__wbg_smartcalcweb_free(ptr);
}
/**
* @param {string} decimal_seperator
* @param {string} thousand_separator
* @returns {SmartCalcWeb}
*/
static default() {
var ret = wasm.smartcalcweb_default();
static default(decimal_seperator, thousand_separator) {
var ptr0 = passStringToWasm0(decimal_seperator, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passStringToWasm0(thousand_separator, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
var ret = wasm.smartcalcweb_default(ptr0, len0, ptr1, len1);
return SmartCalcWeb.__wrap(ret);
}
/**
* @param {string} json_data
* @param {string} decimal_seperator
* @param {string} thousand_separator
* @returns {SmartCalcWeb}
*/
static load_from_json(json_data) {
static load_from_json(json_data, decimal_seperator, thousand_separator) {
var ptr0 = passStringToWasm0(json_data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.smartcalcweb_load_from_json(ptr0, len0);
var ptr1 = passStringToWasm0(decimal_seperator, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
var ptr2 = passStringToWasm0(thousand_separator, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len2 = WASM_VECTOR_LEN;
var ret = wasm.smartcalcweb_load_from_json(ptr0, len0, ptr1, len1, ptr2, len2);
return SmartCalcWeb.__wrap(ret);
}
/**
Expand Down Expand Up @@ -264,6 +279,7 @@ export class SmartCalcWeb {

async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {

if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
Expand All @@ -282,6 +298,7 @@ async function load(module, imports) {
return await WebAssembly.instantiate(bytes, imports);

} else {

const instance = await WebAssembly.instantiate(module, imports);

if (instance instanceof WebAssembly.Instance) {
Expand Down Expand Up @@ -310,38 +327,38 @@ async function init(input) {
var ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbg_new_fc8ee963685ada41 = function() {
imports.wbg.__wbg_new_1abc33d4f9ba3e80 = function() {
var ret = new Array();
return addHeapObject(ret);
};
imports.wbg.__wbg_new_ffb8fbe0ad5d4d2f = function() {
var ret = new Object();
return addHeapObject(ret);
};
imports.wbg.__wbg_push_ef0a52724cfe2a05 = function(arg0, arg1) {
imports.wbg.__wbg_push_44968dcdf4cfbb43 = function(arg0, arg1) {
var ret = getObject(arg0).push(getObject(arg1));
return ret;
};
imports.wbg.__wbg_apply_fd3ddfda5a572c18 = function() { return handleError(function (arg0, arg1, arg2) {
imports.wbg.__wbg_apply_10929ee91ab4232a = handleError(function(arg0, arg1, arg2) {
var ret = getObject(arg0).apply(getObject(arg1), getObject(arg2));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_getTime_f3eeeeabe6c35f9a = function(arg0) {
});
imports.wbg.__wbg_getTime_6e1051297e199ada = function(arg0) {
var ret = getObject(arg0).getTime();
return ret;
};
imports.wbg.__wbg_getTimezoneOffset_a1875382531079bf = function(arg0) {
imports.wbg.__wbg_getTimezoneOffset_98f9d354772d45bf = function(arg0) {
var ret = getObject(arg0).getTimezoneOffset();
return ret;
};
imports.wbg.__wbg_new0_43142faea9f41977 = function() {
imports.wbg.__wbg_new0_1dc5063f3422cdfe = function() {
var ret = new Date();
return addHeapObject(ret);
};
imports.wbg.__wbg_set_c7fc8735d70ceb11 = function() { return handleError(function (arg0, arg1, arg2) {
imports.wbg.__wbg_new_dc5b27cfd2149b8f = function() {
var ret = new Object();
return addHeapObject(ret);
};
imports.wbg.__wbg_set_3afd31f38e771338 = handleError(function(arg0, arg1, arg2) {
var ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));
return ret;
}, arguments) };
});
imports.wbg.__wbg_new_59cb74e423758ede = function() {
var ret = new Error();
return addHeapObject(ret);
Expand Down Expand Up @@ -375,8 +392,6 @@ async function init(input) {
input = fetch(input);
}



const { instance, module } = await load(await input, imports);

wasm = instance.exports;
Expand Down
Binary file modified assets/www/src/js/libsmartcalc_bg.wasm
Binary file not shown.
2 changes: 1 addition & 1 deletion assets/www/src/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"collaborators": [
"Erhan BARIS <[email protected]>"
],
"version": "0.1.0",
"version": "1.0.1",
"files": [
"libsmartcalc_bg.wasm",
"libsmartcalc.js"
Expand Down
2 changes: 1 addition & 1 deletion libsmartcalc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "libsmartcalc"
version = "0.1.0"
version = "1.0.1"
authors = ["Erhan BARIS <[email protected]>"]
edition = "2018"

Expand Down
2 changes: 1 addition & 1 deletion libsmartcalc/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl Session {
}

pub struct SmartCalc {
config: SmartCalcConfig
pub config: SmartCalcConfig
}

impl Default for SmartCalc {
Expand Down
4 changes: 2 additions & 2 deletions libsmartcalc/src/compiler/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ impl DataItem for MemoryItem {
fn get_underlying_number(&self) -> f64 { self.0 as f64 }
fn type_name(&self) -> &'static str { "MEMORY" }
fn type_id(&self) -> TypeId { TypeId::of::<Self>() }
fn print(&self, _: &SmartCalcConfig, _: &RefCell<Session>) -> String {
fn print(&self, config: &SmartCalcConfig, _: &RefCell<Session>) -> String {

let formated_number = format_number(self.0, ".".to_string(), ",".to_string(), 2, true, true);
let formated_number = format_number(self.0, config.thousand_separator.to_string(), config.decimal_seperator.to_string(), 2, true, true);
match self.1 {
MemoryType::Byte => format!("{}B", formated_number),
MemoryType::KiloByte => format!("{}KB", formated_number),
Expand Down
22 changes: 11 additions & 11 deletions libsmartcalc/src/compiler/money.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ impl DataItem for MoneyItem {
fn get_underlying_number(&self) -> f64 { self.0 }
fn type_name(&self) -> &'static str { "MONEY" }
fn type_id(&self) -> TypeId { TypeId::of::<MoneyItem>() }
fn print(&self, _: &SmartCalcConfig, _: &RefCell<Session>) -> String {
fn print(&self, config: &SmartCalcConfig, _: &RefCell<Session>) -> String {
let currency = self.get_currency();
let formated_price = format_number(self.get_price(), currency.thousands_separator.to_string(), currency.decimal_separator.to_string(), currency.decimal_digits, false, true);
let formated_price = format_number(self.get_price(), config.thousand_separator.to_string(), config.decimal_seperator.to_string(), currency.decimal_digits, false, true);
match (currency.symbol_on_left, currency.space_between_amount_and_symbol) {
(true, true) => format!("{} {}", currency.symbol, formated_price),
(true, false) => format!("{}{}", currency.symbol, formated_price),
Expand Down Expand Up @@ -128,12 +128,12 @@ fn format_result_test() {
let uzs = config.get_currency("uzs".to_string()).unwrap();
let uyu = config.get_currency("uyu".to_string()).unwrap();

assert_eq!(MoneyItem(0.0, usd.clone()).print(&config, &session), "$0.00".to_string());
assert_eq!(MoneyItem(0.05555, usd.clone()).print(&config, &session), "$0.06".to_string());
assert_eq!(MoneyItem(123.05555, usd.clone()).print(&config, &session), "$123.06".to_string());
assert_eq!(MoneyItem(1234.05555, usd.clone()).print(&config, &session), "$1,234.06".to_string());
assert_eq!(MoneyItem(123456.05555, usd.clone()).print(&config, &session), "$123,456.06".to_string());
assert_eq!(MoneyItem(123456.0, usd.clone()).print(&config, &session), "$123,456.00".to_string());
assert_eq!(MoneyItem(0.0, usd.clone()).print(&config, &session), "$0,00".to_string());
assert_eq!(MoneyItem(0.05555, usd.clone()).print(&config, &session), "$0,06".to_string());
assert_eq!(MoneyItem(123.05555, usd.clone()).print(&config, &session), "$123,06".to_string());
assert_eq!(MoneyItem(1234.05555, usd.clone()).print(&config, &session), "$1.234,06".to_string());
assert_eq!(MoneyItem(123456.05555, usd.clone()).print(&config, &session), "$123.456,06".to_string());
assert_eq!(MoneyItem(123456.0, usd.clone()).print(&config, &session), "$123.456,00".to_string());

assert_eq!(MoneyItem(0.0, tl.clone()).print(&config, &session), "₺0,00".to_string());
assert_eq!(MoneyItem(0.05555, tl.clone()).print(&config, &session), "₺0,06".to_string());
Expand All @@ -145,9 +145,9 @@ fn format_result_test() {
assert_eq!(MoneyItem(0.0, uzs.clone()).print(&config, &session), "0,00 сўм".to_string());
assert_eq!(MoneyItem(0.05555, uzs.clone()).print(&config, &session), "0,06 сўм".to_string());
assert_eq!(MoneyItem(123.05555, uzs.clone()).print(&config, &session), "123,06 сўм".to_string());
assert_eq!(MoneyItem(1234.05555, uzs.clone()).print(&config, &session), "1 234,06 сўм".to_string());
assert_eq!(MoneyItem(123456.05555, uzs.clone()).print(&config, &session), "123 456,06 сўм".to_string());
assert_eq!(MoneyItem(123456.0, uzs.clone()).print(&config, &session), "123 456,00 сўм".to_string());
assert_eq!(MoneyItem(1234.05555, uzs.clone()).print(&config, &session), "1.234,06 сўм".to_string());
assert_eq!(MoneyItem(123456.05555, uzs.clone()).print(&config, &session), "123.456,06 сўм".to_string());
assert_eq!(MoneyItem(123456.0, uzs.clone()).print(&config, &session), "123.456,00 сўм".to_string());

assert_eq!(MoneyItem(0.0, uyu.clone()).print(&config, &session), "$U 0,00".to_string());
assert_eq!(MoneyItem(0.05555, uyu.clone()).print(&config, &session), "$U 0,06".to_string());
Expand Down
2 changes: 1 addition & 1 deletion libsmartcalc/src/compiler/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl DataItem for NumberItem {
fn get_underlying_number(&self) -> f64 { self.0 }
fn type_name(&self) -> &'static str { "NUMBER" }
fn type_id(&self) -> TypeId { TypeId::of::<NumberItem>() }
fn print(&self, _: &SmartCalcConfig, _: &RefCell<Session>) -> String { format_number(self.0, ".".to_string(), ",".to_string(), 3, true, true) }
fn print(&self, config: &SmartCalcConfig, _: &RefCell<Session>) -> String { format_number(self.0, config.thousand_separator.to_string(), config.decimal_seperator.to_string(), 2, true, true) }
fn unary(&self, unary: UnaryType) -> Arc<dyn DataItem> {
match unary {
UnaryType::Minus => Arc::new(Self(-1.0 * self.0)),
Expand Down
2 changes: 1 addition & 1 deletion libsmartcalc/src/compiler/percent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl DataItem for PercentItem {
fn get_underlying_number(&self) -> f64 { self.0 }
fn type_name(&self) -> &'static str { "PERCENT" }
fn type_id(&self) -> TypeId { TypeId::of::<PercentItem>() }
fn print(&self, _: &SmartCalcConfig, _: &RefCell<Session>) -> String { format!("%{:}", format_number(self.0, ".".to_string(), ",".to_string(), 2, true, true)) }
fn print(&self, config: &SmartCalcConfig, _: &RefCell<Session>) -> String { format!("%{:}", format_number(self.0, config.thousand_separator.to_string(), config.decimal_seperator.to_string(), 2, true, true)) }
fn unary(&self, unary: UnaryType) -> Arc<dyn DataItem> {
match unary {
UnaryType::Minus => Arc::new(Self(-1.0 * self.0)),
Expand Down
8 changes: 6 additions & 2 deletions libsmartcalc/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ pub struct SmartCalcConfig {
pub alias_regex: Vec<(Regex, String)>,
pub rule: LanguageData<RuleItemList>,
pub month_regex: LanguageData<MonthItemList>,
pub numeric_notation: LanguageData<JsonFormat>
pub numeric_notation: LanguageData<JsonFormat>,
pub decimal_seperator: String,
pub thousand_separator: String
}

impl Default for SmartCalcConfig {
Expand Down Expand Up @@ -65,7 +67,9 @@ impl SmartCalcConfig {
rule: LanguageData::new(),
month_regex: LanguageData::new(),
numeric_notation: LanguageData::new(),
alias_regex: Vec::new()
alias_regex: Vec::new(),
decimal_seperator: ",".to_string(),
thousand_separator: ".".to_string()
};

for (name, currency) in config.json_data.currencies.iter() {
Expand Down
16 changes: 0 additions & 16 deletions libsmartcalc/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,6 @@ pub enum NumberNotationType {
Sextillion = 7,
}

impl NumberNotationType {
pub fn from_u8(number: u8) -> Option<Self> {
match number {
0 => Some(NumberNotationType::None),
1 => Some(NumberNotationType::Thousand),
2 => Some(NumberNotationType::Million),
3 => Some(NumberNotationType::Billion),
4 => Some(NumberNotationType::Trillion),
5 => Some(NumberNotationType::Quadrillion),
6 => Some(NumberNotationType::Quintillion),
7 => Some(NumberNotationType::Sextillion),
_ => None,
}
}
}

impl ConstantType {
pub fn from_u8(number: u8) -> Option<Self> {
match number {
Expand Down
4 changes: 2 additions & 2 deletions libsmartcalc/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ fn format_result_test() {

let session = RefCell::new(Session::default());
session.borrow_mut().set_language("en".to_string());
assert_eq!(NumberItem(123456.123456789).print(&config, &session), "123.456,123".to_string());
assert_eq!(NumberItem(1.123456789).print(&config, &session), "1,123".to_string());
assert_eq!(NumberItem(123456.123456789).print(&config, &session), "123.456,12".to_string());
assert_eq!(NumberItem(1.123456789).print(&config, &session), "1,12".to_string());

assert_eq!(format_result(&config, &session, Rc::new(BramaAstType::Item(Arc::new(TimeItem(NaiveTime::from_hms(11, 30, 0)))))), "11:30:00".to_string());
assert_eq!(format_result(&config, &session, Rc::new(BramaAstType::Item(Arc::new(TimeItem(NaiveTime::from_hms(0, 0, 0)))))), "00:00:00".to_string());
Expand Down
4 changes: 0 additions & 4 deletions libsmartcalc/src/json/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,6 @@
"carpi": "[OPERATOR:*]",
"çarp": "[OPERATOR:*]",
"carp": "[OPERATOR:*]",
"x": "[OPERATOR:*]",
"×": "[OPERATOR:*]",
"ekle": "[OPERATOR:+]",
"topla": "[OPERATOR:+]",
"toplam": "[OPERATOR:+]",
Expand Down Expand Up @@ -432,8 +430,6 @@
"alias": {
"times": "[OPERATOR:*]",
"multiply": "[OPERATOR:*]",
"x": "[OPERATOR:*]",
"×": "[OPERATOR:*]",
"add": "[OPERATOR:+]",
"sum": "[OPERATOR:+]",
"append": "[OPERATOR:+]",
Expand Down
4 changes: 2 additions & 2 deletions libsmartcalc/src/tokinizer/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ use crate::tokinizer::Tokinizer;
use regex::Regex;
use crate::token::ui_token::{UiTokenType};

pub fn memory_regex_parser(_: &SmartCalcConfig, tokinizer: &mut Tokinizer, group_item: &[Regex]) {
pub fn memory_regex_parser(config: &SmartCalcConfig, tokinizer: &mut Tokinizer, group_item: &[Regex]) {
for re in group_item.iter() {
for capture in re.captures_iter(&tokinizer.data.to_owned().to_lowercase()) {
let memory_type = match MemoryType::from(&capture.name("TYPE").unwrap().as_str().to_lowercase()[..]) {
Some(memory_type) => memory_type,
None =>MemoryType::Byte
};

if tokinizer.add_token_location(capture.get(0).unwrap().start(), capture.get(0).unwrap().end(), Some(TokenType::Memory(capture.name("NUMBER").unwrap().as_str().replace(",", ".").parse::<f64>().unwrap(), memory_type)), capture.get(0).unwrap().as_str().to_string()) {
if tokinizer.add_token_location(capture.get(0).unwrap().start(), capture.get(0).unwrap().end(), Some(TokenType::Memory(capture.name("NUMBER").unwrap().as_str().replace(&config.thousand_separator[..], "").replace(&config.decimal_seperator[..], ".").parse::<f64>().unwrap(), memory_type)), capture.get(0).unwrap().as_str().to_string()) {
tokinizer.ui_tokens.add_from_regex_match(capture.name("NUMBER"), UiTokenType::Number);
tokinizer.ui_tokens.add_from_regex_match(capture.name("FULL_TYPE"), UiTokenType::Text);
}
Expand Down
Loading

0 comments on commit bb204ce

Please sign in to comment.