initial commit

This commit is contained in:
Yoxem 2026-11-18 22:40:06 +08:00
commit 2c0613a1fd
24 changed files with 6851 additions and 0 deletions

9
LICENSE Normal file
View file

@ -0,0 +1,9 @@
Copyright 2025 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.

21
Project.toml Normal file
View file

@ -0,0 +1,21 @@
name = "uahgi"
uuid = "de6df24e-a306-4916-96f6-3ab6c7568c2f"
authors = ["Tan Kian-ting <chenjt30@gmail.com> and contributors"]
version = "1.0.0-DEV"
[deps]
ArgParse = "c7e460c6-2fb9-53a9-8c5b-16f535851c63"
Fontconfig = "186bb1d3-e1f7-5a2c-a377-96d770f13627"
FreeType = "b38be410-82b0-50bf-ab77-7b57e271db43"
Match = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf"
ParserCombinator = "fae87a5f-d1ad-5cf0-8f61-c941e1580b46"
libharu_jll = "d4e8948d-4b7e-5538-9d15-404f6f0a9070"
[compat]
julia = "1.6.7"
[extras]
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[targets]
test = ["Test"]

29
README.md Normal file
View file

@ -0,0 +1,29 @@
# uahgi
another experimential typesetting tool
## Known issues
### Local project
- function definition, lambda, if, etc
- using faster parser/tokenizer
- RTL
- combining diacritics
### Upstream
- Some .ttc file(eg. Noto Sans/Serif CJK) can't be loaded. It seems to be a libharu bug. For those want to use Noto Sans/Serif CJK, please download the .ttf file on Google Fonts. [Example (Trad. Chinese Version)](https://fonts.google.com/noto/specimen/Noto+Sans+TC)
## How to test
To test with the example, please using the command:
```
cd /path/to/uahgi
julia --project="." src/uahgi.jl example/ex1.ug
```
## Origin of the name
The name is after the Taiwanese/Hokkien word for the movable type, which is ua̍h-gī (活字), in Taichung-Basin accent.
## Test Result
![Example of the syntax](https://github.com/user-attachments/assets/9945139a-0a31-4c61-adc1-c24c6b57abac)
![Generated PDF](https://github.com/user-attachments/assets/ad063fc7-a141-4082-bd1c-d1a7c6465574)

19
docs/grammar.md Normal file
View file

@ -0,0 +1,19 @@
語法:
變數輸入法:
`@varname`
後面如果接英文字,要加`%%`,變成`@varname%%english blah`
註解:`%comment%`,註解內可以換行。
輸入指令:
`{@foo|bar}`
輸入陣列
`{@quote|a|b}`
指定斷字語言:
`{@lang|en}`等,要輸入於第一行才有效。

19
example/ex1 copy.ug Normal file
View file

@ -0,0 +1,19 @@
%123%@foo text%456 7% %
8 9 10%
{@foo}
{@foo|@bar}
貓咪的眼睛,
狐狸的耳朵。
我是
貓,還沒有名字。@foo%我是註釋
%
{@foo|@bar|12\|}

4594
example/ex1.pdf Normal file

File diff suppressed because one or more lines are too long

12
example/ex1.ug Normal file
View file

@ -0,0 +1,12 @@
{@def|@lang|en}%
%{@def|@font|{@quote|FreeSans|AR PL UKai TW}}%
%{@def|@fontsize|12}%
%{@def|@linewidth|400} %in px
%{@def|@hori_align|left} % left| right|center
%{@def|@spacing|{@hglue|{@ex|0.4}|0.2}}%
%{@def|@cjk_lat_spacing|{@hglue|{@ex|0.2}|0.2}}%
%{@def|@cjk_spacing|{@hglue|{@ex|0}|0.2}}%
%the processing of typesetting technology is so sophisticated that many people are afraid of
the implementation of typesetting language.{@set|@fontsize|14} However, it is good to give TEXBook a try. 測試一段漢字,究竟會不會斷行呢?「『《臺灣連翹》是吳濁流的著作,涉及臺灣戰後歷史與政治。』」{@set|@font|{@quote|jf open 粉圓 2.0|AR PL UMing TW}}
願主耶穌ê恩典kap眾聖徒saⁿ-kap tī-leh。À-bēng。(啟示錄bóe-á-cha̍t)原起頭上帝創造天kap地,是創世記頭chi̍t cha̍t。

11
example/ex2.ug Normal file
View file

@ -0,0 +1,11 @@
{@lang|en}
{@def|@font|{@quote|FreeSans|AR PL UKai TW}}
{@def|@fontsize|12}
{@def|@linewidth|300} %in px%
{@def|@spacing|{@hglue|{@ex|1}|2}}
{@def|@cjk_spacing|{@hglue|{@ex|0}|0.001}}
therapy of communication and pronounciation123%comment
anotherline%{@set|@fontsize|10} processing of
of the problem

226
src/arrange.jl Normal file
View file

@ -0,0 +1,226 @@
module Arrange
using Match
u = Main.uahgi
total_cost_table = Dict()
# the cost of make ith to jth item a line
function cost(items, i, j, linewidth, last_of_queue=false)
slice = items[i:j]
last = items[j]
if typeof(last) == u.ChBox && last_of_queue === false
return Inf
end
sum_of_cost_list = 0
# add disc (after) if it exists
if i > 2 && typeof(items[i-1]) == u.Disc
previous = items[i-1]
sum_of_cost_list += item_width(previous.after)
end
if typeof(last) != u.Disc
cost_list = map(x -> item_width(x), slice)
sum_of_cost_list += reduce((x, y)-> x+y, cost_list) - item_width(slice[end])
else
cost_list = map(x -> item_width(x), slice[1:end-1])
if cost_list != []
sum_of_cost_list += reduce((x, y)-> x+y, cost_list)
end
last_width = item_width(last.before)
sum_of_cost_list += last_width
end
if sum_of_cost_list > linewidth
return Inf
else
return (linewidth - sum_of_cost_list) ^ 3
end
end
"""the total cost from 1 to n"""
function total_cost(items, n, linewidth, last_of_queue=false)
if haskey(total_cost_table, n)
return total_cost_table[n][1]
end
# first to nth item cost
fst_to_nth_cost = cost(items, 1, n, linewidth, last_of_queue)
if fst_to_nth_cost < Inf
total_cost_table[n] = [fst_to_nth_cost, 0]
return fst_to_nth_cost
else
mininal_cost = +Inf
prev_breakpoint = nothing
for j in 1:1:(n-1)
total_c = total_cost(items, j, linewidth, false)
cost_tail = cost(items, j+1, n, linewidth, last_of_queue)
if cost_tail < +Inf && last_of_queue == true
tmp_cost = total_c
else
tmp_cost = total_c + cost_tail
end
if tmp_cost < mininal_cost
mininal_cost = tmp_cost
prev_breakpoint = j
end
end
total_cost_table[n] = [mininal_cost, prev_breakpoint]
return mininal_cost
end
end
"""width of a item"""
function item_width(i)
if typeof(i) == u.HGlue
return i.wd
elseif typeof(i) == u.ChBox
return i.wd
elseif typeof(i) == u.Disc
return item_width(i.orig)
else
return 0
end
end
function arrange(vbox, env)
result_vbox_inner = [u.HBox([],nothing,nothing,nothing,nothing,nothing)]
linewidth = parse(Int, env["linewidth"])
eles = vbox.eles[1].eles
total_cost(eles, length(eles), linewidth, true)
current_point = length(eles)
breakpoint_list = [current_point]
while total_cost_table[current_point][2] !== 0.0
current_point = total_cost_table[current_point][2]
push!(breakpoint_list, current_point)
end
breakpoint_list_reversed = reverse(breakpoint_list)
for (x, i) in enumerate(1:1:length(eles))
item = eles[x]
if !(x in breakpoint_list_reversed)
if typeof(item) == u.Par
horizonal_align = env["hori_align"]
result_vbox_inner[end].eles = add_aligner(result_vbox_inner[end].eles, horizonal_align)
push!(result_vbox_inner, u.HBox([],nothing,nothing,nothing,nothing,nothing))
elseif typeof(item) == u.Disc
if item.orig != []
push!(result_vbox_inner[end].eles, item.orig)
end
else
push!(result_vbox_inner[end].eles, item)
end
# x is the last one
elseif i == length(eles)
if typeof(item) !== u.Par
push!(result_vbox_inner[end].eles, item)
end
# x in breakpoint_list_reversed
else
if typeof(item) == u.Par
push!(result_vbox_inner, u.HBox([],nothing,nothing,nothing,nothing,nothing))
elseif typeof(item) == u.Disc
if item.before != []
push!(result_vbox_inner[end].eles, item.before)
end
push!(result_vbox_inner, u.HBox([],nothing,nothing,nothing,nothing,nothing))
if item.after != []
push!(result_vbox_inner[end].eles, item.after)
end
else
push!(result_vbox_inner, u.HBox([],nothing,nothing,nothing,nothing,nothing))
end
end
end
return result_vbox_inner
end
function add_aligner(hbox_eles, horizonal_align)
aligner_glue = u.HGlue(0.0,10000.0)
if horizonal_align == "right"
hbox_eles = reverse(push!(reverse(hbox_eles), aligner_glue))
elseif horizonal_align == "middle"
return hbox_eles
else # left/default
hbox_eles = push!(hbox_eles, aligner_glue)
end
return hbox_eles
end
function position(box_inner, env#=to be used later=#)
pages = [] #a subarray is the content of a page
orig_y = 700 # it can be derived from env
orig_x = 100 # it can be derived from env
posX = orig_x #cursor x
posY = orig_y #cursor y
baselineskip = 30 # it can be derived from env
linewidth = env["linewidth"]
horizonal_align = env["hori_align"]
for (idx, hbox) in enumerate(box_inner)
hbox_eles = hbox.eles
aligner_glue = u.HGlue(0.0,10000.0)
if idx == length(box_inner)
hbox_eles = add_aligner(hbox_eles, horizonal_align)
end
residual_space = parse(Float64, linewidth) - width_sum_of_eles(hbox.eles)
sum_of_stretch = reduce((x,y) -> x+y, map(hglue_stretch, hbox.eles))
space_stretch_ratio = residual_space / sum_of_stretch
pages = position_chbox(hbox_eles, pages, posX, posY, space_stretch_ratio)
posX = orig_x
posY -= baselineskip
end
return pages
end
function hglue_stretch(ele)
if typeof(ele) == u.HGlue
return ele.stretch # stretch
else
return 0
end
end
function width_sum_of_eles(eles)
width_sum = x -> begin
if hasproperty(x, :wd)
return x.wd
else
return 0.0
end
end
if length(eles) == 0
return 0
elseif length(eles) == 1
return width_sum(eles[1])
else
return reduce((x,y)-> x+y, map(width_sum, eles))
end
end
"""positioning all the chboxes in a HBox"""
function position_chbox(hbox_eles, pages, posX, posY, space_stretch_ratio)
for i in hbox_eles
if typeof(i) == u.HGlue
deltaX = i.wd + (i.stretch * space_stretch_ratio)
posX += deltaX
else #ChBox
deltaX = i.wd
i.x = posX
i.y = posY
push!(pages, i)
posX += deltaX
end
end
return pages
end
end

13
src/classes.jl Normal file
View file

@ -0,0 +1,13 @@
module Classes
abstract type Node end
struct ID<:Node val end
struct SEQ<:Node val end # like (a b c) in scheme
struct ELE<:Node val end #an element in a seq
struct ESC_CHAR<:Node val end # character preceded by escape char "\"
struct CHAR<:Node val end #character
struct SPACE<:Node val end # space
struct NL<:Node val end # newline
struct PROG<:Node val end # all the program
# pattern in regex form
#struct PTN_RGX<:Node val::Regex end
end

41
src/hyphenRules/en.jl Normal file

File diff suppressed because one or more lines are too long

144
src/hyphenating.jl Normal file
View file

@ -0,0 +1,144 @@
"""
using Knuth-liang's pattern-matching hyphenating algorithm.
"""
module Hyphenating
using Match
c = Main.uahgi.Parsing.Passes.Classes
function match_lang(item)
@match item begin
c.SEQ([c.ELE([c.ID("def")]),c.ELE([c.ID("lang")]), c.ELE([c.CHAR(v1)])]) => begin
return v1
end
_ => false
end
end
"""
check the language indicated by .ug file
"""
function check_lang(ast)
ast_tree = ast.val
result = map(x -> match_lang(x), ast_tree)
lang = result[1]
if lang != false
return lang
else
return nothing
end
end
function remove_num_from_pattern(ptn)
ptn1 = replace(ptn, r"^\." => "^")
ptn2 = replace(ptn1, r"\.$" => "\$")
ptn3 = replace(ptn2, r"\d" => "")
return ptn3
end
function hyphenate_aux(chars, patterns)
level_of_chars = fill(0, length(chars))
y = filter(x -> (match(Regex(x[1]), chars) !== nothing),patterns)
z = map(x -> (x[1], x[2],
map(x -> x.offset, collect(eachmatch(Regex(x[1]), chars)))), y)
for ptn in z
for offset in ptn[3]
counter = 0
for ptn_char in ptn[2]
if match(r"[a-z]", string(ptn_char)) !== nothing
counter += 1
elseif match(r"[.]", string(ptn_char)) !== nothing
counter = 0
else
# 1-5
if offset + counter -1 != 0
orig = level_of_chars[offset + counter-1]
new = parse(Int, ptn_char)
if new > orig
level_of_chars[offset + counter-1] = new
end
end
counter += 0
end
end
end
end
new_chars = ""
for (idx, char) in enumerate(chars)
new_chars *= char
level_after_char = level_of_chars[idx]
if (level_after_char > 0) && (level_after_char % 2 == 1)
new_chars *= "~" # for hyphenation
end
end
return new_chars
end
function match_char(ast_item, patterns)
@match ast_item begin
c.CHAR(chars), if match(r"[a-zA-Z]+", chars) !== Nothing end =>
begin
raw_result = hyphenate_aux(chars, patterns)
splitted = split(raw_result, "~")
final = []
for i in splitted
push!(final, c.CHAR(i))
push!(final, c.SEQ([c.ELE([c.ID("disc")]),
c.ELE([c.CHAR("-")]),
c.ELE([]),
c.ELE([])]))
end
final = final[1:end-1]
return final
#c.CHAR(hyphenate_aux(chars, patterns))
end
c.SEQ(v) => c.SEQ(map(x -> match_char(x, patterns), v))
_ => ast_item
end
end
function hyphenate(ast)
lang = check_lang(ast)
if lang !== nothing
include("hyphenRules/$lang.jl")
patterns = Hyphen.patterns
pattern_with_orig = map(x->(remove_num_from_pattern(x), x),
patterns)
new_ast_val = map(x -> match_char(x, pattern_with_orig), ast.val)
new_ast_val2 = []
for i in new_ast_val
@match i begin
[x] => push!(new_ast_val2, x)
[x,y] =>begin new_ast_val2 = vcat(new_ast_val2, i) end
[x,y...,z] =>begin new_ast_val2 = vcat(new_ast_val2, i) end
_ => push!(new_ast_val2, i)
end
end
new_ast_val3 = []
for i in new_ast_val2
@match i begin
c.CHAR(val=r"[a-zA-Z]+") => begin
new_ast_val3 = vcat(new_ast_val3,
map(q -> c.CHAR(q), split(i.val, "")))
end
_ => push!(new_ast_val3, i)
end
end
return c.PROG(new_ast_val3)
else
return ast
end
end
end

253
src/interp.jl Normal file
View file

@ -0,0 +1,253 @@
module Interp
using Match
using Fontconfig
include("pdfoperating.jl")
using .PDFOperating
u = Main.uahgi
c = Main.uahgi.Parsing.Passes.Classes
@enum PutChar begin
true_ = 0
false_ = 1
gen_chbox_ = 2
end
function interp_main(ast, env, res_box)
ast_inner = ast.val
val = nothing
for e in ast_inner
(val, env, res_box) = interp(e, env, res_box)
end
return (val, env, res_box)
end
"""
interp: the intepreter of the uahgi.
- ast: element or part of the ast
- env: the variable storaging environment
- res_box: the generated result box containing the content\
- put_char(PutChar): if the character should be put into the res_box.
"""
function interp(ast, env, res_box, put_char=true_)
#println("INTERP", ast)
@match ast begin
c.ID(id) =>
begin
#print("ID____", id)
return interp(env[id], env, res_box, true_)
end
c.SEQ([c.ID("par")]) => begin
par_box = u.Par()
push!(res_box.eles[end].eles, par_box)
return interp("", env, res_box)
end
c.SEQ([c.ELE([c.ID("def")]),
c.ELE([c.ID(id)]),val]) =>
begin
(val_evaled, env, res_box) = interp(val, env, res_box, false_)
#println("ID~~~", id, " VAL~~~", val_evaled)
if !haskey(env, id)
env[id] = val_evaled
else
throw("the variable $id has been defined.")
end
return (val_evaled, env, res_box)
end
c.SEQ([c.ELE([c.ID("set")]),
c.ELE([c.ID(id)]),val]) =>
begin
(val_evaled, env, res_box) = interp(val, env, res_box, false_)
#println("ID~~~", id, " VAL~~~", val_evaled)
if haskey(env, id)
env[id] = val_evaled
else
throw("the variable $id is not defined yet.")
end
return (val_evaled, env, res_box)
end
c.SEQ([c.ELE([c.ID("quote")]),
y...]) => begin
list = map(x -> x[1],
map(x -> interp(x, env, res_box), y))
#println("QUOTE", list)
return (list, env, res_box)
end
c.ELE([v...]) => begin
ele = reduce( (x, y) -> x*""*y,
map(i -> interp(i, env, res_box, false_)[1], v))
return (ele, env, res_box)
end
c.SEQ([c.ELE([c.ID("ex")]), val]) =>begin
x = 'x'
font_family = select_font(x, env)
font_path = get_font_path(font_family)
font_size = parse(Int, env["fontsize"])
charmetrics = PDFOperating.check_char_size(
'x',
font_path,
font_size)
ex_in_px = charmetrics.wd
(val, _, _) = interp(val, env, res_box, false_)
val_ex_in_px = ex_in_px * parse(Float64,val)
return (val_ex_in_px, env, res_box)
end
c.SEQ([c.ELE([c.ID("hglue")]),
width,stretch]) => begin
if put_char == true_
(width_evaled, _, _) = interp(width, env, res_box, false_)
(stretch_evaled, _, _) = interp(stretch, env, res_box, false_)
push!(res_box.eles[end].eles,
u.HGlue(width_evaled, parse(Float64, stretch_evaled))
)
end
return (ast, env, res_box)
end
c.CHAR(ch) => begin
atomic_ch = ch[1]
if put_char == false_
return (ch, env, res_box)
end
font_family = select_font(atomic_ch, env)
font_path = get_font_path(font_family)
font_size = parse(Int, env["fontsize"])
glyph_metrics = PDFOperating.check_char_size(
atomic_ch, font_path, font_size)
chbox = u.ChBox(ch,
font_path,
font_size,
glyph_metrics.ht,
glyph_metrics.dp,
glyph_metrics.wd,
nothing, nothing)
if put_char == true_
push!(res_box.eles[end].eles, chbox)
return (ch, env, res_box)
else # put_char == gen_chbox_
return (chbox, env, res_box)
end
end
c.SEQ([c.ELE([c.ID("disc")]),
c.ELE(before),
c.ELE(after),
c.ELE(orig)])=> begin
before_item = length(before) == 0 ? [] : before[1]
after_item = length(after) == 0 ? [] : after[1]
orig_item = length(orig) == 0 ? [] : orig[1]
(before_evaled, _, _) = interp(before_item, env, res_box, gen_chbox_)
(after_evaled, _, _) = interp(after_item, env, res_box, gen_chbox_)
(orig_evaled, _, _) = interp(orig_item, env, res_box, gen_chbox_)
ret = u.Disc(before_evaled, after_evaled, orig_evaled)
push!(res_box.eles[end].eles, ret)
return (ret, env, res_box)
end
c.NL(nl) => begin
#if spacing defined
if haskey(env, "spacing")
(spacing, _, _) = interp(env["spacing"], env, res_box, false_)
add_spacing = interp(spacing, env, res_box, true_)
end
return (nl, env, res_box)
end
c.SPACE(sp) => begin
#if spacing defined
if haskey(env, "spacing")
(spacing, _, _) = interp(env["spacing"], env, res_box, false_)
add_spacing = interp(spacing, env, res_box, true_)
end
return (sp, env, res_box)
end
# empty item
[] => return (ast, env, res_box)
"" => return (ast, env, res_box)
_ => begin
println("unknown token: ", ast)
val_evaled = nothing
return (val_evaled, env, res_box)
end
end
end
function get_font_path(font_family)
ptn = Fontconfig.Pattern(family=font_family)
matched = Fontconfig.match(ptn)
path = match(r"file=([^:]+)", string(matched))[1]
return path
end
"""
check if the glyph of a char is contained by `font_family`
"""
function is_in_font(char, font_family)
ptn = Fontconfig.Pattern(family=font_family)
matched = Fontconfig.match(ptn)
charset = match(r"charset=([^:]+)", string(matched))[1]
splitted1 = split(charset, " ")
splitted2 = map(x -> split(x, "-"), splitted1)
"""aux function"""
regex_aux(x) = map(y -> padding_zero(y), x)
x1 = map(x -> regex_aux(x), splitted2)
x2 = map(x -> length(x) == 1 ? "\\u" * x[1] : "\\u" * x[1] * "-\\u" * x[2] , x1)
regex_final = "[" * reduce((x,y)-> x*""*y, x2) * "]"
regex_final_wrapped = Regex(regex_final)
if match(regex_final_wrapped, string(char)) !== nothing
return true
else
return false
end
end
"""
padding zero for a hex-digit string `i` to make it a 4-digit.
- "27" -> "0027"
- "8af" -> "08af"
"""
function padding_zero(i)
if length(i) == 2
i="00"*i
end
if length(i)==3
i="0"*i
end
return i
end
"""
Select proper font having the glyph of char `ch`
"""
function select_font(ch, env)
font_idx = 1
font_family = string(env["font"][font_idx])
font_family_length = length(font_family)
while !is_in_font(ch, font_family)
if font_idx <= font_family_length
font_idx += 1
font_family = string(env["font"][font_idx])
else
font_list = string(env["font"])
throw("the chars $atomic_ch is not contained in all the fonts
listed in listed fonts: $font_list")
end
end
return font_family
end
end

139
src/parsing.jl Normal file
View file

@ -0,0 +1,139 @@
module Parsing
using ParserCombinator
using Match
include("passes.jl")
include("hyphenating.jl")
using .Passes
using .Hyphenating
#=
grammar rules of uahgi
=#
comment = P"\%[^%]+\%"
newline = P"(\r?\n)" |> Passes.Classes.NL
space = p"[ \t]+" > Passes.Classes.SPACE
id_name = p"[_a-zA-Z][_0-9a-zA-Z]*" > Passes.Classes.ID
id = E"@" + id_name
empty_char = P"" # empty char
#make alphabet series a group for hyphenating
char = p"([a-zA-Z]+|[^ \|\{\}\@\%a-zA-Z\n\r\t\\])" > Passes.Classes.CHAR #[1:2,:?]
# chars should be preceded by "\" are \, {, }, |, @, %
esc_char = p"[\{\|\}\@\%]" > Passes.Classes.ESC_CHAR
esc_combined = E"\\" + esc_char
#=
seq = (foo x1 x2 " ")
=> {@foo|x1|x2| }
=#
seq = Delayed() # recursively used later.
char_and_combined = char | esc_combined | space | newline
seq_atom_item = id | Repeat(char_and_combined) | empty_char |> Passes.Classes.ELE
seq_item = seq | seq_atom_item
seq_item_rest = E"|" + seq_item
seq_inner = seq_item + (seq_item_rest)[0:end] |> Passes.Classes.SEQ
seq.matcher = E"{" + seq_inner + E"}"
part = seq | comment | space | newline | id | char
all = (Repeat(part) + Eos()) |> Passes.Classes.PROG
function parse(input)
ast = parse_one(input, all)[1]
#print(parse_one(, Pattern(r".b.")))
ast = Hyphenating.hyphenate(ast)
passes = Passes.processed_passes
ast_val = ast.val
for pass in passes
ast_val = use_pass(ast_val, pass)
end
new_ast = Passes.Classes.PROG(ast_val)
return new_ast
end
function ast_pattern_matched(pattern, ast_head)
zipped = zip(pattern, ast_head)
zipped_mapped = map(x -> match_unit(x), zipped)
is_all_matched = reduce((x,y)-> x && y, zipped_mapped)
return is_all_matched
end
function match_unit(pair)
pattern = pair[1]
ast_item = pair[2]
#println(pattern, "~~~", ast_item)
if typeof(pattern) != typeof(ast_item)
return false
elseif typeof(pattern.val) == Regex
is_matched = occursin(pattern.val, ast_item.val)
return is_matched
else
return pattern.val == ast_item.val
end
end
function use_pass(ast_val, pass)
pass_pattern = pass.pattern
pass_pattern_length = length(pass_pattern)
if length(ast_val) < pass_pattern_length
return ast_val
else
ast_head = ast_val[1:pass_pattern_length]
if ast_pattern_matched(pass_pattern, ast_head)
ast_head = pass.func(ast_head)
raw_remained = [ast_head[2:end];ast_val[pass_pattern_length+1:end]]
remained = use_pass(raw_remained, pass)
ast_val = [ast_head[1]; remained]
else
raw_remained = ast_val[2:end]
remained = use_pass(raw_remained, pass)
ast_val = [ast_head[1]; remained]
return ast_val
end
end
end
function ast_to_string(ast)
item = 5
str = @match ast begin
Passes.Classes.PROG(v) => begin
prog_inner = reduce( (x, y) -> x*" "*y, map(i -> ast_to_string(i), v))
return "[" * prog_inner * "]"
end
Passes.Classes.SEQ(v) => begin
prog_inner = reduce( (x, y) -> x*" "*y, map(i -> ast_to_string(i), v))
return "(" * prog_inner * ")"
end
Passes.Classes.ID(v) => "[ID: " * v * "]"
Passes.Classes.ELE([]) => return "[ELE : ()]"
Passes.Classes.ELE(v) => begin
prog_inner = reduce( (x, y) -> x*" "*y, map(i -> ast_to_string(i), v))
return "[ELE : (" * prog_inner * ")]"
end
Passes.Classes.ESC_CHAR(ch) => "[ESC:\"" * ch[1] * "\"]"
Passes.Classes.CHAR(ch) => "\"" * ch * "\""
Passes.Classes.NL(_) => "NL"
Passes.Classes.SPACE(_) => "SPACE"
_ => string(ast)
end
return str
end
end

97
src/passes.jl Normal file
View file

@ -0,0 +1,97 @@
module Passes
include("classes.jl")
using .Classes
export processed_passes, Pass
processed_passes = []
struct Pass
pattern
func
end
####definition of passes ####
# 2 newline become @par{}
function two_nl_to_par_pass_func(two_nl)
return [Classes.SEQ([Classes.ID("par")])]
end
two_nl_to_par_pattern = [Classes.NL([]), Classes.NL([])] #two continuous newline
two_nl_to_par_pass = Pass(two_nl_to_par_pattern,
two_nl_to_par_pass_func)
push!(processed_passes, two_nl_to_par_pass)
# hyphen between 2 chars to disc
function discretize_hyphen(two_nl)
inner = Classes.SEQ([Classes.ELE([Classes.ID("disc")]),
Classes.ELE([Classes.CHAR("-")]),
Classes.ELE([]),
Classes.ELE([Classes.CHAR("-")])])
return [two_nl[1]; inner; two_nl[3]]
end
hyphen_pattern = [Classes.CHAR(r"[^\-]"),
Classes.CHAR(r"[-]"), Classes.CHAR(r"[^\-]")]
hyphen_disc_pass = Pass(hyphen_pattern,
discretize_hyphen)
push!(processed_passes, hyphen_disc_pass)
adjacent_cjk_pattern = [Classes.CHAR(r"[\p{Han}]"),
Classes.CHAR(r"[\p{Han}]")]
# in latin+cjk and latin+cjk add glue.
function insert_hglue_in_adjacent_cjk_lat(two_nl)
inner = Classes.ID("cjk_lat_spacing")
return [two_nl[1]; inner; two_nl[2]]
end
adjacent_cjk_lat_pattern = [Classes.CHAR(r"[\p{Han}]"),
Classes.CHAR(r"[^\p{Han}·,。!?:」』》】]〕』〗〉}…—「『《〔[【『〖〈{]")]
adjacent_cjk_lat_pattern2 = [Classes.CHAR(r"[^\p{Han}·,。!?:」』》】]〕』〗〉}…—「『《〔[【『〖〈{]"),
Classes.CHAR(r"[\p{Han}]")]
adjacent_cjk_lat_pass = Pass(adjacent_cjk_lat_pattern,
insert_hglue_in_adjacent_cjk_lat)
push!(processed_passes, adjacent_cjk_lat_pass)
adjacent_cjk_lat2_pass = Pass(adjacent_cjk_lat_pattern2,
insert_hglue_in_adjacent_cjk_lat)
push!(processed_passes, adjacent_cjk_lat2_pass)
# in 2 hanzi add glue.
function insert_hglue_in_adjacent_cjk(two_nl)
inner = Classes.ID("cjk_spacing")
return [two_nl[1]; inner; two_nl[2]]
end
adjacent_cjk_pattern = [Classes.CHAR(r"[\p{Han}]"),
Classes.CHAR(r"[\p{Han}]")]
adjacent_cjk_pass = Pass(adjacent_cjk_pattern,
insert_hglue_in_adjacent_cjk)
push!(processed_passes, adjacent_cjk_pass)
# line breaking rule in CJK 避頭尾/禁則処理
adjacent_cjk_punc_pattern = [Classes.CHAR(r"[·,。!?:」』》】]〕』〗〉}]"),
Classes.CHAR(r"[^·,。!?:」』》】]〕』〗〉}]")]
adjacent_cjk_punc_pattern2 = [Classes.CHAR(r"[^「『《〔[【『〖〈{]"),
Classes.CHAR(r"[「『《〔[【『〖〈{]")]
adjacent_cjk_punc_pattern3 = [Classes.CHAR(r"[…—]"),
Classes.CHAR(r"[^…—]")]
adjacent_glue_pass = Pass(adjacent_cjk_pattern,
insert_hglue_in_adjacent_cjk)
push!(processed_passes, adjacent_glue_pass)
adjacent_glue_pass2 = Pass(adjacent_cjk_punc_pattern2,
insert_hglue_in_adjacent_cjk)
push!(processed_passes, adjacent_glue_pass2)
adjacent_glue_pass3 = Pass(adjacent_cjk_punc_pattern3,
insert_hglue_in_adjacent_cjk)
push!(processed_passes, adjacent_glue_pass3)
end

145
src/pdfoperating.jl Normal file
View file

@ -0,0 +1,145 @@
module PDFOperating
using libharu_jll
using FreeType
"""
using TeX-like metrics, in px
- height
- weight
- depth
"""
struct CharMetrics
ht::Float64
dp::Float64
wd::Float64
end
#the default path is Noto Serif CJK Regular
#default_font_path = "src/thirdParty/fonts/noto/NotoSerifTC-Regular.ttf"
default_font_path = "src/thirdParty/fonts/linuxLibertine/LinLibertine_Rah.ttf"
function createPDF()
#=returns pdf=#
pdf = @ccall libhpdf.HPDF_New(""::Cstring, 0::Cint)::Ptr{Cvoid}
#using utf-8
@ccall libhpdf.HPDF_UseUTFEncodings(pdf::Ptr{Cvoid})::Ptr{Cvoid};
@ccall libhpdf.HPDF_SetCurrentEncoder(pdf::Ptr{Cvoid}, "UTF-8"::Cstring)::Ptr{float};
return pdf
end
function addPage(pdf)
page = @ccall libhpdf.HPDF_AddPage(pdf::Ptr{Cvoid})::Ptr{Cvoid}
return page
end
function load_font(pdf, font_path,index=0)
HPDF_TRUE = 1
# only available in ttf and ttc
is_ttf = match(r".+\.ttf$", font_path)
is_ttc = match(r".+\.ttc$", font_path)
if is_ttf !== nothing
font_name = @ccall libhpdf.HPDF_LoadTTFontFromFile(
pdf::Ptr{Cvoid},
font_path::Cstring, HPDF_TRUE::Cint)::Cstring
elseif is_ttc !== nothing
font_name = @ccall libhpdf.HPDF_LoadTTFontFromFile2(
pdf::Ptr{Cvoid},
font_path::Cstring,
index::Cuint,
HPDF_TRUE::Cint)::Cstring
else
throw("the format of \"$font_path\" is not valid!")
end
font = @ccall libhpdf.HPDF_GetFont(
pdf::Ptr{Cvoid},
font_name::Cstring,
"UTF-8"::Cstring)::Ptr{Cvoid};
return font
end
function put_text(page, text, font, size, x, y)
# set font and size
@ccall libhpdf.HPDF_Page_SetFontAndSize(
page::Ptr{Cvoid},
font::Ptr{Cvoid},
float(size)::Cfloat)::Ptr{Cvoid};
#declare putting text
@ccall libhpdf.HPDF_Page_BeginText(
page::Ptr{Cvoid})::Ptr{Cvoid}
# put the text on
@ccall libhpdf.HPDF_Page_TextOut(
page::Ptr{Cvoid},
float(x)::Cfloat,
float(y)::Cfloat,
text::Cstring)::Ptr{Cvoid};
# end of putting text
@ccall libhpdf.HPDF_Page_EndText(
page::Ptr{Cvoid})::Ptr{Cvoid}
end
function save_pdf(pdf, file_name)
@ccall libhpdf.HPDF_SaveToFile(
pdf::Ptr{Cvoid},
file_name::Cstring)::Ptr{Cvoid};
end
function check_char_size(char, font_path, font_size, font_index=0)
library = Vector{FT_Library}(undef, 1)
error = FT_Init_FreeType(library)
face = Ref{FT_Face}()
FT_New_Face(library[1], string(font_path), 0, face)
glyph_index = FT_Get_Char_Index(face[], char)
FT_Load_Glyph(face[], glyph_index, FT_LOAD_NO_SCALE)
faceRec = unsafe_load(face[])
glyphrec = unsafe_load(faceRec.glyph)
metrics = glyphrec.metrics
# horizonal mode
width = metricToPx(metrics.horiAdvance, font_size) * 0.75
#from baseline up to top of the glyph
height = metricToPx(metrics.horiBearingY, font_size) * 0.75
#from baseline down to the bottom of the glyph
depth = metricToPx(metrics.height - metrics.horiBearingY, font_size) * 0.75
return CharMetrics(height, depth, width)
end
"""
convert freetype metric unit to px with fontsize in pt
"""
function metricToPx(metric, size_pt)
return metric * size_pt / 750
end
#pdf = createPDF()
#page = addPage(pdf)
#font = load_font(pdf, default_font_path)
#put_text(page, "上下abc", font, 15, 100, 200)
#put_text(page, "天地人", font, 15, 200, 200)
#save_pdf(pdf, "text.pdf")
#println("PDF generated.")
#check_char_size(
# '安',
# default_font_path,
# 20)
"""generate_pdf"""
function generate_pdf(box_list, file_path)
pdf = createPDF()
page = addPage(pdf)
for ch in box_list
font = load_font(pdf, ch.font_path)
put_text(page, ch.char, font, ch.size, ch.x, ch.y)
end
save_pdf(pdf, file_path)
end
end

View file

@ -0,0 +1,343 @@
GNU GENERAL PUBLIC LICENSE (with font exception)
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
As a special exception, if you create a document which uses this font, and embed this font or unaltered portions of this font into the document, this font does not by itself cause the resulting document to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the document might be covered by the GNU General Public License. If you modify this font, you may extend this exception to your version of the font, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

Binary file not shown.

View file

@ -0,0 +1,94 @@
Copyright (c) 2003–2012, Philipp H. Poll (www.linuxlibertine.org | gillian at linuxlibertine.org),
with Reserved Font Name "Linux Libertine" and "Biolinum".
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

97
src/thirdParty/fonts/noto/LICENCE.txt vendored Normal file
View file

@ -0,0 +1,97 @@
Copyright (c) <dates>, <Copyright Holder> (<URL|email>),
with Reserved Font Name <Reserved Font Name>.
Copyright (c) <dates>, <additional Copyright Holder> (<URL|email>),
with Reserved Font Name <additional Reserved Font Name>.
Copyright (c) <dates>, <additional Copyright Holder> (<URL|email>).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

154
src/uahgi.jl Normal file
View file

@ -0,0 +1,154 @@
module uahgi
include("parsing.jl")
include("interp.jl")
include("arrange.jl")
include("pdfoperating.jl")
using .Interp
using .Parsing
using .Arrange
using .PDFOperating
using ArgParse
export ChBox, HGlue
abstract type Box end
"""
a like-breakable discrete point.
- before: the item before likebreaking
- after: the item after linebreaking
- orig: the status while not triggering like breaking
"""
mutable struct Disc<:Box
before
after
orig
end
"""
Horizonal Box
- eles = array in the Hbox
- ht = height
- dp = depth
- wd = width
"""
mutable struct HBox<:Box
eles
ht
dp
wd
x
y
end
"""
Horizonal Glue (HGlue)
- wd : width
- stretch : stretch
"""
mutable struct HGlue<:Box
wd
stretch
end
"""
Par
- for paragraph marker.
"""
mutable struct Par<:Box
end
"""
Vertical Box
- eles = array in the Hbox
- ht = height
- dp = depth
- wd = width
"""
mutable struct VBox<:Box
eles
ht
dp
wd
x
y
end
"""
Character Box
- char: character
- font_path: font path for the char
- size: font sizein pt
- ht = height
- dp = depth
- wd = width
"""
mutable struct ChBox<:Box
char
font_path
size
ht
dp
wd
x
y
end
function parse_commandline()
#= please see:
https://carlobaldassi.github.io/ArgParse.jl/stable/
=#
s = ArgParseSettings()
@add_arg_table! s begin
"FILE"
help = "the file path to be converted."
required = false
end
return parse_args(s)
end
function main()
parsed_args = parse_commandline()
file_path = parsed_args["FILE"]
if file_path === nothing
#help string
help = "usage: uahgi.jl [-h] [FILE]
positional arguments:
FILE the file path to be converted.
optional arguments:
-h, --help show this help message and exit"
println(help)
return 0
end
# for test
#if parsed_args["FILE"] === nothing
# file_path = "./example/ex1.ug"
#else
# file_path = parsed_args["FILE"]
#end
file_content = open(f->read(f, String), file_path)
ast = Parsing.parse(file_content)
default_env = Dict() # the default environment for the intepreter
output_box_orig = VBox([HBox([], nothing, nothing, nothing, nothing, nothing)],
nothing, nothing, nothing, nothing, nothing)
output_box_result = Interp.interp_main(ast, default_env, output_box_orig)
env = output_box_result[2]
output_box = output_box_result[3]
arranged = Arrange.arrange(output_box, env)
unit_positioned = Arrange.position(arranged, env)
generated_pdf = PDFOperating.generate_pdf(unit_positioned, file_path[1:end-3] * ".pdf")
end
main()
end

6
test/runtests.jl Normal file
View file

@ -0,0 +1,6 @@
using uahgi
using Test
@testset "uahgi.jl" begin
# Write your tests here.
end

385
text.pdf Normal file

File diff suppressed because one or more lines are too long