Skip to content

Commit

Permalink
fix(android, react, vue): add font load state, change resolve from vo…
Browse files Browse the repository at this point in the history
…id to string
  • Loading branch information
Cyunong committed Oct 22, 2024
1 parent ce1f0d6 commit 370f9ab
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ export default class LoadFontExample extends React.Component {
async loadFont() {
this.setState({ fontFamily: this.state.inputFontFamily });
await FontLoaderModule.load(this.state.fontFamily, this.state.fontUrl)
.then(() => {
this.setState({ loadState: 'Success' });
.then((result) => {
this.setState({ loadState: result });
})
.catch((error) => {
this.setState({ loadState: error });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,8 +454,7 @@ export default {
console.log('fontUrl:', this.fontUrl)
let result;
try {
await Vue.Native.FontLoader.load(this.fontFamily, this.fontUrl);
result = 'success';
result = await Vue.Native.FontLoader.load(this.fontFamily, this.fontUrl);
} catch (error) {
result = error.message;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,7 @@ export default defineComponent({
console.log('load fontUrl:', fontUrl.value)
let result;
try {
await Native.FontLoader.load(fontFamily.value, fontUrl.value);
result = 'success';
result = await Native.FontLoader.load(fontFamily.value, fontUrl.value);
} catch (error) {
result = error.message;
}
Expand Down
4 changes: 2 additions & 2 deletions driver/js/packages/hippy-vue-next/src/runtime/native/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export interface NativeApiType {
};

FontLoader: {
load: (fontFamily: string, url: string) => Promise<undefined>;
load: (fontFamily: string, url: string) => Promise<string>;
};

// include window and screen info
Expand Down Expand Up @@ -528,7 +528,7 @@ export const Native: NativeApiType = {
* @param fontFamily
* @param url - font url
*/
load(fontFamily, url): Promise<undefined> {
load(fontFamily: string, url: string): Promise<string> {
return Native.callNativeWithPromise.call(
this,
'FontLoaderModule',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
*/

export interface FontLoaderModule {
load: (fontFamily: string, url: string) => undefined;
load: (fontFamily: string, url: string) => string;
}
2 changes: 1 addition & 1 deletion driver/js/packages/hippy-vue/src/runtime/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ const Native: NeedToTyped = {
* @param {string} fontFamily - The font family to download,
* @param {string} url - The url where to download the font.
*/
load(fontFamily: NeedToTyped, url: NeedToTyped) {
load(fontFamily: string, url: string) {
return callNativeWithPromise.call(this, 'FontLoaderModule', 'load', fontFamily, url);
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,31 +38,32 @@
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

public class FontLoader {

private final WeakReference<NativeRender> mNativeRenderRef;
private final WeakReference<VfsManager> mVfsManager;
private final File mFontDir;
private final File mFontUrlDictPath;
private Map<String, String> mConcurrentFontUrlDict;
private final Set<String> mConcurrentFontsLoaded;
private final Set<String> mConcurrentUrlsLoading;
private final File mFontUrlMapPath;
private Map<String, String> mConcurrentFontUrlMap;
private final Map<String, FontLoadState> mConcurrentFontLoadStateMap;
private static final String[] ALLOWED_EXTENSIONS = {"otf", "ttf"};
private static final String FONT_DIR_NAME = "HippyFonts";
private static final String FONT_URL_DICT_NAME = "fontUrlDict.ser";
private static final String FONT_URL_MAP_NAME = "fontUrlMap.ser";

public enum FontLoadState {
FONT_LOADING,
FONT_LOADED
}


public FontLoader(VfsManager vfsManager, NativeRender nativeRender) {
mNativeRenderRef = new WeakReference<>(nativeRender);
mVfsManager = new WeakReference<>(vfsManager);
mFontDir = new File(ContextHolder.getAppContext().getCacheDir(), FONT_DIR_NAME);
mFontUrlDictPath = new File(mFontDir, FONT_URL_DICT_NAME);
mConcurrentFontsLoaded = new CopyOnWriteArraySet<>();
mConcurrentUrlsLoading = new CopyOnWriteArraySet<>();
mFontUrlMapPath = new File(mFontDir, FONT_URL_MAP_NAME);
mConcurrentFontLoadStateMap = new ConcurrentHashMap<>();
}

private boolean saveFontFile(byte[] byteArray, String fileName, Promise promise) {
Expand All @@ -78,7 +79,7 @@ private boolean saveFontFile(byte[] byteArray, String fileName, Promise promise)
try (FileOutputStream fos = new FileOutputStream(fontFile)) {
fos.write(byteArray);
if (promise != null) {
promise.resolve(null);
promise.resolve(fileName + " download success!");
}
return true;
} catch (IOException e) {
Expand All @@ -90,16 +91,17 @@ private boolean saveFontFile(byte[] byteArray, String fileName, Promise promise)
}

public boolean isFontLoaded(String fontFamily) {
return mConcurrentFontsLoaded.contains(fontFamily);
return fontFamily != null &&
mConcurrentFontLoadStateMap.get(fontFamily) == FontLoadState.FONT_LOADED;
}

private void saveFontUrlDictFile() {
try (FileOutputStream fos = new FileOutputStream(mFontUrlDictPath);
private void saveFontUrlMapFile() {
try (FileOutputStream fos = new FileOutputStream(mFontUrlMapPath);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(mConcurrentFontUrlDict);
LogUtils.d("FontLoader", "Save fontUrlDict.ser success");
oos.writeObject(mConcurrentFontUrlMap);
LogUtils.d("FontLoader", "Save fontUrlMap.ser success");
} catch (IOException e) {
LogUtils.d("FontLoader", "Save fontUrlDict.ser failed");
LogUtils.d("FontLoader", "Save fontUrlMap.ser failed");
}
}

Expand All @@ -115,24 +117,24 @@ public static String getFileExtension(String url) {
}

public boolean loadIfNeeded(final String fontFamily, final String fontUrl, int rootId) {
if (mConcurrentFontUrlDict == null) {
Map<String, String> fontUrlDict;
try (FileInputStream fis = new FileInputStream(mFontUrlDictPath);
if (mConcurrentFontUrlMap == null) {
Map<String, String> fontUrlMap;
try (FileInputStream fis = new FileInputStream(mFontUrlMapPath);
ObjectInputStream ois = new ObjectInputStream(fis)) {
fontUrlDict = (Map<String, String>) ois.readObject();
fontUrlMap = (Map<String, String>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
fontUrlDict = new HashMap<>();
fontUrlMap = new HashMap<>();
}
mConcurrentFontUrlDict = new ConcurrentHashMap<>(fontUrlDict);
mConcurrentFontUrlMap = new ConcurrentHashMap<>(fontUrlMap);
}
String fontFileName = mConcurrentFontUrlDict.get(fontUrl);
String fontFileName = mConcurrentFontUrlMap.get(fontUrl);
if (fontFileName != null) {
File fontFile = new File(mFontDir, fontFileName);
if (fontFile.exists()) {
return false;
}
}
if (mConcurrentUrlsLoading.contains(fontUrl)) {
if (mConcurrentFontLoadStateMap.containsKey(fontFamily)) {
return false;
}
loadAndRefresh(fontFamily, fontUrl, rootId, null);
Expand All @@ -149,7 +151,7 @@ public void loadAndRefresh(final String fontFamily, final String fontUrl, int ro
}
return;
}
mConcurrentUrlsLoading.add(fontUrl);
mConcurrentFontLoadStateMap.put(fontFamily, FontLoadState.FONT_LOADING);
mVfsManager.get().fetchResourceAsync(fontUrl, null, null,
new FetchResourceCallback() {
@Override
Expand All @@ -158,24 +160,27 @@ public void onFetchCompleted(@NonNull final ResourceDataHolder dataHolder) {
if (dataHolder.resultCode
!= ResourceDataHolder.RESOURCE_LOAD_SUCCESS_CODE || bytes == null
|| bytes.length <= 0) {
mConcurrentFontLoadStateMap.remove(fontFamily);
if (promise != null) {
promise.reject("Fetch font file failed, url=" + fontUrl);
}
} else {
String fileName = fontFamily + getFileExtension(fontUrl);
if (saveFontFile(bytes, fileName, promise)) {
LogUtils.d("FontLoader", "Fetch font file success");
mConcurrentFontsLoaded.add(fontFamily);
mConcurrentFontUrlDict.put(fontUrl, fileName);
saveFontUrlDictFile();
mConcurrentFontLoadStateMap.put(fontFamily, FontLoadState.FONT_LOADED);
mConcurrentFontUrlMap.put(fontUrl, fileName);
saveFontUrlMapFile();
TypeFaceUtil.clearFontCache(fontFamily);
NativeRender nativeRender = mNativeRenderRef.get();
if (nativeRender != null) {
nativeRender.refreshTextWindow(rootId);
}
}
else {
mConcurrentFontLoadStateMap.remove(fontFamily);
}
}
mConcurrentUrlsLoading.remove(fontUrl);
dataHolder.recycle();
}

Expand Down

0 comments on commit 370f9ab

Please sign in to comment.