Skip to content

Commit

Permalink
initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
tukinami committed Jun 27, 2023
0 parents commit 0dc8359
Show file tree
Hide file tree
Showing 17 changed files with 1,393 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "i686-pc-windows-msvc"
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
/Cargo.lock
33 changes: 33 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[package]
name = "saori-pie-chart"
version = "1.0.0"
edition = "2021"
authors = [ "tukinami seika" ]
license = "MIT"
readme = "README.md"
description = "SAORI to create pie chart png image."

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
svg-pie-chart = { git = "https://github.com/tukinami/svg-pie-chart.git" }
resvg = { version = "0.31.1", default-features = false, features = [ "text", "system-fonts" ] }
png = "0.17.8"

[target.'cfg(windows)'.dependencies]
winapi = {version = "0.3.9", features = ["winbase", "libloaderapi", "stringapiset"]}

[dev-dependencies]
tempfile = "3.3.0"
encoding_rs = "0.8.31"

[lib]
name = "piechart"
path = "src/lib.rs"
crate-type = ["rlib", "cdylib"]

[profile.release]
strip = true
opt-level = "z"
lto = true
codegen-units = 1
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 月波 清火

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.
112 changes: 112 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# SAORI pie chart

[GitHub repository](https://github.com/tukinami/saori-pie-chart)

## これは何?

デスクトップマスコット、「伺か」で使用できるSAORIの一種です。

円グラフを作成し、pngとして出力します。

「伺か」「SAORI」等の用語については詳しく説明いたしませんのでご了承下さい。

## 使い方

SAORI自体の使い方は、使用するSHIORIなどによって異なりますので、ご自身でお調べ下さい。

ここではこのSAORIの使い方について説明いたします。

Argument0〜9までの引数が必須項目です。
Argument10〜12、13〜15……と、以後3つ一組で一つの項目を入力します。

成功した場合、0という文字列を返します。
それ以外の場合は失敗理由を返します。

### 必須項目

+ Argument0: 出力するpngファイルのパス(SAORIからの相対パスになります)
+ Argument1: 出力するpngファイルの幅(px)
+ Argument2: 出力するpngファイルの高さ(px)
+ Argument3: 円グラフの半径(px)
+ Argument4: ラベル文字の色(RGBのR(0~255))
+ Argument5: ラベル文字の色(RGBのG(0~255))
+ Argument6: ラベル文字の色(RGBのB(0~255))
+ Argument7: ラベル文字のフォント(システムにインストールされていなければデフォルトのものが使用されます)
+ Argument8: ラベル文字の大きさ(px)
+ Argument9: ラベル文字の位置(中心からの距離)

### 必須項目後、項目ごとに一組ずつ

+ Argument*: ラベル文字(文字列)
+ Argument*: 円グラフの大きさ(全体を1としたときの割合)
+ Argument*: 円グラフの色([CSSで色として指定できる文字列](https://developer.mozilla.org/ja/docs/Web/CSS/color_value))

### 例: YAYA

```
On_Test
{
// 幅: 100px, 高さ: 100px, 半径: 40px, ラベル文字の色: 0, 0, 0 (黒),
// ラベル文字のフォント: sans-self (ゴシック体デフォルト),
// ラベル文字の大きさ: 10px, ラベル文字の位置: 20px
// 項目1:: ラベル文字: Red, 大きさ: 0.5, 色: #fe5555(少し明るい赤)
// 項目2:: ラベル文字: Green, 大きさ: 0.1, 色: #55fe55(少し明るい緑)
// 項目3:: ラベル文字: Blue, 大きさ: 0.25, 色: #5555fe(少し明るい青)
// 項目4:: ラベル文字: Other, 大きさ: 0.15, 色: #999(灰色)
_result = FUNCTIONEX('path/to/piechart.dll', 'path/to/output.png', 100, 100, 40, 0, 0, 0, 'sans-serif', 10, 20, 'Red', 0.5, '#fe5555', 'Green', 0.1, '#55fe55', 'Blue', 0.25, '#5555fe', 'Other', 0.15, '#999')
if _result == 0 {
// 成功時の処理
}
else {
// 失敗時の処理
}
}
```

### 例: 里々

#### satori_conf.txt

```
@SAORI
お好きな登録名,path/to/piechart.dll
```

#### 使用時

```
*テスト
# 幅: 100px, 高さ: 100px, 半径: 40px, ラベル文字の色: 0, 0, 0 (黒),
# ラベル文字のフォント: sans-self (ゴシック体デフォルト),
# ラベル文字の大きさ: 10px, ラベル文字の位置: 20px
# 項目1:: ラベル文字: Red, 大きさ: 0.5, 色: #fe5555(少し明るい赤)
# 項目2:: ラベル文字: Green, 大きさ: 0.1, 色: #55fe55(少し明るい緑)
# 項目3:: ラベル文字: Blue, 大きさ: 0.25, 色: #5555fe(少し明るい青)
# 項目4:: ラベル文字: Other, 大きさ: 0.15, 色: #999(灰色)
$円グラフ結果=(お好きな登録名,path/to/output.png,100,100,40,0,0,0,sans-serif,10,20,Red,0.5,#fe5555,Green,0.1,#55fe55,Blue,0.25,#5555fe,Other,0.15,#999)
>円グラフ成功 (円グラフ結果)==0
>円グラフ失敗
```

## 使用ライブラリ

いずれも敬称略。ありがとうございます。

+ [winapi\_rs](https://github.com/retep998/winapi-rs) / Peter Atashian
+ [resvg](https://github.com/RazrFalcon/resvg) / Yevhenii Reizner
+ [png](https://github.com/image-rs/image-png) / The image-rs Developers
+ (テスト実行時) [encoding\_rs](https://github.com/hsivonen/encoding_rs) / Henri Sivonen
+ (テスト実行時) [tempfile](https://github.com/Stebalien/tempfile) / Steven Allen, The Rust Project Developers, Ashley Mannix, Jason White

また、自作ライブラリの[svg-pie-chart](https://github.com/tukinami/svg-pie-chart)を使用しています。

## ライセンス

MITにて配布いたします。

## 作成者

月波 清火 (tukinami seika)

[GitHub](https://github.com/tukinami)
139 changes: 139 additions & 0 deletions src/chars.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
use winapi::{
shared::{
minwindef::LPBOOL,
ntdef::{LPCSTR, LPWSTR, NULL},
},
um::{
stringapiset::{MultiByteToWideChar, WideCharToMultiByte},
winnls::MB_PRECOMPOSED,
winnt::LPSTR,
},
};

pub(crate) fn multi_byte_to_wide_char(from: &[u8], codepage: u32) -> Result<Vec<u16>, ()> {
let mut from_buf: Vec<i8> = from.iter().map(|v| *v as i8).collect();
from_buf.push(0);

let to_buf_size = unsafe {
MultiByteToWideChar(
codepage,
MB_PRECOMPOSED,
from_buf.as_ptr(),
-1,
NULL as LPWSTR,
0,
)
};

if to_buf_size == 0 {
return Err(());
}

let mut to_buf = vec![0; to_buf_size as usize + 1];
let result = unsafe {
MultiByteToWideChar(
codepage,
MB_PRECOMPOSED,
from_buf.as_ptr(),
-1,
to_buf.as_mut_ptr(),
to_buf_size,
)
};

if result == 0 {
Err(())
} else {
Ok(to_buf)
}
}

pub(crate) fn wide_char_to_multi_byte(from: &mut Vec<u16>, codepage: u32) -> Result<Vec<i8>, ()> {
from.push(0);

let to_buf_size = unsafe {
WideCharToMultiByte(
codepage,
0,
from.as_ptr(),
-1,
NULL as LPSTR,
0,
NULL as LPCSTR,
NULL as LPBOOL,
)
};

if to_buf_size == 0 {
return Err(());
}

let mut to_buf: Vec<i8> = vec![0; to_buf_size as usize + 1];
let result = unsafe {
WideCharToMultiByte(
codepage,
0,
from.as_ptr(),
-1,
to_buf.as_mut_ptr(),
to_buf_size,
NULL as LPCSTR,
NULL as LPBOOL,
)
};

if result == 0 {
Err(())
} else {
Ok(to_buf)
}
}

#[cfg(test)]
mod tests {
use crate::request::SaoriCharset;

use super::*;

use encoding_rs;

mod multi_byte_to_wide_char {
use super::*;

#[test]
fn success_when_encoding_and_codepage_is_same() {
let case = "あいうえお仕様";
let (case_byte, _encoding, _is_err) = encoding_rs::SHIFT_JIS.encode(case);

let result =
multi_byte_to_wide_char(&case_byte, SaoriCharset::ShiftJIS.codepage()).unwrap();

let p = result.partition_point(|v| *v != 0);

let result = String::from_utf16_lossy(&result[..p]);

assert_eq!(&result, case);
}
}

mod wide_char_to_multi_byte {
use super::*;

#[test]
fn success_when_valid_wide_char_and_codepage_with_shift_jis() {
let case = "あいうえお仕様";
let mut case_chars: Vec<u16> = case.encode_utf16().collect();

let result =
wide_char_to_multi_byte(&mut case_chars, SaoriCharset::ShiftJIS.codepage())
.unwrap();

let result: Vec<u8> = result.iter().map(|v| *v as u8).collect();

let p = result.partition_point(|v| *v != 0);
let (encoded, _encoding, _is_err) = encoding_rs::SHIFT_JIS.decode(&result[..p]);

assert_eq!(&encoded, case);
}
}
}
64 changes: 64 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::fmt::Display;

#[derive(Debug)]
pub(crate) enum PieChartError {
Success,
NotEnoughArguments,
InvalidArgumentKind(usize, ArgumentKind),
UsvgError(resvg::usvg::Error),
IoError(std::io::Error),
EncodingError(png::EncodingError),
SizeTooSmall,
InvalidData,
}

#[derive(Debug)]
pub(crate) enum ArgumentKind {
Integer,
FloatNumber,
}

impl Display for PieChartError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Success => write!(f, "0"),
Self::NotEnoughArguments => write!(f, "Error: arguments are less than 9."),
Self::InvalidArgumentKind(number, expect) => {
write!(f, "Error: arguments of {number} expect {expect}.")
}
Self::UsvgError(e) => write!(f, "Error: {e}."),
Self::IoError(e) => write!(f, "Error: {e}."),
Self::EncodingError(e) => write!(f, "Error: {e}."),
Self::SizeTooSmall => write!(f, "Error: size too small."),
Self::InvalidData => write!(f, "Error: invalid data."),
}
}
}

impl From<resvg::usvg::Error> for PieChartError {
fn from(value: resvg::usvg::Error) -> Self {
Self::UsvgError(value)
}
}

impl From<std::io::Error> for PieChartError {
fn from(value: std::io::Error) -> Self {
Self::IoError(value)
}
}

impl From<png::EncodingError> for PieChartError {
fn from(value: png::EncodingError) -> Self {
Self::EncodingError(value)
}
}

impl Display for ArgumentKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let kind_str = match self {
Self::Integer => "integer",
Self::FloatNumber => "float number",
};
write!(f, "{kind_str}")
}
}
Loading

0 comments on commit 0dc8359

Please sign in to comment.