Skip to content

Commit

Permalink
test5: remove fontconfig in CI
Browse files Browse the repository at this point in the history
  • Loading branch information
yisibl committed Aug 20, 2023
1 parent 94eb60f commit e193aa6
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 123 deletions.
34 changes: 12 additions & 22 deletions .github/workflows/CI.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ jobs:
setup: |
sudo apt-get update
sudo apt-get install gcc-arm-linux-gnueabihf -y
# sudo apt-get install libfontconfig1 -y
build: |
yarn build --target armv7-unknown-linux-gnueabihf
arm-linux-gnueabihf-strip *.node
Expand Down Expand Up @@ -260,8 +259,8 @@ jobs:
- host: windows-latest
target: x86_64-pc-windows-msvc
node:
# - '14'
# - '16'
- '14'
- '16'
- '18'
runs-on: ${{ matrix.settings.host }}
steps:
Expand Down Expand Up @@ -297,8 +296,8 @@ jobs:
fail-fast: false
matrix:
node:
# - '14'
# - '16'
- '14'
- '16'
- '18'
runs-on: ubuntu-latest
steps:
Expand All @@ -325,7 +324,7 @@ jobs:
run: ls -R .
shell: bash
- name: Test bindings
run: docker run --rm -v /usr/share/fonts:/usr/share/fonts -v $(pwd):/build -w /build node:${{ matrix.node }}-slim sh -c "find /usr/share/fonts -name *.ttf && yarn test"
run: docker run --rm -v /usr/share/fonts:/usr/share/fonts -v $(pwd):/build -w /build node:${{ matrix.node }}-slim yarn test"
test-linux-x64-musl-binding:
name: Test bindings on x86_64-unknown-linux-musl - node@${{ matrix.node }}
needs:
Expand All @@ -334,8 +333,8 @@ jobs:
fail-fast: false
matrix:
node:
# - '14'
# - '16'
- '14'
- '16'
- '18'
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -364,7 +363,7 @@ jobs:
run: ls -R .
shell: bash
- name: Test bindings
run: docker run --rm -v /usr/share/fonts:/usr/share/fonts -v $(pwd):/build -w /build node:${{ matrix.node }}-alpine sh -c "find /usr/share/fonts -name *.ttf && yarn test"
run: docker run --rm -v /usr/share/fonts:/usr/share/fonts -v $(pwd):/build -w /build node:${{ matrix.node }}-alpine yarn test"
test-linux-aarch64-gnu-binding:
name: Test bindings on aarch64-unknown-linux-gnu - node@${{ matrix.node }}
needs:
Expand All @@ -373,8 +372,8 @@ jobs:
fail-fast: false
matrix:
node:
# - '14'
# - '16'
- '14'
- '16'
- '18'
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -406,9 +405,6 @@ jobs:
run: |
set -e
find /usr/share/fonts -name *.ttf
apt-get install fontconfig -y
fc-cache --force
fc-list :lang=en
ls -la
yarn test
test-linux-aarch64-musl-binding:
Expand Down Expand Up @@ -445,9 +441,6 @@ jobs:
run: |
set -e
find /usr/share/fonts -name *.ttf
apk add fontconfig
fc-cache --force
fc-list :lang=en
apk add nodejs npm yarn
yarn test
test-linux-arm-gnueabihf-binding:
Expand All @@ -458,8 +451,8 @@ jobs:
fail-fast: false
matrix:
node:
# - '14'
# - '16'
- '14'
- '16'
- '18'
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -490,9 +483,6 @@ jobs:
run: |
set -e
find /usr/share/fonts -name *.ttf
apt-get install fontconfig -y
fc-cache --force
fc-list :lang=en
ls -la
yarn test
Expand Down
75 changes: 6 additions & 69 deletions __test__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PathLike, promises as fs, readdirSync, statSync } from 'fs'
import { promises as fs } from 'fs'
import { join } from 'path'

import test from 'ava'
Expand Down Expand Up @@ -270,54 +270,18 @@ test('should be load custom fontDirs(no defaultFontFamily option)', (t) => {
t.is(originPixels.join(',').match(/0,0,255/g)?.length, 1726)
})

test.only('The defaultFontFamily is not found in the OS and needs to be fallback', async (t) => {
test('The defaultFontFamily is not found in the OS and needs to be fallback', (t) => {
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 300 200">
<text fill="blue" font-family="" font-size="100">
<tspan x="10" y="60%">Abc</tspan>
</text>
</svg>
`

async function checkFileExists(filepath: PathLike) {
try {
await fs.access(filepath, fs.constants.F_OK)
return true
} catch (error) {
return false
}
}

function find_files(directoryPath: PathLike) {
// 获取目录下的所有文件和子目录
const items = readdirSync(directoryPath)

// 遍历每个文件或子目录
items.forEach((item) => {
const itemPath = require('path').join(directoryPath, item)
const stats = statSync(itemPath)

if (stats.isFile()) {
// 处理文件
console.info('文件:', itemPath)
} else if (stats.isDirectory()) {
// 处理子目录,并递归遍历
find_files(itemPath)
}
})
}

const fontPath = require('path').join('/usr/share/fonts')
const isExists = await checkFileExists(fontPath)
console.info(`Node.js 开始读取字体目录 ${fontPath}`, isExists)
if (isExists) {
find_files(fontPath)
}

const resvg = new Resvg(svg, {
font: {
loadSystemFonts: true,
// fontDirs: ['/usr/share/fonts/'], // 防止在 CI 的 Docker 环境找不到字体
fontDirs: ['/usr/share/fonts/'], // 防止在 CI 的 Docker 环境找不到字体
defaultFontFamily: 'this-is-a-non-existent-font-family',
},
logLevel: 'debug',
Expand All @@ -326,57 +290,30 @@ test.only('The defaultFontFamily is not found in the OS and needs to be fallback
const originPixels = pngData.pixels.toJSON().data
// Find the number of blue `rgb(0,255,255)`pixels
const matchPixels = originPixels.join(',').match(/0,0,255/g)
console.info('✅ matchPixels length =', matchPixels?.length)
t.true(matchPixels !== null) // If the font is not matched, there are no blue pixels.
t.true((matchPixels?.length ?? 0) > 1500)
})

test('Test defaultFontFamily', async (t) => {
test('Test defaultFontFamily', (t) => {
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 300 200">
<text fill="blue" font-family="" font-size="100">
<tspan x="10" y="60%">Abc</tspan>
</text>
</svg>
`

async function checkFileExists(filepath: PathLike) {
try {
await fs.access(filepath, fs.constants.F_OK)
return true
} catch (error) {
return false
}
}
const isExists = await checkFileExists('/usr/share/fonts')
console.info(`Node.js 开始读取字体目录 /usr/share/fonts`, isExists)
if (isExists) {
readdirSync('/usr/share/fonts').forEach((file) => {
console.info(`获取到文件 ${file}`)
})
}

const isExists2 = await checkFileExists('/usr/local/share/fonts')
console.info(`字体目录 /usr/local/share/fonts`, isExists2)
if (isExists2) {
readdirSync('/usr/local/share/fonts').forEach((file) => {
console.info(`获取到文件 ${file}`)
})
}

const resvg = new Resvg(svg, {
font: {
loadSystemFonts: false,
fontDirs: ['./example'],
defaultFontFamily: 'Source Han Serif CN Light', // 指定中文字体,期望自动 fallback 到 英文的 Pacifico.
defaultFontFamily: 'Source Han Serif CN Light', // 指定中文字体,期望自动 fallback 到英文 字体 Pacifico.
},
logLevel: 'debug',
})
const pngData = resvg.render()
const originPixels = pngData.pixels.toJSON().data
// Find the number of blue `rgb(0,255,255)`pixels
const matchPixels = originPixels.join(',').match(/0,0,255/g)
console.info('✅ matchPixels length =', matchPixels?.length)
t.true(matchPixels !== null) // If the font is not matched, there are no blue pixels.
t.true((matchPixels?.length ?? 0) > 1500)
})
Expand Down Expand Up @@ -406,7 +343,7 @@ test('Async rendering', async (t) => {
const MaybeTest = typeof AbortController !== 'undefined' ? test : test.skip

MaybeTest('should be able to abort queued async rendering', async (t) => {
// fill the task queue
// Fill the task queue
for (const _ of Array.from({ length: 100 })) {
process.nextTick(() => {})
}
Expand Down
3 changes: 0 additions & 3 deletions example/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ async function main() {
loadSystemFonts: false, // It will be faster to disable loading system fonts.
// fontFiles: ['./__test__/Pacifico-Regular.ttf'],
fontDirs: ['./example'],
// defaultFontFamily: 'Source Han Serif CN Light',
// defaultFontFamily: 'Nabla',
defaultFontFamily: 'this-is-a-non-existent-font-family',
},
logLevel: 'debug', // Default Value: error
})
Expand Down
43 changes: 14 additions & 29 deletions src/fonts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,46 +73,35 @@ pub fn load_wasm_fonts(

#[cfg(not(target_arch = "wasm32"))]
fn set_font_families(font_options: &JsFontOptions, fontdb: &mut Database) {
let mut default_font_family = font_options.default_font_family.clone();
// debug font list
for face in fontdb.faces() {
let family = face
.families
.iter()
.find(|f| f.1 == Language::English_UnitedStates)
.unwrap_or(&face.families[0]);

debug!("font_id = {}, family_name = {}", face.id, family.0);
}
let mut default_font_family = font_options.default_font_family.clone().trim().to_string();
// Debug: get font lists
// for face in fontdb.faces() {
// let family = face
// .families
// .iter()
// .find(|f| f.1 == Language::English_UnitedStates)
// .unwrap_or(&face.families[0]);
// debug!("font_id = {}, family_name = {}", face.id, family.0);
// }

let trimmed_default_font_family = default_font_family.trim();
let fontdb_found_default_font_family = fontdb
.faces()
.iter()
.find_map(|it| {
it.families
.iter()
.find(|f| f.0 == trimmed_default_font_family)
.find(|f| f.0 == default_font_family)
.map(|f| f.0.clone())
})
.unwrap_or_default();

debug!(
"fontdb 找到的默认字体名称 = {}",
fontdb_found_default_font_family
);

// 当 default_font_family 为空或系统无该字体时,尝试把 fontdb
// 中字体列表的第一个字体设置为默认的字体。
if trimmed_default_font_family.is_empty() || fontdb_found_default_font_family.is_empty() {
if default_font_family.is_empty() || fontdb_found_default_font_family.is_empty() {
// font_files 或 font_dirs 选项不为空时, 从已加载的字体列表中获取第一个字体的 font family。
if !font_options.font_files.is_empty() || !font_options.font_dirs.is_empty() {
default_font_family = get_first_font_family_or_fallback(fontdb);
}
// else {
// debug!("其他情况 = {}", default_font_family);
// default_font_family = fallback_font_family;
// }
}

fontdb.set_serif_family(&default_font_family);
Expand All @@ -121,7 +110,7 @@ fn set_font_families(font_options: &JsFontOptions, fontdb: &mut Database) {
fontdb.set_fantasy_family(&default_font_family);
fontdb.set_monospace_family(&default_font_family);

debug!("📝 defaultFontFamily = {}", default_font_family);
debug!("📝 default_font_family = '{}'", default_font_family);

#[cfg(not(target_arch = "wasm32"))]
find_and_debug_font_path(fontdb, default_font_family.as_str())
Expand Down Expand Up @@ -224,14 +213,10 @@ fn get_first_font_family_or_fallback(fontdb: &mut Database) -> String {
.unwrap_or(&face.families[0]);

default_font_family = base_family.0.clone();
debug!(
"📝 get_first_font_family 找到字体了 = {}",
default_font_family
);
}
None => {
debug!(
"📝 get_first_font_family 没找到字体 = {}",
"📝 get_first_font_family not found = '{}'",
default_font_family
);
}
Expand Down

0 comments on commit e193aa6

Please sign in to comment.